/* eslint-disable */
import { useState, useEffect, useRef, useId } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowRight, BarChart, BookOpen, ChevronLeft, ChevronRight, Clock, Globe,
  ChevronDown, RadioTower, Rocket, Satellite, Star, Telescope, Users
} from '../components/icons/PhosphorIcons';
import useSEO from '../hooks/useSEO';
import ScrollReveal from '../components/ScrollReveal';
import LazyImage from '../components/LazyImage';
import BorderGlow from '../components/BorderGlow';
import SpotlightCard from '../components/SpotlightCard';
import StarBorder from '../components/StarBorder';
import AnimatedList from '../components/AnimatedList';
import HomeTestimonials from '../components/home/HomeTestimonials';
import WarmTooltip from '../components/WarmTooltip';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, Pagination, Navigation } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';


const programTabs = [
  { id: 'courses', label: 'Courses', icon: BookOpen },
  { id: 'live', label: 'Live Sessions', icon: Telescope },
  { id: 'labs', label: 'Labs & Clubs', icon: Rocket },
  { id: 'expeditions', label: 'Expeditions', icon: Globe },
];

import { API_BASE, parseApiResponse } from '../lib/apiClient';
import { getAutomaticEventStatus } from '../lib/eventStatus';
import { useSiteVisibility } from '../context/useSiteVisibility';

const WHATSAPP_COMMUNITY_URL = 'https://chat.whatsapp.com/GZaWhGp3gVD93h6g3rMiEp';

const capabilityItems = [
  'Live telemetry',
  'Tracking dashboards',
  'Astronomy clubs',
  'Mobile planetariums',
  'Telescope arrays',
  'Observatory labs',
  'Sky tools',
  'Student research',
  'Aerospace workshops',
  'Dark-sky expeditions',
];

function PartnerLogo({ partner, duplicate = false }) {
  const content = (
    <div
      className="mx-8 md:mx-12 flex items-center justify-center shrink-0 pt-4 outline-none cursor-pointer"
      tabIndex={duplicate ? -1 : 0}
      aria-hidden={duplicate || undefined}
      aria-label={duplicate ? undefined : `Partner organization: ${partner.name}`}
    >
      <img
        src={partner.logo || partner.url}
        alt={duplicate ? '' : `${partner.name} logo`}
        className="h-20 md:h-24 w-auto max-w-[190px] md:max-w-[230px] rounded-[22%] object-contain opacity-90 transition-all duration-300 hover:scale-105"
        loading="lazy"
      />
    </div>
  );

  if (duplicate) return content;

  return (
    <WarmTooltip content={partner.name} side="top" size="sm">
      {content}
    </WarmTooltip>
  );
}

const ecosystem = [
  {
    title: 'Astronomical Sky Tools',
    desc: {
      what: 'Live satellite tracking & interactive sky maps.',
      who: 'Students and amateur stargazers.',
      why: 'Conduct live night-sky observations.',
    },
    cta: 'Launch Sky Tools',
    path: '/astronomical-tools',
    image: '/assets/ecosystem-satellite.webp',
    icon: Satellite,
    accent: 'var(--v3-text-secondary)',
    glow: 'var(--v3-accent-glow)',
  },
  {
    title: 'School Infrastructure',
    desc: {
      what: 'Astronomy clubs, labs & mobile planetariums.',
      who: 'K-12 school educational institutions.',
      why: 'Integrate hands-on STEM space experiments.',
    },
    cta: 'Partner With Schools',
    path: '/services',
    image: '/assets/ecosystem-observatory.webp',
    icon: RadioTower,
    accent: 'var(--v3-accent)',
    glow: 'var(--v3-accent-glow)',
  },
  {
    title: 'Research Pathways',
    desc: {
      what: 'Portal access & certification tracking.',
      who: 'Individual student space explorers.',
      why: 'Transition to professional datasets.',
    },
    cta: 'Enter Portal',
    path: '/dashboard',
    image: '/assets/ecosystem-research.webp',
    icon: BarChart,
    accent: 'var(--v3-info)',
    glow: 'var(--v3-accent-glow)',
  },
];

const faqs = [
  {
    category: 'Getting Started',
    question: 'How should we start?',
    answer: 'Explore our online programs catalog or contact our academic outreach team. We help match the right curriculum format to the age group, school size, and learning goals.',
  },
  {
    category: 'Courses',
    question: 'Who are CosmaNeX programs built for?',
    answer: 'Our curriculum is designed for K-12 students, schools, science educators, and young space enthusiasts who want to transition from passive reading to practical astronomy, STEM experiments, and aerospace learning.',
  },
  {
    category: 'Schools',
    question: 'Do you work directly with schools?',
    answer: 'Yes. We set up active astronomy clubs, mobile planetarium experiences, theme-based space workshops, Khagolshala laboratories, observatory setups, and curriculum-linked projects.',
  },
  {
    category: 'Certificates',
    question: 'Do students receive certificates?',
    answer: 'Yes. All online courses (such as iAstronomer) and camp participants receive certified, shareable credentials. School programs also provide certificates during exhibitions.',
  },
  {
    category: 'Support',
    question: 'Are the tools live or static?',
    answer: 'Our software tools are built around live astronomy pipelines, coordinate calculations, active satellite tracking, and real-time celestial events to mirror a professional observatory setup.',
  },
  {
    category: 'Payments',
    question: 'What are the payment and setup options?',
    answer: 'Online camp enrollments are processed directly through the student portal. School-level partnerships and laboratory setups are custom-quoted based on infrastructure requirements and cohort size.',
  },
];

