'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Header } from '@/app/components/Header';
import { Footer } from '@/app/components/Footer';
import { Button } from '@/app/components/Button';
import api from '@/lib/api';
import { getVideoEmbedSrc } from '@/lib/videoEmbed';

export default function ProgramPage() {
  const params = useParams();
  const slug = params?.slug as string;
  
  const [thematicArea, setThematicArea] = useState<any>(null);
  const [projects, setProjects] = useState<any[]>([]);
  const [allThematicAreas, setAllThematicAreas] = useState<any[]>([]);
  const [totalProjectsCount, setTotalProjectsCount] = useState<number>(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isVisible, setIsVisible] = useState(false);
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState<string>('');

  // Helper function to normalize color values
  const normalizeColor = (color: string | null | undefined, fallback: string = '#4A90E2'): string => {
    if (!color) return fallback;
    // If it's already a valid hex color with #, return as is
    if (color.startsWith('#')) {
      // Validate hex color format
      return /^#[0-9A-F]{6}$/i.test(color) ? color : fallback;
    }
    // If it's a hex color without #, add it
    if (/^[0-9A-F]{6}$/i.test(color)) {
      return `#${color}`;
    }
    // If it looks like a CSS color name or other format, try to use it
    // Otherwise return fallback
    return fallback;
  };

  // Helper function to lighten a hex color
  const lightenColor = (hex: string, percent: number = 20): string => {
    // Remove # if present
    const color = hex.replace('#', '');
    
    // Parse RGB
    const r = parseInt(color.substring(0, 2), 16);
    const g = parseInt(color.substring(2, 4), 16);
    const b = parseInt(color.substring(4, 6), 16);
    
    // Lighten each component
    const lightenAmount = percent / 100;
    const newR = Math.round(r + (255 - r) * lightenAmount);
    const newG = Math.round(g + (255 - g) * lightenAmount);
    const newB = Math.round(b + (255 - b) * lightenAmount);
    
    // Convert back to hex
    return `#${newR.toString(16).padStart(2, '0')}${newG.toString(16).padStart(2, '0')}${newB.toString(16).padStart(2, '0')}`;
  };

  // Get the background color from primary SDG
  const getSDGBackgroundColor = (): string => {
    return normalizeColor(
      thematicArea?.primary_sdg?.color,
      '#4A90E2'
    );
  };

  // Get muted/desaturated color for left side (icon + title panel)
  const getLeftSideColor = (): string => {
    const baseColor = getSDGBackgroundColor();
    const color = baseColor.replace('#', '');
    const r = parseInt(color.substring(0, 2), 16);
    const g = parseInt(color.substring(2, 4), 16);
    const b = parseInt(color.substring(4, 6), 16);
    const gray = (r + g + b) / 3;
    const desaturateAmount = 0.4;
    const newR = Math.round(r * desaturateAmount + gray * (1 - desaturateAmount));
    const newG = Math.round(g * desaturateAmount + gray * (1 - desaturateAmount));
    const newB = Math.round(b * desaturateAmount + gray * (1 - desaturateAmount));
    const lightenFactor = 0.7;
    const finalR = Math.round(newR + (255 - newR) * lightenFactor);
    const finalG = Math.round(newG + (255 - newG) * lightenFactor);
    const finalB = Math.round(newB + (255 - newB) * lightenFactor);
    return `#${finalR.toString(16).padStart(2, '0')}${finalG.toString(16).padStart(2, '0')}${finalB.toString(16).padStart(2, '0')}`;
  };

  // Get the lightest shade of the SDG color for the right side (e.g. light red for red)
  const getRightSideSDGColor = (): string => {
    const baseColor = getSDGBackgroundColor();
    const color = baseColor.replace('#', '');
    const r = parseInt(color.substring(0, 2), 16);
    const g = parseInt(color.substring(2, 4), 16);
    const b = parseInt(color.substring(4, 6), 16);
    // Mix heavily with white for lowest shade (~88% white, 12% tint)
    const mix = 0.88;
    const finalR = Math.round(r * (1 - mix) + 255 * mix);
    const finalG = Math.round(g * (1 - mix) + 255 * mix);
    const finalB = Math.round(b * (1 - mix) + 255 * mix);
    return `#${finalR.toString(16).padStart(2, '0')}${finalG.toString(16).padStart(2, '0')}${finalB.toString(16).padStart(2, '0')}`;
  };

  // Helper function to get SDG icon path from local images
  const getSDGIconPath = (sdgNumber: number, sdgTitle?: string): string => {
    // Map SDG numbers to image filenames
    const sdgImageMap: Record<number, string> = {
      1: 'no_poverty.png',
      2: 'zero_hunger.png',
      3: 'good_health_and_well_being.png',
      4: 'quality_education.png',
      5: 'gender_quality.png',
      6: 'clean_water_and_sanitation.png',
      7: 'clean_energy.png',
      8: 'economic_growth.png',
      9: 'infrastructure_9.png',
      10: 'reduced_inequalities.png',
      11: 'sunstainable_cities_and_communications.png',
      12: 'responsible_consumption_and_production.png',
      13: 'climate_action.png',
      14: 'life_below_water.png',
      15: 'life_on_land.png',
      16: 'peace_and_justice_strong_instituions.png',
      17: 'partnership_for_the_goals.png',
    };

    const filename = sdgImageMap[sdgNumber] || null;
    if (filename) {
      return `/images/sdgs/${filename}`;
    }
    
    // Fallback: try to generate filename from title if number mapping fails
    if (sdgTitle) {
      const slug = sdgTitle.toLowerCase().replace(/[^a-z0-9]+/g, '_');
      return `/images/sdgs/${slug}.png`;
    }
    
    return '';
  };

  // Helper function to get thematic area icon path from local images (same pattern as SDG icons)
  const getThematicAreaIconPath = (slug?: string, title?: string): string | null => {
    // Map thematic area slugs to filenames in public/images/thematic_area_icons (exact filenames as on disk)
    const thematicAreaIconMap: Record<string, string> = {
      'health': 'Health.png',
      'nutrition': 'Nutrition.png',
      'sbc': 'SBC.png',
      'wash': 'Waash.png',
      'education': 'Education.png',
      'food-security-agriculture': 'Food Srcurity.png',
      'protection': 'Protection.png',
      'emergency-response': 'Emergency Response.png',
      'gender': 'Gender.png',
      'infrastructure': 'Insfrastructure.png',
      'youth-support': 'Youth.png',
    };

    if (slug && thematicAreaIconMap[slug]) {
      return `/images/thematic_area_icons/${thematicAreaIconMap[slug]}`;
    }
    // Fallback: try title (e.g. "Health" -> "Health.png")
    if (title) {
      const normalized = title.trim();
      return `/images/thematic_area_icons/${normalized}.png`;
    }
    return null;
  };

  useEffect(() => {
    if (slug) {
      fetchThematicArea();
      fetchAllThematicAreas();
      fetchTotalProjectsCount();
    }
  }, [slug]);

  useEffect(() => {
    if (!loading && thematicArea) {
      setTimeout(() => setIsVisible(true), 100);
    }
  }, [loading, thematicArea]);

  const fetchThematicArea = async () => {
    try {
      setLoading(true);
      setError(null);
      setIsVisible(false);
      const data: any = await api.getThematicArea(slug);
      
      setThematicArea(data);
      if (data.projects && Array.isArray(data.projects)) {
        setProjects(data.projects);
      } else {
        setProjects([]);
      }
    } catch (err: any) {
      console.error('Error fetching thematic area:', err);
      setError(err?.message || 'Failed to load thematic area');
    } finally {
      setLoading(false);
    }
  };

  const fetchAllThematicAreas = async () => {
    try {
      const data: any = await api.getThematicAreas();
      const areas = Array.isArray(data) ? data : (data?.data || []);
      const activeAreas = areas
        .filter((area: any) => area.status === 'active')
        .sort((a: any, b: any) => (a.order || 0) - (b.order || 0));
      setAllThematicAreas(activeAreas);
    } catch (err: any) {
      console.error('Error fetching all thematic areas:', err);
    }
  };

  const fetchTotalProjectsCount = async () => {
    try {
      // The fetchApi utility already extracts data.data, so this will be an array
      const allProjects: any = await api.getProjects({ paginate: false });
      console.log('All projects from API:', allProjects);
      
      // Ensure it's an array
      const projectsArray = Array.isArray(allProjects) ? allProjects : [];
      
      // Filter for active projects
      const activeProjects = projectsArray.filter((p: any) => p.status === 'active');
      
      setTotalProjectsCount(activeProjects.length);
      console.log('Total active projects count:', activeProjects.length);
    } catch (err: any) {
      console.error('Error fetching total projects:', err);
      setTotalProjectsCount(0);
    }
  };


  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mb-4"></div>
            <p className="text-lg text-neutral-600">Loading thematic area...</p>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  if (error || !thematicArea) {
    return (
      <div className="min-h-screen bg-white">
        <Header />
        <div className="min-h-[80vh] flex items-center justify-center px-4">
          <div className="text-center max-w-2xl">
            <h1 className="text-4xl md:text-5xl font-bold text-primary-500 mb-4">
              {error ? 'Error Loading Thematic Area' : 'Thematic Area Not Found'}
            </h1>
            <p className="text-lg md:text-xl text-neutral-600 mb-8">
              {error || 'The thematic area you\'re looking for doesn\'t exist.'}
            </p>
            <Link 
              href="/#what-we-do"
              className="inline-flex items-center gap-2 px-6 py-3 bg-primary-500 text-neutral-900 rounded-lg hover:bg-primary-700 transition-colors font-semibold"
            >
              Back to Programs
            </Link>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  // Placeholder images
  const placeholderImages: Record<string, string> = {
    education: '/images/hero/slider-1.webp',
    'youth-support': '/images/hero/slider-2.webp',
    'food-security-agriculture': '/images/hero/slider-3.webp',
    default: '/images/hero/slider-1.webp',
  };

  const getPlaceholderImage = (slug: string) => {
    return placeholderImages[slug as keyof typeof placeholderImages] || placeholderImages.default;
  };

  const heroImage = thematicArea.image_large || thematicArea.image_medium || thematicArea.image || getPlaceholderImage(thematicArea.slug || 'default');
  let iconElement: React.ReactElement | null = null;
  if (thematicArea.icon) {
    iconElement = <div className="w-10 h-10" dangerouslySetInnerHTML={{ __html: thematicArea.icon }} />;
  }

  return (
    <div className="min-h-screen bg-white">
      <Header />
      
      {/* Header with Breadcrumb and Title */}
      <section className="bg-gradient-to-br from-neutral-50 via-white to-neutral-50 pt-28 pb-4">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Breadcrumb */}
          <nav className={`mb-6 transition-all duration-700 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-4'}`} aria-label="Breadcrumb">
            <ol className="flex items-center space-x-2 text-sm">
              <li>
                <Link href="/" className="text-neutral-600 hover:text-primary-600 transition-colors duration-200 flex items-center gap-1.5">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                  </svg>
                  <span>Home</span>
                </Link>
              </li>
              <li className="text-neutral-400">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </li>
              <li>
                <Link href="/#what-we-do" className="text-neutral-600 hover:text-primary-600 transition-colors duration-200">
                  What We Do
                </Link>
              </li>
              <li className="text-neutral-400">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </li>
              <li className="text-primary-600 font-medium">{thematicArea.title}</li>
            </ol>
          </nav>

          {/* Thematic Area Title */}
          <div className={`transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
            <h1 className="text-4xl md:text-5xl font-black text-neutral-900 leading-tight mb-2">
              {thematicArea.title}
            </h1>
            {thematicArea.stats && (
              <div className="flex items-center gap-2 text-primary-700">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span className="text-lg font-bold">{thematicArea.stats}</span>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* SDG Goals Section - Concise, light shade on right */}
      {thematicArea.sdgs && thematicArea.sdgs.length > 0 && (
        <section id={thematicArea.slug} className="pt-6 pb-6 md:pt-8 md:pb-8 bg-neutral-50 relative overflow-hidden">
          <div className={`relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-12'}`}>
            <div className="flex flex-col lg:flex-row gap-0 rounded-2xl overflow-hidden shadow-xl relative">
              <div className="absolute inset-0 rounded-2xl border-2 border-white/40 pointer-events-none" />
              
              {/* Left Side - Icon and Title (muted) */}
              <div 
                className="lg:w-52 flex-shrink-0 flex flex-col items-center justify-center text-center p-5 lg:p-6 relative"
                style={{ backgroundColor: getLeftSideColor() }}
              >
                <div className="absolute top-0 right-0 w-20 h-20 bg-white/10 rounded-full -mr-10 -mt-10" />
                <div className="w-20 h-20 lg:w-24 lg:h-24 mb-3 flex items-center justify-center relative z-10 bg-white/40 backdrop-blur-sm rounded-2xl p-2.5 shadow-lg">
                  {getThematicAreaIconPath(thematicArea.slug, thematicArea.title) ? (
                    <img 
                      src={getThematicAreaIconPath(thematicArea.slug, thematicArea.title)!} 
                      alt={thematicArea.title}
                      className="w-full h-full object-contain"
                    />
                  ) : thematicArea.icon ? (
                    <div 
                      className="w-full h-full flex items-center justify-center [&_svg]:w-full [&_svg]:h-full [&_svg]:text-neutral-700 [&_path]:stroke-neutral-700"
                      dangerouslySetInnerHTML={{ __html: thematicArea.icon }} 
                    />
                  ) : thematicArea.image ? (
                    <img src={thematicArea.image} alt={thematicArea.title} className="w-full h-full object-contain" />
                  ) : thematicArea.emoji ? (
                    <div className="text-6xl">{thematicArea.emoji}</div>
                  ) : (
                    <svg className="w-full h-full text-neutral-700" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z" />
                    </svg>
                  )}
                </div>
                <h2 className="text-xl lg:text-2xl font-bold text-neutral-800 leading-tight relative z-10">
                  {thematicArea.title}
                </h2>
                <div className="w-12 h-0.5 bg-neutral-400 rounded-full mt-2" />
              </div>

              {/* Right Side - Lightest shade of SDG color */}
              <div 
                className="flex-1 p-5 lg:p-6 relative"
                style={{ backgroundColor: getRightSideSDGColor() }}
              >
                <div className="absolute inset-0 opacity-[0.03]" style={{ backgroundImage: `radial-gradient(circle at 2px 2px, currentColor 1px, transparent 0)`, backgroundSize: '24px 24px' }} />
                <div className="grid grid-cols-1 md:grid-cols-12 gap-3 md:gap-4 mb-4 relative z-10">
                  {thematicArea.primary_sdg && (
                    <div className="md:col-span-3">
                      <h4 className="text-neutral-700 font-bold text-xs mb-2 uppercase tracking-wider">Primary Goal</h4>
                      {thematicArea.primary_sdg.number ? (
                        <img 
                          src={getSDGIconPath(thematicArea.primary_sdg.number, thematicArea.primary_sdg.title)} 
                          alt={thematicArea.primary_sdg.title}
                          className="w-full max-w-[90px] h-auto object-contain transform hover:scale-105 transition-transform duration-300 shadow-md rounded-lg"
                        />
                      ) : (
                        <div 
                          className="w-[90px] aspect-square rounded-lg flex items-center justify-center text-2xl font-bold text-white shadow-md"
                          style={{ backgroundColor: thematicArea.primary_sdg.color || '#1F2937' }}
                        >
                          {thematicArea.primary_sdg.number}
                        </div>
                      )}
                    </div>
                  )}
                  {thematicArea.additional_sdgs && thematicArea.additional_sdgs.length > 0 && (
                    <div className="md:col-span-9">
                      <h4 className="text-neutral-700 font-bold text-xs mb-2 uppercase tracking-wider">Additional Goals</h4>
                      <div className="flex flex-wrap gap-2 md:gap-3">
                        {thematicArea.additional_sdgs.map((sdg: any) => (
                          <div key={sdg.id} className="group relative">
                            {sdg.number ? (
                              <img 
                                src={getSDGIconPath(sdg.number, sdg.title)} 
                                alt={sdg.title}
                                className="w-[70px] h-[70px] object-contain rounded-lg transform group-hover:scale-105 transition-transform duration-300 shadow-sm"
                              />
                            ) : (
                              <div 
                                className="w-[70px] h-[70px] rounded-lg flex items-center justify-center text-lg font-bold text-white shadow-sm"
                                style={{ backgroundColor: sdg.color || '#1F2937' }}
                              >
                                {sdg.number}
                              </div>
                            )}
                            <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1.5 bg-neutral-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap pointer-events-none z-10">
                              {sdg.title}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
                {thematicArea.primary_sdg?.how_we_achieve && (
                  <div className="text-neutral-800 border-t border-neutral-300/50 pt-4 mt-2 relative z-10">
                    <h5 className="text-base lg:text-lg font-bold mb-2 text-neutral-800">
                      How We Achieve These Goals
                    </h5>
                    <div 
                      className="text-neutral-700 text-sm leading-relaxed text-justify [&_p]:mb-2 [&_p]:text-justify [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:mb-2 [&_li]:mb-1"
                      dangerouslySetInnerHTML={{ __html: thematicArea.primary_sdg.how_we_achieve }}
                    />
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Video (after SDG section; same width as SDG block) */}
      {thematicArea.video_link && (
        <section
          className="pt-2 md:pt-4 pb-6 md:pb-8 bg-neutral-50 relative overflow-hidden"
          aria-label={`${thematicArea.title} video`}
        >
          <div className={`relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-12'}`}>
            {(() => {
              const embedSrc = getVideoEmbedSrc(thematicArea.video_link);
              if (embedSrc) {
                return (
                  <div className="relative w-full overflow-hidden shadow-lg border border-neutral-200 bg-neutral-900 aspect-video rounded-l-none rounded-r-2xl">
                    <iframe
                      src={embedSrc}
                      title={`${thematicArea.title} — video`}
                      className="absolute inset-0 w-full h-full"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                      allowFullScreen
                      loading="lazy"
                      referrerPolicy="strict-origin-when-cross-origin"
                    />
                  </div>
                );
              }
              return (
                <div className="w-full rounded-l-none rounded-r-2xl border border-neutral-200 bg-white p-6 text-center shadow-lg">
                  <p className="text-neutral-600 mb-4 text-sm">
                    This video link is not supported for embedded playback. Open it in a new tab to watch.
                  </p>
                  <a
                    href={thematicArea.video_link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 px-5 py-2.5 bg-primary-500 text-neutral-900 rounded-lg font-semibold hover:bg-primary-700 transition-colors"
                  >
                    Open video
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                    </svg>
                  </a>
                </div>
              );
            })()}
          </div>
        </section>
      )}

      {/* Description Section (if no SDGs or as fallback) */}
      {(!thematicArea.sdgs || thematicArea.sdgs.length === 0) && (
        <section className={`py-16 md:py-24 bg-white transition-all duration-1000 delay-100 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-12">
              {/* Main Content */}
              <div className="lg:col-span-2">
                <div className="prose prose-lg max-w-none">
                  <h2 className="text-3xl md:text-4xl font-bold text-neutral-900 mb-6">
                    About {thematicArea.title}
                  </h2>
                  <div className="text-lg text-neutral-700 leading-relaxed space-y-4">
                    <p>{thematicArea.description}</p>
                  </div>
                </div>
              </div>

              {/* Sidebar */}
              <div className="lg:col-span-1">
                <div className="sticky top-24">
                  <div className="bg-neutral-50 rounded-lg p-6 border border-neutral-200">
                    <h3 className="text-lg font-bold text-neutral-900 mb-4">Quick Facts</h3>
                    {thematicArea.stats && (
                      <div className="space-y-4">
                        <div>
                          <div className="text-sm text-neutral-600 mb-1">Impact</div>
                          <div className="text-2xl font-bold text-primary-600">{thematicArea.stats}</div>
                        </div>
                      </div>
                    )}
                    <div className="mt-6 pt-6 border-t border-neutral-200">
                      <Button 
                        variant="primary" 
                        size="lg" 
                        className="w-full"
                      >
                        Support This Work
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Projects Section - Professional Table Design */}
      {projects && projects.length > 0 && (
        <section className="pt-8 pb-16 md:pt-10 md:pb-20 bg-neutral-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            {/* Section Header with Stats */}
            <div className={`mb-10 transition-all duration-1000 delay-400 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
              <div className="text-center mb-6">
                <h2 className="text-4xl md:text-5xl font-bold text-primary-500 mb-6">
                  Active Projects 
                </h2>
              </div>

              {/* Stats Grid - Soft Colors */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                {/* Total Projects */}
                <div className="bg-neutral-100 rounded-xl p-6 border border-neutral-200 shadow-sm">
                  <div className="flex items-center justify-between mb-2">
                    <div className="text-neutral-700 text-sm font-semibold">Total Projects</div>
                    <svg className="w-7 h-7 text-neutral-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                  </div>
                  <div className="text-3xl font-bold text-neutral-900 mb-1">250+</div>
                  <div className="text-neutral-600 text-xs">Projects implemented</div>
                </div>

                {/* Thematic Area Projects */}
                <div className="bg-primary-50 rounded-xl p-6 border border-primary-100 shadow-sm">
                  <div className="flex items-center justify-between mb-2">
                    <div className="text-primary-600 text-sm font-semibold">{thematicArea.title}</div>
                    <svg className="w-7 h-7 text-primary-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                  </div>
                  <div className="text-3xl font-bold text-primary-900 mb-1">{projects.length}</div>
                  <div className="text-primary-600 text-xs">Projects in this area</div>
                </div>

                {/* Beneficiaries */}
                <div className="bg-green-50 rounded-xl p-6 border border-green-100 shadow-sm">
                  <div className="flex items-center justify-between mb-2">
                    <div className="text-green-600 text-sm font-semibold">Beneficiaries</div>
                    <svg className="w-7 h-7 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                    </svg>
                  </div>
                  <div className="text-3xl font-bold text-green-900 mb-1">
                    {projects.reduce((sum: number, p: any) => sum + (p.beneficiaries_count || 0), 0).toLocaleString()}
                  </div>
                  <div className="text-green-600 text-xs">People reached</div>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-5 gap-8">
              {/* Sidebar Filters */}
              <aside className={`lg:col-span-1 transition-all duration-1000 delay-500 ${isVisible ? 'opacity-100 translate-x-0' : 'opacity-0 -translate-x-8'}`}>
                <div className="bg-white rounded-2xl p-6 border border-neutral-200 shadow-sm sticky top-24">
                  <h3 className="text-lg font-bold text-neutral-900 mb-6 flex items-center gap-2">
                    <svg className="w-5 h-5 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
                    </svg>
                    Filters
                  </h3>

                  {/* Search */}
                  <div className="mb-6">
                    <label className="block text-sm font-semibold text-neutral-700 mb-2">
                      Search Projects
                    </label>
                    <div className="relative">
                      <input
                        type="text"
                        placeholder="Search by name..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full px-4 py-2.5 pl-10 bg-white border border-neutral-300 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-primary-500 transition-all"
                      />
                      <svg className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                      </svg>
                    </div>
                  </div>

                  {/* Status Filter */}
                  <div className="mb-6">
                    <label className="block text-sm font-semibold text-neutral-700 mb-3">
                      Project Status
                    </label>
                    <div className="space-y-2">
                      {['all', 'active', 'completed', 'ongoing'].map((status) => (
                        <button
                          key={status}
                          onClick={() => setSelectedStatus(status)}
                          className={`w-full text-left px-4 py-2.5 rounded-lg transition-all duration-200 ${
                            selectedStatus === status
                              ? 'bg-primary-500 text-neutral-900 shadow-md'
                              : 'bg-white text-neutral-700 hover:bg-neutral-100 border border-neutral-200'
                          }`}
                        >
                          <span className="font-medium capitalize">{status}</span>
                          {status !== 'all' && (
                            <span className={`ml-2 text-xs ${selectedStatus === status ? 'text-white/80' : 'text-neutral-500'}`}>
                              ({projects.filter((p: any) => p.status && p.status.toLowerCase() === status.toLowerCase()).length})
                            </span>
                          )}
                          {status === 'all' && (
                            <span className={`ml-2 text-xs ${selectedStatus === status ? 'text-white/80' : 'text-neutral-500'}`}>
                              ({projects.length})
                            </span>
                          )}
                        </button>
                      ))}
                    </div>
                  </div>

                </div>
              </aside>

              {/* Projects Table */}
              <div className="lg:col-span-4">
                {(() => {
                  // Filter projects (case-insensitive status matching)
                  const filteredProjects = projects.filter((project: any) => {
                    const matchesStatus = selectedStatus === 'all' || 
                      (project.status && project.status.toLowerCase() === selectedStatus.toLowerCase());
                    const matchesSearch = searchQuery === '' || 
                      (project.name && project.name.toLowerCase().includes(searchQuery.toLowerCase())) ||
                      (project.description && project.description.toLowerCase().includes(searchQuery.toLowerCase()));
                    return matchesStatus && matchesSearch;
                  });

                  if (filteredProjects.length === 0) {
                    return (
                      <div className="text-center py-16 bg-white rounded-2xl border border-neutral-200">
                        <div className="inline-flex items-center justify-center w-20 h-20 bg-neutral-100 rounded-full mb-6">
                          <svg className="w-10 h-10 text-neutral-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                          </svg>
                        </div>
                        <h3 className="text-2xl font-bold text-neutral-900 mb-2">No Projects Found</h3>
                        <p className="text-neutral-600">Try adjusting your filters or search query</p>
                      </div>
                    );
                  }

                  return (
                    <div className="bg-white rounded-2xl shadow-sm border border-neutral-200 overflow-hidden">
                      {/* Table Header */}
                      <div className="bg-neutral-50 border-b border-neutral-200 px-6 py-4">
                        <div className="flex items-center justify-between">
                          <h3 className="text-lg font-bold text-neutral-900">
                            {filteredProjects.length} {filteredProjects.length === 1 ? 'Project' : 'Projects'}
                          </h3>
                          <span className="text-sm text-neutral-600">
                            Showing {filteredProjects.length} of {projects.length} total
                          </span>
                        </div>
                      </div>

                      {/* Table */}
                      <div className="overflow-x-auto">
                        <table className="w-full">
                          <thead className="bg-neutral-50 border-b border-neutral-200">
                            <tr>
                              <th className="px-6 py-4 text-left text-xs font-bold text-neutral-700 uppercase tracking-wider">Title</th>
                              <th className="px-6 py-4 text-left text-xs font-bold text-neutral-700 uppercase tracking-wider">Donor</th>
                              <th className="px-6 py-4 text-left text-xs font-bold text-neutral-700 uppercase tracking-wider">Duration</th>
                              <th className="px-6 py-4 text-left text-xs font-bold text-neutral-700 uppercase tracking-wider">Beneficiaries</th>
                              <th className="px-6 py-4 text-left text-xs font-bold text-neutral-700 uppercase tracking-wider">Status</th>
                              <th className="px-6 py-4 text-right text-xs font-bold text-neutral-700 uppercase tracking-wider">Action</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-neutral-200 bg-white">
                            {filteredProjects.map((project: any, index: number) => {
                              const statusColors: Record<string, string> = {
                                'active': 'bg-green-100 text-green-700 border-green-200',
                                'completed': 'bg-blue-100 text-blue-700 border-blue-200',
                                'ongoing': 'bg-yellow-100 text-yellow-700 border-yellow-200',
                                'planned': 'bg-gray-100 text-gray-700 border-gray-200',
                                'suspended': 'bg-red-100 text-red-700 border-red-200'
                              };
                              
                              return (
                                <tr
                                  key={project.id || index}
                                  className="group hover:bg-neutral-50 transition-colors duration-200"
                                >
                                  {/* Title Column */}
                                  <td className="px-6 py-4">
                                    <Link href={`/projects/${project.slug}`} className="text-neutral-700 hover:text-neutral-900 font-medium border-b border-neutral-300 hover:border-neutral-700 pb-0.5 transition-colors">
                                      {project.name}
                                    </Link>
                                  </td>

                                  {/* Donor Column */}
                                  <td className="px-6 py-4">
                                    {project.donor ? (
                                      <div className="flex items-center gap-2">
                                        <svg className="w-4 h-4 text-primary-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                        </svg>
                                        <span className="text-sm text-neutral-700">{project.donor.name}</span>
                                      </div>
                                    ) : (
                                      <span className="text-sm text-neutral-400">-</span>
                                    )}
                                  </td>

                                  {/* Duration Column */}
                                  <td className="px-6 py-4">
                                    {project.start_date && project.end_date ? (
                                      <div className="text-sm text-neutral-700">
                                        <div>{new Date(project.start_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}</div>
                                        <div className="text-xs text-neutral-500">to</div>
                                        <div>{new Date(project.end_date).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}</div>
                                      </div>
                                    ) : (
                                      <span className="text-sm text-neutral-400">-</span>
                                    )}
                                  </td>

                                  {/* Beneficiaries Column */}
                                  <td className="px-6 py-4">
                                    {project.beneficiaries_count ? (
                                      <div className="text-sm font-semibold text-neutral-900">
                                        {project.beneficiaries_count.toLocaleString()}
                                      </div>
                                    ) : (
                                      <span className="text-sm text-neutral-400">-</span>
                                    )}
                                  </td>

                                  {/* Status Column */}
                                  <td className="px-6 py-4">
                                    <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold border ${statusColors[project.status] || 'bg-gray-100 text-gray-700 border-gray-200'}`}>
                                      <span className="w-1.5 h-1.5 rounded-full bg-current mr-1.5"></span>
                                      {project.status.charAt(0).toUpperCase() + project.status.slice(1)}
                                    </span>
                                  </td>

                                  {/* Action Column */}
                                  <td className="px-6 py-4 text-right">
                                    <Link href={`/projects/${project.slug}`}>
                                      <button className="inline-flex items-center gap-2 px-4 py-2 bg-primary-500 hover:bg-primary-400 text-neutral-900 font-semibold rounded-lg transition-all duration-200 text-sm shadow-sm hover:shadow-md">
                                        <span>View</span>
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                        </svg>
                                      </button>
                                    </Link>
                                  </td>
                                </tr>
                              );
                            })}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  );
                })()}
              </div>
            </div>
          </div>
        </section>
      )}

      {/* No Projects Message */}
      {projects.length === 0 && (
        <section className="py-24 bg-gradient-to-b from-white to-neutral-50">
          <div className={`max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center transition-all duration-1000 delay-500 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
            <div className="max-w-2xl mx-auto">
              <div className="inline-flex items-center justify-center w-24 h-24 bg-gradient-to-br from-primary-100 to-primary-200 rounded-3xl mb-8 shadow-lg">
                <svg className="w-12 h-12 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
              </div>
              <h3 className="text-3xl md:text-4xl font-bold text-neutral-900 mb-4">No Projects Available Yet</h3>
              <p className="text-xl text-neutral-600 leading-relaxed mb-8">
                Projects for this thematic area are currently being developed. Check back soon for updates on our upcoming initiatives!
              </p>
              <div className="inline-flex items-center gap-2 px-6 py-3 bg-primary-100 text-primary-700 rounded-full text-sm font-semibold">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span>Coming Soon</span>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* CTA Section */}
      <section className="relative py-24 md:py-32 bg-gradient-to-br from-primary-600 via-primary-700 to-primary-800 text-white overflow-hidden">
        {/* Animated Background Elements */}
        <div className="absolute inset-0">
          <div className="absolute top-0 right-0 w-96 h-96 bg-white/10 rounded-full mix-blend-overlay filter blur-3xl animate-blob" />
          <div className="absolute bottom-0 left-0 w-96 h-96 bg-white/10 rounded-full mix-blend-overlay filter blur-3xl animate-blob animation-delay-2000" />
          <div className="absolute inset-0 opacity-10">
            <div className="absolute top-0 left-0 w-full h-full" style={{
              backgroundImage: `radial-gradient(circle at 2px 2px, white 1px, transparent 0)`,
              backgroundSize: '40px 40px'
            }} />
          </div>
        </div>
        
        <div className={`relative max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 text-center transition-all duration-1000 ${isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'}`}>
          {/* Icon */}
          <div className="inline-flex items-center justify-center w-20 h-20 bg-white/20 backdrop-blur-sm rounded-2xl mb-8">
            <svg className="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
            </svg>
          </div>

          <h2 className="text-4xl md:text-5xl lg:text-6xl font-bold mb-6 leading-tight">
            Support Our {thematicArea.title} Work
          </h2>
          
          <p className="text-xl md:text-2xl text-white/90 mb-12 max-w-3xl mx-auto leading-relaxed">
            Your donation helps us continue this vital work and reach more communities in need. Together, we can create lasting change.
          </p>
          
          <div className="flex flex-col sm:flex-row gap-6 justify-center items-center">
            <Link href="/donate">
              <button className="group px-10 py-5 bg-white hover:bg-neutral-50 text-primary-600 rounded-xl font-bold text-lg shadow-2xl hover:shadow-3xl transform hover:scale-105 transition-all duration-300 flex items-center gap-3">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                </svg>
                <span>Donate Now</span>
                <svg className="w-5 h-5 transform group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </button>
            </Link>
            <Link href="/#get-involved">
              <button className="group px-10 py-5 bg-white/10 hover:bg-white/20 backdrop-blur-sm text-white rounded-xl font-bold text-lg border-2 border-white/30 hover:border-white/50 transform hover:scale-105 transition-all duration-300 flex items-center gap-3">
                <span>Get Involved</span>
                <svg className="w-5 h-5 transform group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </button>
            </Link>
          </div>
        </div>
      </section>

      <Footer />
      
      <style jsx>{`
        @keyframes fadeInUp {
          from {
            opacity: 0;
            transform: translateY(30px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        @keyframes fadeIn {
          from {
            opacity: 0;
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        @keyframes blob {
          0%, 100% {
            transform: translate(0, 0) scale(1);
          }
          25% {
            transform: translate(20px, -50px) scale(1.1);
          }
          50% {
            transform: translate(-20px, 20px) scale(0.9);
          }
          75% {
            transform: translate(50px, 50px) scale(1.05);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.3s ease-in-out;
        }
        .animate-blob {
          animation: blob 7s infinite;
        }
        .animation-delay-2000 {
          animation-delay: 2s;
        }
        .animation-delay-4000 {
          animation-delay: 4s;
        }
      `}</style>
    </div>
  );
}