function FAQItem({ faq, index }) {
  const [open, setOpen] = useState(false);
  const answerId = useId();
  return (
    <motion.div
      layout
      className={`home-v3-faq-item transition-colors duration-200 border overflow-hidden ${open ? 'is-open' : ''}`}
    >
      <button
        onClick={() => setOpen(!open)}
        aria-expanded={open}
        aria-controls={answerId}
        className="home-v3-faq-trigger w-full flex items-center justify-between gap-5 text-left p-5 focus:outline-none"
      >
        <span className="home-v3-faq-index" aria-hidden="true">{String(index + 1).padStart(2, '0')}</span>
        <div className="space-y-1.5 flex-1">
          <span className="inline-block text-[9px] font-semibold tracking-normal text-v3-accent bg-[var(--v3-accent)]/5 px-2.5 py-0.5 rounded-full border border-[var(--v3-accent)]/15">
            {faq.category}
          </span>
          <span className="block font-bold text-[0.95rem] text-white tracking-tight leading-snug">{faq.question}</span>
        </div>
        <motion.div
          animate={{ rotate: open ? 180 : 0 }}
          className="w-8 h-8 shrink-0 rounded-full border border-white/10 flex items-center justify-center bg-white/5 text-v3-accent"
        >
          <ChevronDown size={15} />
        </motion.div>
      </button>
      <AnimatePresence initial={false}>
        {open && (
          <motion.div
            id={answerId}
            role="region"
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="overflow-hidden"
          >
            <div className="p-5 pt-1 text-[0.9rem] text-slate-300 leading-relaxed font-medium">
              {faq.answer}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

export default function Home() {
  const { homeSections } = useSiteVisibility();
  const navigate = useNavigate();
  const swiperRef = useRef(null);
  const testimonialPrevRef = useRef(null);
  const testimonialNextRef = useRef(null);
  useSEO({
    title: 'CosmaNeX | Global Space Science & Astronomy Education Ecosystem',
    description:
      'CosmaNeX builds modern space education programs, live astronomy tools, and campus-ready aerospace learning infrastructure.',
    path: '/',
    image: '/cosmanex-banner.jpg',
  });

  const [activeProgramTab, setActiveProgramTab] = useState('courses');
  const [dbCourses, setDbCourses] = useState([]);
  const [dbEvents, setDbEvents] = useState([]);
  const [dynamicTestimonials, setDynamicTestimonials] = useState([]);
  const [dynamicFaqs, setDynamicFaqs] = useState(faqs);
  const [dynamicPartners, setDynamicPartners] = useState(null);
  const [liveMetrics, setLiveMetrics] = useState(null);
  const [homeLoaded, setHomeLoaded] = useState(false);
  const [prevEl, setPrevEl] = useState(null);
  const [nextEl, setNextEl] = useState(null);
  const [paginationEl, setPaginationEl] = useState(null);

  useEffect(() => {
    const fetchHomeData = async () => {
      const [coursesRes, eventsRes, testRes, faqsRes, partnersRes, metricsRes] = await Promise.allSettled([
        fetch(`${API_BASE}/api/courses`).then(parseApiResponse),
        fetch(`${API_BASE}/api/cms/events`).then(parseApiResponse),
        fetch(`${API_BASE}/api/cms/testimonials`).then(parseApiResponse),
        fetch(`${API_BASE}/api/cms/faqs`).then(parseApiResponse),
        fetch(`${API_BASE}/api/cms/partners`).then(parseApiResponse),
        fetch(`${API_BASE}/api/cms/metrics`).then(parseApiResponse),
      ]);

      if (coursesRes.status === 'fulfilled' && coursesRes.value?.success) {
        setDbCourses(coursesRes.value.courses || []);
      }

      if (eventsRes.status === 'fulfilled' && eventsRes.value?.success && Array.isArray(eventsRes.value.events)) {
        setDbEvents(eventsRes.value.events);
      }

      if (testRes.status === 'fulfilled' && testRes.value?.success && testRes.value.testimonials?.length > 0) {
        const mapped = testRes.value.testimonials.map((t, idx) => ({
          id: t.id || `t-${idx}`,
          quote: t.review || t.quote,
          name: t.name,
          role: t.role,
          institution: (t.institution && t.institution !== 'CosmaNeX Partner') ? t.institution : '',
          rating: t.rating ?? 0,
          avatar: t.photo || t.avatar || 'https://api.dicebear.com/7.x/adventurer/svg?seed=user',
          completedProgram: (t.completedProgram && t.completedProgram !== 'Seeded Program') ? t.completedProgram : ''
        }));
        setDynamicTestimonials(mapped);
      }

      if (faqsRes.status === 'fulfilled' && faqsRes.value?.success && faqsRes.value.faqs?.length > 0) {
        setDynamicFaqs(faqsRes.value.faqs);
      }

      if (partnersRes.status === 'fulfilled' && partnersRes.value?.success) {
        setDynamicPartners(partnersRes.value.partners || []);
      }

      if (metricsRes.status === 'fulfilled' && metricsRes.value?.success && metricsRes.value.metrics) {
        setLiveMetrics(metricsRes.value.metrics);
      }

      // Everything is applied in the same tick, so the courses section swaps skeleton → content once.
      setHomeLoaded(true);
    };

    fetchHomeData();
  }, []);

  const getDynamicPrograms = () => {
    const list = [];

    // 1. Add Dynamic Courses from DB
    dbCourses.forEach(c => {
      if (c.category === 'Online Programs') {
        list.push({
          id: c.id,
          category: 'courses',
          title: c.title,
          instructor: typeof c.instructor === 'object' && c.instructor !== null ? c.instructor.name : (c.instructor || 'Space Science Mentor'),
          price: c.price === 0 ? 'Free' : `₹${c.price}`,
          level: c.level || 'Beginner',
          duration: c.duration || 'Flexible',
          skills: (c.tags && c.tags.length > 0) ? c.tags.join(', ') : (c.shortDescription || 'Space Science, Celestial Observation'),
          thumbnail: c.thumbnail,
          path: `/course/${c.slug}`,
          rating: c.rating ?? 0,
          reviews: c.reviewsCount ?? (Array.isArray(c.reviews) ? c.reviews.length : 0)
        });
      } else if (c.category === 'Travel Expeditions') {
        list.push({
          id: c.id,
          category: 'expeditions',
          title: c.title,
          instructor: typeof c.instructor === 'object' && c.instructor !== null ? c.instructor.name : (c.instructor || 'Expedition Lead'),
          price: c.price === 0 ? 'Flexible' : `₹${c.price}`,
          level: c.level || 'All Ages',
          duration: c.duration || '3 to 5 Days',
          skills: (c.tags && c.tags.length > 0) ? c.tags.join(', ') : (c.shortDescription || 'Dark sky routing, wilderness exploration'),
          thumbnail: c.thumbnail,
          path: `/course/${c.slug}`,
          rating: c.rating ?? 0,
          reviews: c.reviewsCount ?? (Array.isArray(c.reviews) ? c.reviews.length : 0)
        });
      }
    });

    // 2. Add Live Sessions (Admin-managed via /api/cms/events, linked to /media#events)
    if (dbEvents.length > 0) {
      dbEvents.forEach((evt, idx) => {
        const computedStatus = getAutomaticEventStatus(evt, Date.now());
        list.push({
          id: evt.id || `evt-${idx}`,
          category: 'live',
          title: evt.title,
          image: evt.thumbnail || evt.image || null,
          instructor: evt.host || 'CosmaNeX Faculty',
          price: 'Free Access',
          level: evt.platform || 'YouTube Live',
          duration: evt.date || 'Scheduled',
          time: evt.time || '',
          metrics: evt.metrics || 'Open Registration',
          status: computedStatus,
          path: '/media#events',
          externalLink: evt.link || '',
          ctaLabel: 'View in Media Hub'
        });
      });
    } else {
      list.push(
        {
          id: 'live-calib',
          category: 'live',
          title: 'German Equatorial Mount Calibration Masterclass',
          instructor: 'Mr. Siddhivinayak Shukla',
          price: 'Free Access',
          level: 'Interactive Webinar',
          duration: 'July 15, 2026',
          metrics: '550+ Enrolled',
          status: 'Upcoming',
          path: '/media#events',
          externalLink: 'https://zoom.us/j/example1',
          ctaLabel: 'View in Media Hub'
        },
        {
          id: 'live-astro',
          category: 'live',
          title: 'Deep-Sky Astrophotography & Core Nebula Stacking',
          instructor: 'Mitul Jain',
          price: 'Free Stream',
          level: 'YouTube Live',
          duration: 'July 20, 2026',
          metrics: '820+ Registered',
          status: 'Active',
          path: '/media#events',
          externalLink: 'https://www.youtube.com/live/example2',
          ctaLabel: 'View in Media Hub'
        },
        {
          id: 'live-combustion',
          category: 'live',
          title: 'Model Rocket Solid Fuel Combustion & Aerodynamics',
          instructor: 'Shivam Gupta',
          price: 'Lab Session',
          level: 'On-site Live Stream',
          duration: 'August 05, 2026',
          metrics: '120 limit (Filled)',
          status: 'Upcoming',
          path: '/media#events',
          externalLink: 'https://cosmanex.com/events/rocket-lab',
          ctaLabel: 'View in Media Hub'
        }
      );
    }

    // 3. Add static Labs/Community groups
    list.push(
      {
        id: 'community-wa',
        category: 'labs',
        title: 'CosmaNeX WhatsApp Astronomy Community',
        instructor: 'Community Admins',
        price: 'Join Free',
        level: 'All Enthusiasts',
        duration: 'Active 24/7',
        skills: 'Join our active WhatsApp community to discuss stargazing, solar cycles, satellite tracking, and daily space news with thousands of space enthusiasts.',
        thumbnail: 'https://images.unsplash.com/photo-1451187580459-43490279c0fa?auto=format&fit=crop&w=800&q=80',
        path: WHATSAPP_COMMUNITY_URL,
        isExternal: true,
        ctaLabel: 'Join WhatsApp Community'
      }
    );

    return list;
  };

  const dynamicHomePrograms = getDynamicPrograms();
  const visiblePrograms = dynamicHomePrograms.filter((program) => program.category === activeProgramTab);

  return (
    <main className="home-v3 min-h-screen bg-transparent text-white pb-24 overflow-hidden" data-dark-hero="true">
      {homeSections.hero && <section className="home-v3-hero">
        <div className="home-v3-art" aria-hidden="true" />
        <div className="home-v3-star-field" aria-hidden="true" />
        <div className="home-v3-hero-inner">
          <div className="home-v3-copy">
            <p className="home-v3-eyebrow">Space Education Infrastructure</p>
            <h1>
              <span>Modern space</span>
              <span>learning, <em>built</em></span>
              <span className="home-v3-title-accent">around live data.</span>
            </h1>
            <p className="home-v3-lede">
              CosmaNeX turns astronomy into an active engineering discipline through programs, telemetry tools, campus labs, and immersive hardware.
            </p>
            <div className="home-v3-actions">
              <Link to="/services" className="home-v3-button home-v3-button-primary" title="Browse our services and offerings">
                View services <ArrowRight size={15} />
              </Link>
              <button
                type="button"
                className="home-v3-button home-v3-button-secondary"
                title="Scroll to contact details"
                onClick={() => {
                  const footerEl = document.getElementById('footer-connect') || document.querySelector('footer');
                  if (footerEl && window.__lenis && typeof window.__lenis.scrollTo === 'function') {
                    window.__lenis.scrollTo(footerEl, { duration: 1.2 });
                  } else {
                    footerEl?.scrollIntoView({ behavior: 'smooth', block: 'start' });
                  }
                }}
              >
                Get in touch <ArrowRight size={15} />
              </button>
            </div>
          </div>
        </div>
      </section>}

      {homeSections.partners && dynamicPartners?.length > 0 && (
      <section className="py-16 border-y border-white/[0.08] bg-white/[0.01] overflow-hidden" title="Our Collaborators and Partners">
        <div className="max-w-7xl mx-auto px-6 mb-10">
          <p className="text-center text-[11px] font-semibold tracking-[0.25em] text-slate-500">
            COLLABORATIONS & PARTNER ORGANIZATIONS
          </p>
        </div>
        <div className={`relative flex w-full select-none ${dynamicPartners.length > 3 ? 'overflow-hidden' : 'justify-center px-6'}`}>
          {dynamicPartners.length > 3 ? (
            <div className="animate-marquee flex w-max items-center py-2">
              <div className="flex min-w-[100vw] shrink-0 items-center justify-around">
                {dynamicPartners.map(partner => <PartnerLogo key={partner.id || partner.name} partner={partner} />)}
              </div>
              <div className="flex min-w-[100vw] shrink-0 items-center justify-around" aria-hidden="true">
                {dynamicPartners.map(partner => <PartnerLogo key={`duplicate-${partner.id || partner.name}`} partner={partner} duplicate />)}
              </div>
            </div>
          ) : (
            <div className="flex flex-wrap items-center justify-center py-2">
              {dynamicPartners.map(partner => <PartnerLogo key={partner.id || partner.name} partner={partner} />)}
            </div>
          )}
        </div>
      </section>
      )}

      {homeSections.story && <section className="home-v3-story-section max-w-7xl mx-auto px-6 mt-24">
        <div className="home-v3-story-intro mb-16 space-y-10">
          <ScrollReveal>
            <div className="text-center max-w-3xl mx-auto space-y-4">
              <p className="text-xs font-semibold tracking-normal text-v3-accent">
                Why CosmaNeX
              </p>
              <h2 className="text-3xl sm:text-4xl lg:text-5xl font-black text-white tracking-tight leading-tight">
                Space is a live data stream, not a static chapter.
              </h2>
              <p className="text-sm sm:text-base text-[var(--v3-text-secondary)] leading-relaxed font-medium">
                We bridge classroom astronomy with real-time observation, aerospace datasets, and engineered learning systems so students can move from curiosity to research-grade thinking.
              </p>
            </div>
          </ScrollReveal>

          <ScrollReveal delay={0.08}>
            <div className="home-v3-story-grid">
              {[
                {
                  title: 'The Gap',
                  desc: 'Textbooks teach space as static chapters, separating students from the active night sky.',
                  image: '/assets/home-theory-gap.webp',
                  accent: 'var(--v3-text-secondary)',
                  audience: 'Classroom engagement gap',
                  features: ['Textbook Learning', 'Theory Centric']
                },
                {
                  title: 'Our Mission',
                  desc: 'To turn astronomy into an active, hands-on engineering and observation discipline.',
                  image: '/assets/home-cubesat-team.webp',
                  accent: 'var(--v3-accent-soft)',
                  audience: 'Hands-on learning',
                  features: ['Practical Telemetry', 'STEM Driven']
                },
                {
                  title: 'Active Technology',
                  desc: 'We build campus observatories, mobile domes, and live satellite tracking feeds.',
                  image: '/assets/home-radio-array.webp',
                  accent: 'var(--v3-text-secondary)',
                  audience: 'Integrated infrastructure',
                  features: ['GoTo Telescopes', 'Mobile Domes']
                },
                {
                  title: 'Future Research',
                  desc: 'Students transition from sky-watching to publishing data and tracking telemetry.',
                  image: '/assets/home-observatory-research.webp',
                  accent: 'var(--v3-accent-soft)',
                  audience: 'Real aerospace careers',
                  features: ['Telemetry Feeds', 'Data Analysis']
                }
              ].map((pillar, idx) => (
                <ScrollReveal key={pillar.title} delay={idx * 0.06} className={`home-v3-story-grid-item ${idx === 0 ? 'is-featured' : ''}`}>
                <article className={`home-v3-story-card ${idx === 0 ? 'is-featured' : ''}`}>
                  <div className="home-v3-story-image">
                    <img src={pillar.image} alt="" loading="lazy" decoding="async" />
                    <span className="home-v3-story-index">0{idx + 1}</span>
                  </div>
                  <div className="home-v3-story-copy">
                    <p className="home-v3-story-kicker">{pillar.audience}</p>
                    <h3>{pillar.title}</h3>
                    <p className="home-v3-story-description">{pillar.desc}</p>
                    <div className="home-v3-story-tags">
                      {pillar.features.map((feat) => <span key={feat}>{feat}</span>)}
                    </div>
                  </div>
                </article>
                </ScrollReveal>
              ))}
            </div>
          </ScrollReveal>
        </div>

        <ScrollReveal>
          <div className="flex items-center justify-between gap-4 mb-8">
            <h2 className="text-sm font-bold text-slate-400 uppercase tracking-wider">
              CosmaNeX Ecosystem
            </h2>
            <Link to="/about-us" className="hidden sm:inline-flex items-center gap-2 text-xs font-semibold tracking-normal text-v3-accent hover:text-white transition-colors">
              About Us <ArrowRight size={13} />
            </Link>
          </div>
        </ScrollReveal>

        <div className="home-v3-ecosystem-grid mb-16">
          {ecosystem.map(({ title, desc, cta, path, image, icon: Icon, accent, glow }, index) => (
            <ScrollReveal key={title} delay={index * 0.08} className={`home-v3-ecosystem-grid-item ${index === 0 ? 'is-featured' : ''}`}>
              <Link to={path} className={`home-v3-ecosystem-card group ${index === 0 ? 'is-featured' : ''}`}>
                <div className="home-v3-ecosystem-image">
                  {image ? <img src={image} alt="" loading="lazy" decoding="async" /> : <Icon size={48} style={{ color: accent }} strokeWidth={1.5} />}
                  <span className="home-v3-ecosystem-index">0{index + 1}</span>
                </div>
                <div className="home-v3-ecosystem-copy">
                  <p className="home-v3-ecosystem-kicker">{desc.what}</p>
                  <h3>{title}</h3>
                  <p className="home-v3-ecosystem-impact">{desc.why}</p>
                  <div className="home-v3-ecosystem-footer">
                    <span>{desc.who}</span>
                    <span className="home-v3-ecosystem-link">{cta}<ArrowRight size={15} /></span>
                  </div>
                </div>
              </Link>
            </ScrollReveal>
          ))}
        </div>
      </section>}

      {homeSections.programs && <section className="home-v3-program-section max-w-7xl mx-auto px-6 mt-16">
        <ScrollReveal>
          <div className="home-v3-program-metrics flex flex-wrap items-center gap-x-8 gap-y-3 mb-6 text-[10px] sm:text-xs font-semibold tracking-normal min-h-[18px]">
            <span className="flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full bg-[var(--v3-accent)]" />
              {liveMetrics?.studentsCount ?? dbCourses.reduce((s, c) => s + (Number(c.studentsEnrolled) || 0), 0)} {((liveMetrics?.studentsCount ?? 0) === 1) ? 'Student' : 'Students'}
            </span>
            <span className="flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full bg-[var(--v3-accent)]" />
              {dbCourses.length || liveMetrics?.programsCount || dynamicHomePrograms.length} {((dbCourses.length || liveMetrics?.programsCount || dynamicHomePrograms.length) === 1) ? 'Program' : 'Programs'}
            </span>
            {homeSections.partners && (
            <span className="flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full bg-[var(--v3-text-secondary)]" />
              {liveMetrics?.partnerSchoolsCount ?? (Array.isArray(dynamicPartners) ? dynamicPartners.length : 0)} Partner {((liveMetrics?.partnerSchoolsCount ?? (Array.isArray(dynamicPartners) ? dynamicPartners.length : 0)) === 1) ? 'School' : 'Schools'}
            </span>
            )}
            <span className="flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
              {liveMetrics?.completionRate ?? 100}% Completion Rate
            </span>
          </div>
        </ScrollReveal>

        <ScrollReveal>
          <div className="home-v3-program-header max-w-3xl mb-8">
            <h2 className="text-3xl sm:text-5xl font-black text-white tracking-tight leading-none mb-4">
              Learn space science by doing it.
            </h2>
            <p className="text-sm sm:text-base text-slate-400 leading-relaxed font-medium">
              Choose the format that fits your classroom, campus, or personal learning path.
            </p>
          </div>
        </ScrollReveal>

        <div className="border-b border-white/10 mb-8 overflow-hidden">
          <div className="home-v3-program-tabs grid grid-cols-4 sm:flex sm:items-center sm:justify-start gap-0 sm:gap-8 w-full sm:w-auto">
            {programTabs.map(({ id, label, icon: Icon }) => (
              <button
                key={id}
                onClick={() => setActiveProgramTab(id)}
                title={label}
                  className={`home-v3-program-tab relative min-w-0 h-14 sm:h-auto flex items-center justify-center gap-2 pb-0 sm:pb-4 text-sm sm:text-base font-bold transition-colors w-full sm:w-auto overflow-hidden ${activeProgramTab === id ? 'is-active' : ''} ${
                  activeProgramTab === id ? 'text-v3-accent' : 'text-[var(--v3-text-secondary)]/70 hover:text-white'
                }`}
              >
                <Icon size={18} className="shrink-0" />
                <span>{label}</span>
                {activeProgramTab === id && (
                  <motion.span layoutId="home-program-tab" className="absolute left-0 right-0 bottom-0 h-0.5 bg-[var(--v3-accent)] home-v3-program-tab-indicator" />
                )}
              </button>
            ))}
          </div>
        </div>

        {/* Conditional Layouts based on Tab Category */}
        <div className="space-y-8 mb-24 min-h-[420px]">
          {!homeLoaded && (activeProgramTab === 'courses' || activeProgramTab === 'expeditions') ? (
            <span className="sr-only" role="status">Loading programs</span>
          ) : visiblePrograms.length > 0 ? (
            (() => {
              // 1. Live Sessions: Render the exact media schedule events layout (managed in Admin Panel & linked to Media Hub)
              if (activeProgramTab === 'live') {
                const mappedEvents = visiblePrograms.map(item => ({
                  id: item.id,
                  title: item.title,
                  image: item.thumbnail || item.image || '/assets/event-deep-sky.webp',
                  host: item.instructor,
                  platform: item.level,
                  date: item.duration,
                  metrics: item.metrics || 'Open Registration',
                  status: item.status || 'Upcoming',
                  link: item.path || '/media#events',
                  ctaLabel: item.ctaLabel || 'View in Media Hub'
                }));

                const STATUS_ORDER = { Active: 0, Upcoming: 1, Ended: 2 };
                mappedEvents.sort((a, b) => (STATUS_ORDER[a.status] ?? 99) - (STATUS_ORDER[b.status] ?? 99));

                return (
                  <div className="py-4">
                    <AnimatedList
                      items={mappedEvents.slice(0, 6)}
                      onItemSelect={() => {
                        navigate('/media?tab=Events#events');
                      }}
                    />
                  </div>
                );
              }

              // 2. Labs & Clubs: dedicated WhatsApp community showcase
              if (activeProgramTab === 'labs') {
                const waItem = visiblePrograms.find(item => item.id === 'community-wa');
                if (!waItem) return null;
                return (
                  <ScrollReveal>
                    <SpotlightCard
                      spotlightColor="var(--v3-whatsapp-soft)"
                      className="max-w-5xl mx-auto bg-[var(--v3-whatsapp-deep)] border border-white/[0.08] rounded-3xl overflow-hidden hover:border-[var(--v3-whatsapp)]/40 transition-all duration-300 group shadow-xl"
                    >
                      <div className="grid md:grid-cols-[1.05fr_1fr]">
                        <div className="relative min-h-[220px] md:min-h-[340px] overflow-hidden">
                          <img src="/assets/home-labs-club.webp" alt="Students building a rover prototype in an aerospace club workshop" className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-700" loading="lazy" decoding="async" />
                          <div className="absolute inset-0 bg-gradient-to-t md:bg-gradient-to-r from-transparent via-transparent to-[var(--v3-whatsapp-deep)]/80 pointer-events-none" />
                        </div>
                        <div className="p-8 sm:p-10 flex flex-col justify-center">
                          <h3 className="text-2xl sm:text-3xl font-bold text-white mb-3 leading-tight group-hover:text-[var(--v3-whatsapp)] transition-colors">
                            {waItem.title}
                          </h3>
                          <p className="text-sm sm:text-base text-slate-300 leading-relaxed mb-7 font-normal">
                            {waItem.skills}
                          </p>
                          <a
                            href={waItem.path}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-2xl text-xs sm:text-sm font-semibold transition-all duration-300 w-full sm:w-fit text-center bg-[var(--v3-whatsapp)] hover:bg-[var(--v3-whatsapp-hover)] text-slate-950 shadow-lg shadow-[var(--v3-whatsapp)]/15 no-underline hover:no-underline"
                            style={{ textDecoration: 'none' }}
                          >
                            {waItem.ctaLabel} <ArrowRight size={14} />
                          </a>
                        </div>
                      </div>
                    </SpotlightCard>
                  </ScrollReveal>
                );
              }

              // 3. Courses / Expeditions: Render standard Featured + Grid layout
              const featured = visiblePrograms[0];
              const secondaries = visiblePrograms.slice(1);
              const openProgramCard = (program) => {
                if (!program?.path) return;
                if (program.isExternal || /^https?:\/\//i.test(program.path)) {
                  window.open(program.path, '_blank', 'noopener,noreferrer');
                } else {
                  navigate(program.path);
                }
              };
              return (
                <>
                  {/* Featured Service Banner */}
                  <ScrollReveal>
                    <BorderGlow
                      onClick={() => openProgramCard(featured)}
                      role="link"
                      tabIndex={0}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                          e.preventDefault();
                          openProgramCard(featured);
                        }
                      }}
                      className="home-v3-featured-program group overflow-hidden shadow-xl cursor-pointer"
                      edgeSensitivity={30}
                      glowColor="225 100 54"
                      backgroundColor="var(--v3-panel-raised)"
                      borderRadius={24}
                      glowRadius={24}
                      glowIntensity={0.65}
                      coneSpread={25}
                      colors={['var(--v3-accent)', 'var(--v3-accent)', 'var(--v3-accent)']}
                    >
                      <div className="grid grid-cols-1 lg:grid-cols-12 items-stretch min-h-[320px] xl:min-h-[350px]">
                        {/* Thumbnail Side */}
                        <div className="lg:col-span-6 relative aspect-video lg:aspect-auto min-h-[180px] lg:min-h-[250px] bg-slate-900 overflow-hidden" title={featured.title}>
                          <LazyImage
                            src={featured.thumbnail}
                            alt={featured.title}
                            title={featured.title}
                            className="w-full h-full object-cover group-hover:scale-[1.02] transition-transform duration-300"
                          />
                          <div className="home-v3-featured-badge absolute top-4 left-4 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-slate-950/85 text-v3-accent border border-[var(--v3-accent)]/30 text-[9px] font-semibold tracking-normal shadow-lg shadow-black/40 backdrop-blur-md">
                            <span className="w-1.5 h-1.5 rounded-full bg-[var(--v3-accent)] animate-pulse" />
                            ★ Featured Service
                          </div>
                          <div className="absolute bottom-4 right-4 price-badge !text-sm">
                            {featured.price}
                          </div>
                        </div>

                        {/* Detail Side */}
                        <div className="lg:col-span-6 p-6 sm:p-8 flex flex-col justify-between">
                          <div>
                            <div className="flex flex-wrap items-center gap-2 sm:gap-3 text-[10px] text-[var(--v3-text-secondary)] font-semibold tracking-normal mb-4">
                              <span className="flex items-center gap-1"><Clock size={12} /> {featured.duration}</span>
                              <span className="text-white/20">•</span>
                              <span className="flex items-center gap-1"><BarChart size={12} /> {featured.level}</span>
                              <span className="text-white/20">•</span>
                              <span className="text-v3-accent">
                                Lead: {typeof featured.instructor === 'object' && featured.instructor !== null ? featured.instructor.name : featured.instructor}
                              </span>
                            </div>
                            <h3 className="text-xl sm:text-2xl font-black text-white leading-tight mb-4 group-hover:text-v3-accent transition-colors">
                              {featured.title}
                            </h3>
                            <p className="text-xs sm:text-sm text-[var(--v3-text-secondary)] leading-relaxed font-medium mb-6">
                              <span className="font-bold text-white">Outcomes & Skills: </span>
                              {featured.skills}
                            </p>
                          </div>

                          <div className="border-t border-white/5 pt-5 flex justify-between items-center text-xs">
                            <div className="flex items-center gap-1 text-slate-300">
                              <Star size={14} weight={Number(featured.rating) > 0 ? 'fill' : 'regular'} className="rating-star" />
                              <span className="font-black text-sm">{featured.reviews > 0 && featured.rating > 0 ? featured.rating : 'New'}</span>
                              {featured.reviews > 0 && <span className="text-[10px] text-[var(--v3-text-secondary)] font-medium">({featured.reviews} reviews)</span>}
                            </div>
                            {featured.isExternal ? (
                              <a
                                href={featured.path}
                                target="_blank"
                                rel="noopener noreferrer"
                                onClick={(e) => e.stopPropagation()}
                                className="inline-flex items-center justify-center gap-2 p-3 sm:px-5 sm:py-3 rounded-full sm:rounded-xl bg-white/5 border border-white/10 text-white hover:border-[var(--v3-accent)]/40 hover:bg-[var(--v3-accent)]/10 text-xs font-semibold transition-all duration-300 shrink-0"
                                style={{ textDecoration: 'none' }}
                                title={featured.ctaLabel || 'Access Event'}
                              >
                                <ArrowRight size={16} />
                                <span className="hidden sm:inline">{featured.ctaLabel || 'Access Event'}</span>
                                <ChevronRight size={13} className="hidden sm:inline" />
                              </a>
                            ) : (
                              <Link
                                to={featured.path}
                                onClick={(e) => e.stopPropagation()}
                                className="inline-flex items-center justify-center gap-2 p-3 sm:px-5 sm:py-3 rounded-full sm:rounded-xl bg-white/5 border border-white/10 text-white hover:border-[var(--v3-accent)]/40 hover:bg-[var(--v3-accent)]/10 text-xs font-semibold transition-all duration-300 shrink-0"
                                title="Enroll & View Details"
                              >
                                <BookOpen size={16} />
                                <span className="hidden sm:inline">Enroll & View Details</span>
                                <ChevronRight size={13} className="hidden sm:inline" />
                              </Link>
                            )}
                          </div>
                        </div>
                      </div>
                    </BorderGlow>
                  </ScrollReveal>

                  {/* Secondary Services Grid */}
                  {secondaries.length > 0 && (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mt-8" title="Available Services and Curriculums">
                      {secondaries.map((course, index) => (
                        <ScrollReveal key={course.id} delay={index * 0.06}>
                          <BorderGlow
                            onClick={() => openProgramCard(course)}
                            role="link"
                            tabIndex={0}
                            onKeyDown={(e) => {
                              if (e.key === 'Enter' || e.key === ' ') {
                                e.preventDefault();
                                openProgramCard(course);
                              }
                            }}
                            className="home-v3-course-card hover:-translate-y-1.5 hover:shadow-2xl transition-all duration-300 group flex flex-col justify-between h-full shadow-lg cursor-pointer"
                            edgeSensitivity={30}
                            glowColor="225 100 54"
                            backgroundColor="var(--v3-panel-raised)"
                            borderRadius={16}
                            glowRadius={20}
                            glowIntensity={0.65}
                            coneSpread={25}
                            colors={['var(--v3-accent)', 'var(--v3-accent)', 'var(--v3-accent)']}
                          >
                            <div className="aspect-video bg-slate-900 overflow-hidden relative flex-shrink-0" title={course.title}>
                              <LazyImage
                                src={course.thumbnail}
                                alt={`Thumbnail for ${course.title}`}
                                title={course.title}
                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                              />
                              <div className="absolute top-2 right-2 price-badge" title={`Price: ${course.price}`}>
                                {course.price}
                              </div>
                            </div>

                            <div className="p-4 flex-1 flex flex-col justify-between">
                              <div>
                                <div className="flex items-center gap-2 text-[9px] text-[var(--v3-text-secondary)] font-semibold tracking-normal mb-2">
                                  <span className="flex items-center gap-1" title={`Duration: ${course.duration}`}><Clock size={9} /> {course.duration}</span>
                                  <span>-</span>
                                  <span className="flex items-center gap-1" title={`Level: ${course.level}`}><BarChart size={9} /> {course.level}</span>
                                </div>
                                <h3 className="min-w-0 text-xs font-black text-white leading-snug truncate mb-1.5 group-hover:text-v3-accent transition-colors" title={course.title}>
                                  {course.title}
                                </h3>
                                <p className="text-[9px] text-[var(--v3-text-secondary)]/80 font-bold mb-3" title={`Instructor: ${typeof course.instructor === 'object' && course.instructor !== null ? course.instructor.name : course.instructor}`}>
                                  Lead: {typeof course.instructor === 'object' && course.instructor !== null ? course.instructor.name : course.instructor}
                                </p>
                                <div className="min-w-0 text-[11px] text-[var(--v3-text-secondary)]/70 leading-relaxed truncate mb-4 font-medium" title={`Outcome: ${course.skills}`}>
                                  <span className="font-bold text-[var(--v3-text)]">Outcome: </span>
                                  <span className="text-[var(--v3-text-secondary)]">{course.skills}</span>
                                </div>
                              </div>

                              <div className="border-t border-white/5 pt-3 flex justify-between items-center text-[11px]">
                                <div className="flex items-center gap-1 text-slate-300" title={`Rating: ${course.rating} based on reviews`}>
                                  <Star size={11} weight={Number(course.rating) > 0 ? 'fill' : 'regular'} className="rating-star" />
                                  <span className="font-bold">{course.reviews > 0 && course.rating > 0 ? course.rating : 'New'}</span>
                                  {course.reviews > 0 && <span className="text-[9px] text-[var(--v3-text-secondary)] font-medium">({course.reviews})</span>}
                                </div>
                                {course.isExternal ? (
                                  <a
                                    href={course.path}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    onClick={(e) => e.stopPropagation()}
                                    className="font-semibold text-v3-accent group-hover:text-white text-[11px] flex items-center gap-0.5"
                                    title={`Join the community link for ${course.title}`}
                                    aria-label={`Join Community for ${course.title}`}
                                    style={{ textDecoration: 'none' }}
                                  >
                                    {course.ctaLabel || 'Join Community'} <ChevronRight size={11} className="group-hover:translate-x-0.5 transition-transform" />
                                  </a>
                                ) : (
                                  <Link
                                    to={course.path}
                                    onClick={(e) => e.stopPropagation()}
                                    className="font-semibold text-v3-accent group-hover:text-white text-[11px] flex items-center gap-0.5"
                                    title={`View details for ${course.title}`}
                                    aria-label={`View Details for ${course.title}`}
                                  >
                                    View Details <ChevronRight size={11} className="group-hover:translate-x-0.5 transition-transform" />
                                  </Link>
                                )}
                              </div>
                            </div>
                          </BorderGlow>
                        </ScrollReveal>
                      ))}
                    </div>
                  )}
                </>
              );
            })()
          ) : (
            <div className="text-center py-16 bg-[var(--v3-panel-raised)]/50 border border-white/5 rounded-3xl p-8 max-w-xl mx-auto shadow-xl">
              <div className="w-14 h-14 mx-auto mb-4 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center text-v3-accent">
                <BookOpen size={24} />
              </div>
              <h3 className="text-base font-bold text-white mb-2">Curriculum Under Preparation</h3>
              <p className="text-xs text-slate-400 max-w-md mx-auto leading-relaxed mb-6 font-medium">
                New syllabi and observational workshops for this category are being finalized by our mission astronomers.
              </p>
              <Link
                to="/services"
                className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-[var(--color-accent)] hover:opacity-90 text-xs font-semibold tracking-normal text-white transition-all cursor-pointer shadow-md shadow-[var(--color-accent)]/20"
              >
                Browse All Services <ArrowRight size={13} />
              </Link>
            </div>
          )}
        </div>
      </section>}

      {/* ═══ TESTIMONIALS SECTION ═══════════════════════════════ */}
      {homeSections.testimonials && dynamicTestimonials.length > 0 && <HomeTestimonials
        dynamicTestimonials={dynamicTestimonials}
        liveMetrics={liveMetrics}
        dbCourses={dbCourses}
        dynamicPartners={dynamicPartners}
      />}

      {/* ═══ FAQ SECTION ═══════════════════════════════════════ */}
      {homeSections.faq && <section className="home-v3-faq-section max-w-7xl mx-auto px-6 mt-28 mb-12">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-start">
          {/* Left Column: Heading and CTA Card */}
          <div className="home-v3-faq-copy lg:col-span-5 space-y-8 lg:sticky lg:top-28">
            <ScrollReveal>
              <div>
                <p className="text-[10px] font-bold uppercase tracking-[0.25em] text-v3-accent mb-4" style={{ fontFamily: "'Space Grotesk', sans-serif" }}>
                  FAQ
                </p>
                <h2 className="text-4xl sm:text-5xl font-black text-white tracking-tight leading-tight mb-5">
                  Everything you need <br />
                  <span className="text-gradient">before joining.</span>
                </h2>
                <p className="text-sm sm:text-base text-slate-400 leading-relaxed font-medium">
                  Have questions about CosmaNeX online camps, K-12 school labs, or interactive sky tools? Browse our quick answers or get in touch.
                </p>
              </div>
            </ScrollReveal>

            {/* Premium CTA Card */}
            <ScrollReveal delay={0.06}>
              <div className="p-6 rounded-3xl bg-white/[0.02] border border-white/[0.08] backdrop-blur-md relative overflow-hidden group">
                <div className="absolute top-0 right-0 w-24 h-24 bg-[var(--v3-accent)]/10 rounded-full blur-2xl pointer-events-none" />
                <h3 className="text-base font-black text-white mb-2">Still have questions?</h3>
                <p className="text-xs text-slate-400 leading-relaxed mb-6 font-medium">
                  We are here to help you build the future of space and astronomy education.
                </p>
                <a
                  href="https://mail.google.com/mail/?view=cm&fs=1&to=hello@cosmanex.com"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-white/5 border border-white/10 text-white hover:border-[var(--v3-accent)]/40 hover:bg-[var(--v3-accent)]/10 text-xs font-semibold transition-all duration-300"
                  style={{ textDecoration: 'none' }}
                >
                  Email Our Team <ArrowRight size={13} />
                </a>
              </div>
            </ScrollReveal>
          </div>

          {/* Right Column: FAQ Accordion */}
          <div className="lg:col-span-7 space-y-4">
            <ScrollReveal delay={0.08}>
              <div className="space-y-4">
                {dynamicFaqs.map((faq, index) => (
                  <FAQItem key={faq.question} faq={faq} index={index} />
                ))}
              </div>
            </ScrollReveal>
          </div>
        </div>
      </section>}

      {/* ═══ MINIMALIST FINAL CTA ═════════════════════════════ */}
      {homeSections.contact && <section className="max-w-4xl mx-auto px-6 py-20 text-center border-t border-white/[0.08] mt-24">
        <ScrollReveal>
          <div className="space-y-6">
            <h2 className="text-3xl sm:text-4xl font-black text-white tracking-tight">
              Ready to explore space beyond textbooks?
            </h2>
            <p className="text-slate-400 text-sm max-w-lg mx-auto leading-relaxed font-medium">
              Join thousands of students and leading schools engineering the future of astronomy education.
            </p>
            <div className="flex flex-wrap justify-center gap-4 pt-2">
              <Link to="/services" className="inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-2xl bg-[var(--color-accent)] text-white text-xs sm:text-sm font-semibold border border-transparent btn-glow transition-all duration-300 hover:-translate-y-0.5" title="Browse our catalog of services">
                Browse Services <ArrowRight size={13} />
              </Link>
              <a
                href="https://mail.google.com/mail/?view=cm&fs=1&to=hello@cosmanex.com"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-2xl border border-white/10 text-white bg-white/5 hover:border-[var(--v3-accent)]/40 hover:bg-[var(--v3-accent)]/10 text-xs sm:text-sm font-semibold transition-all duration-300 hover:-translate-y-0.5"
                style={{ textDecoration: 'none' }}
              >
                Partner With Us
              </a>
            </div>
          </div>
        </ScrollReveal>
      </section>}
    </main>
  );
}
