import React, { useState } from 'react';
import {
  Cloud,
  Cpu,
  Shield,
  Briefcase,
  Video,
  MessageCircle,
  Compass,
  BookOpen,
  Wrench,
  CheckCircle,
  TrendingUp,
  ArrowRight,
  Star,
  FileText,
  Download,
  Calendar,
  Scale,
  Calculator,
  ChevronDown,
  ChevronUp,
  Clock,
  CheckCircle2,
  Users,
  Award,
} from 'lucide-react';
import { Container, Eyebrow, Pill } from '../components/Ui';
import { Reveal } from '../components/Brand';
import { COURSES, SUBJECTS, SubjectKey, ZiteCourse } from '../data/courses';
import { getCohortForCourse } from '../data/cohorts';
import { COURSE_COMPARISON_DATA } from '../data/courseComparisonData';
import { Testimonials } from '../components/Testimonials';
import { CredentialBadges } from '../components/CredentialBadges';
import { SyllabusModal } from '../components/SyllabusModal';
import { PathwayAdvisor } from '../components/PathwayAdvisor';
import { TuitionCalculator } from '../components/TuitionCalculator';
import { useComparison } from '../context/ComparisonContext';
import { FaqAccordion } from '../components/FaqAccordion';

export function HomePage({ onNavigate }: { onNavigate: (path: string) => void }) {
  const [syllabusOpen, setSyllabusOpen] = useState(false);
  const [selectedCourseForSyllabus, setSelectedCourseForSyllabus] = useState<ZiteCourse | undefined>(undefined);
  const [toolsExpanded, setToolsExpanded] = useState<'none' | 'advisor' | 'calculator'>('none');

  const handleOpenSyllabusWithCourse = (courseOrSlug?: ZiteCourse | string) => {
    if (typeof courseOrSlug === 'string') {
      const found = COURSES.find((c) => c.slug === courseOrSlug);
      setSelectedCourseForSyllabus(found);
    } else {
      setSelectedCourseForSyllabus(courseOrSlug);
    }
    setSyllabusOpen(true);
  };

  return (
    <div className="space-y-16 sm:space-y-24">
      {/* 1. Hero: Clear value proposition, concise text & two primary actions */}
      <Hero onNavigate={onNavigate} />

      {/* 2. Programme Categories */}
      <ProgrammeCategories onNavigate={onNavigate} onOpenSyllabus={handleOpenSyllabusWithCourse} />

      {/* 3. How Online Learning Works */}
      <HowOnlineLearningWorks onNavigate={onNavigate} />

      {/* 4. Selected Courses & Upcoming Intakes (with expandable planning tools) */}
      <SelectedCoursesAndIntakes
        onNavigate={onNavigate}
        onOpenSyllabus={handleOpenSyllabusWithCourse}
        toolsExpanded={toolsExpanded}
        setToolsExpanded={setToolsExpanded}
      />

      {/* 5. Existing Instructor, Community & Testimonial Content */}
      <section className="space-y-16">
        <CredentialBadges />
        <Testimonials onNavigate={onNavigate} />
      </section>

      {/* 6. Clear Admissions CTA & Top Objection Handling */}
      <div className="space-y-8">
        <FaqAccordion onNavigate={onNavigate} />
        <AdmissionsCta onNavigate={onNavigate} />
      </div>

      {/* Syllabus Modal */}
      <SyllabusModal
        course={selectedCourseForSyllabus}
        isOpen={syllabusOpen}
        onClose={() => {
          setSyllabusOpen(false);
          setSelectedCourseForSyllabus(undefined);
        }}
        onNavigate={onNavigate}
      />
    </div>
  );
}

/* -------------------------------------------------------------------------- */
/* 1. Hero Section                                                            */
/* -------------------------------------------------------------------------- */
function Hero({ onNavigate }: { onNavigate: (path: string) => void }) {
  return (
    <section className="mesh pt-8 pb-14 sm:pb-20 border-b border-border/50">
      <Container className="grid gap-12 lg:grid-cols-12 items-center">
        {/* Left Column: Clear Value Proposition */}
        <div className="lg:col-span-7 space-y-6">
          <div className="inline-flex items-center gap-2 text-xs font-bold text-teal bg-teal-soft/80 border border-teal/20 px-3.5 py-1.5 rounded-full">
            <span className="h-2 w-2 rounded-full bg-teal" aria-hidden="true" />
            <span>PRACTICAL LEARNING. PURPOSEFUL PROGRESS.</span>
          </div>

          <h1 className="text-3xl sm:text-5xl lg:text-6xl font-bold leading-[1.08] tracking-tight text-foreground">
            Building skills. Advancing careers.{' '}
            <span className="serif-accent text-teal block sm:inline">Strengthening workplaces.</span>
          </h1>

          <p className="text-base sm:text-lg text-muted-foreground max-w-xl leading-relaxed">
            Develop practical digital and cloud capability with PANIA Digital Academy. Explore 22 live online programmes designed for career progression, or partner with us to upskill your team.
          </p>

          {/* EXACTLY TWO ACTIONS: "Explore Courses" and "Train Your Team" */}
          <div className="flex flex-wrap items-center gap-3.5 pt-2">
            <Pill to="/programmes" variant="primary">
              Explore Courses
            </Pill>
            <Pill to="/organisations" variant="outline" arrow={false}>
              Train Your Team
            </Pill>
          </div>

          {/* Delivery Channels Indicator */}
          <div className="flex items-center gap-3 pt-4 text-xs text-muted-foreground border-t border-border/60 max-w-lg">
            <div className="flex -space-x-1.5" aria-hidden="true">
              <span className="h-7 w-7 rounded-full border-2 border-background grid place-items-center bg-ocean text-white shadow-xs">
                <Video className="h-3.5 w-3.5" />
              </span>
              <span className="h-7 w-7 rounded-full border-2 border-background grid place-items-center bg-teal text-white shadow-xs">
                <Video className="h-3.5 w-3.5" />
              </span>
              <span className="h-7 w-7 rounded-full border-2 border-background grid place-items-center bg-accent text-accent-foreground shadow-xs">
                <MessageCircle className="h-3.5 w-3.5" />
              </span>
            </div>
            <span>Delivered 100% online through live Zoom, Google Meet & dedicated WhatsApp groups.</span>
          </div>
        </div>

        {/* Right Column: High-fidelity visual editorial showcase */}
        <div className="lg:col-span-5 relative">
          <div className="relative rounded-3xl overflow-hidden shadow-xl aspect-[4/3] bg-muted border border-border">
            <img
              src="https://images.fillout.com/902438/vk44zcsdgn/generated-images/uteGWhHScxfTQrVcWbgT9p/img_LCW8ChsAM1I7LXZw.jpg"
              alt="PANIA learner engaged in hands-on cloud computing coursework"
              className="w-full h-full object-cover"
              loading="eager"
              decoding="async"
            />
          </div>

          {/* Restrained Metric Card */}
          <div className="absolute -bottom-5 right-4 sm:-right-4 bg-card rounded-2xl shadow-lg p-4 border border-border flex items-center gap-3.5">
            <div className="h-11 w-11 rounded-xl bg-primary text-primary-foreground flex items-center justify-center font-bold text-lg shadow-xs">
              22
            </div>
            <div>
              <p className="font-bold text-xs text-foreground">Live Online Tracks</p>
              <p className="text-[11px] text-muted-foreground">Cloud · AI · Security · Work Readiness</p>
            </div>
          </div>
        </div>
      </Container>
    </section>
  );
}

/* -------------------------------------------------------------------------- */
/* 2. Programme Categories                                                     */
/* -------------------------------------------------------------------------- */
function ProgrammeCategories({
  onNavigate,
  onOpenSyllabus,
}: {
  onNavigate: (path: string) => void;
  onOpenSyllabus: () => void;
}) {
  const categories: { key: SubjectKey; title: string; desc: string; icon: React.ElementType }[] = [
    {
      key: 'cloud',
      title: 'Cloud Computing & DevOps',
      desc: 'AWS, Google Cloud and Microsoft Azure certification blueprints with hands-on console sandboxes.',
      icon: Cloud,
    },
    {
      key: 'ai',
      title: 'Artificial Intelligence & Data',
      desc: 'Machine learning fundamentals, generative AI tools, and professional data annotation workflows.',
      icon: Cpu,
    },
    {
      key: 'security',
      title: 'Cybersecurity & Networking',
      desc: 'Network defense, Cisco routing, Linux system administration, and software engineering foundations.',
      icon: Shield,
    },
    {
      key: 'work',
      title: 'Online Work Readiness',
      desc: 'Virtual assistant capabilities, freelance client bidding, graphics, and high-impact business communication.',
      icon: Briefcase,
    },
  ];

  return (
    <section aria-labelledby="categories-heading">
      <Container>
        <div className="max-w-2xl space-y-2 mb-10">
          <Eyebrow>Curriculum Architecture</Eyebrow>
          <h2 id="categories-heading" className="text-3xl sm:text-4xl font-bold tracking-tight text-foreground">
            Explore our four core disciplines.
          </h2>
          <p className="text-muted-foreground text-sm sm:text-base leading-relaxed">
            Every track is structured around real-world competency, sandboxed lab execution, and verified vendor blueprint standards.
          </p>
        </div>

        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
          {categories.map((cat, idx) => {
            const Icon = cat.icon;
            const meta = SUBJECTS[cat.key];
            const count = COURSES.filter((c) => c.subject === cat.key).length;

            return (
              <a
                key={cat.key}
                href={`#/programmes?subject=${cat.key}`}
                onClick={(e) => {
                  e.preventDefault();
                  onNavigate(`/programmes?subject=${cat.key}`);
                }}
                className="lift group flex flex-col justify-between p-6 rounded-3xl bg-card border border-border hover:border-primary/40 transition-all shadow-xs"
              >
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <span className={`h-12 w-12 rounded-2xl grid place-items-center ${meta.bgSolid} text-white shadow-xs`}>
                      <Icon className="h-6 w-6" aria-hidden="true" />
                    </span>
                    <span className="text-xs font-bold text-muted-foreground bg-secondary px-2.5 py-1 rounded-full">
                      {count} tracks
                    </span>
                  </div>

                  <h3 className="font-bold text-lg text-foreground group-hover:text-primary transition-colors">
                    {cat.title}
                  </h3>
                  <p className="text-xs text-muted-foreground mt-2 leading-relaxed">
                    {cat.desc}
                  </p>
                </div>

                <div className="mt-6 pt-4 border-t border-border/50 flex items-center justify-between text-xs font-bold text-primary group-hover:underline">
                  <span>View courses</span>
                  <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" aria-hidden="true" />
                </div>
              </a>
            );
          })}
        </div>

        <div className="mt-6 text-center">
          <button
            onClick={onOpenSyllabus}
            className="inline-flex items-center gap-2 text-xs font-semibold text-primary hover:underline cursor-pointer"
          >
            <FileText className="w-4 h-4" aria-hidden="true" />
            <span>Need full module breakdowns? Download the Complete Syllabus Pack</span>
          </button>
        </div>
      </Container>
    </section>
  );
}

/* -------------------------------------------------------------------------- */
/* 3. How Online Learning Works                                               */
/* -------------------------------------------------------------------------- */
function HowOnlineLearningWorks({ onNavigate }: { onNavigate: (path: string) => void }) {
  const steps = [
    {
      num: '01',
      title: 'Interactive Live Masterclasses',
      desc: 'Join weekly live evening or weekend sessions on Zoom & Google Meet led by senior African industry practitioners.',
      icon: Video,
    },
    {
      num: '02',
      title: 'Zero-Install Cloud Sandboxes',
      desc: 'Practise in browser-based consoles (AWS, GCP, Codespaces, Linux shells). No expensive hardware required.',
      icon: Cloud,
    },
    {
      num: '03',
      title: '2-Hour Recordings & 24/7 WhatsApp',
      desc: 'Never fall behind. Missed sessions are posted within 2 hours, backed by continuous peer support and mentor clinics.',
      icon: MessageCircle,
    },
    {
      num: '04',
      title: 'Workplace Capstone Project',
      desc: 'Build and deploy verified production architectures to showcase in your portfolio to regional and remote employers.',
      icon: Award,
    },
  ];

  return (
    <section className="bg-secondary/40 py-16 sm:py-20 border-y border-border" aria-labelledby="learning-heading">
      <Container>
        <div className="grid gap-12 lg:grid-cols-12 items-center">
          {/* Left Column: Narrative */}
          <div className="lg:col-span-5 space-y-4">
            <Eyebrow>The PANIA Method</Eyebrow>
            <h2 id="learning-heading" className="text-3xl sm:text-4xl font-bold tracking-tight text-foreground">
              Real practical skills.{' '}
              <span className="serif-accent text-teal block sm:inline">Zero commute.</span>
            </h2>
            <p className="text-muted-foreground text-sm sm:text-base leading-relaxed">
              We designed our online model specifically for busy professionals, recent graduates, and career transitioners in Nairobi and East Africa who require flexible schedules without sacrificing hands-on rigor.
            </p>

            <div className="pt-2">
              <Pill to="/learning" variant="primary">
                Learn How Delivery Works
              </Pill>
            </div>
          </div>

          {/* Right Column: 4 Process Blocks */}
          <div className="lg:col-span-7 grid gap-4 sm:grid-cols-2">
            {steps.map((step) => {
              const Icon = step.icon;
              return (
                <div
                  key={step.num}
                  className="bg-card rounded-2xl p-5 border border-border shadow-2xs space-y-2.5"
                >
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold text-teal bg-teal-soft px-2 py-0.5 rounded-md">
                      Step {step.num}
                    </span>
                    <Icon className="w-4 h-4 text-muted-foreground" aria-hidden="true" />
                  </div>
                  <h3 className="font-bold text-base text-foreground">{step.title}</h3>
                  <p className="text-xs text-muted-foreground leading-relaxed">{step.desc}</p>
                </div>
              );
            })}
          </div>
        </div>
      </Container>
    </section>
  );
}

/* -------------------------------------------------------------------------- */
/* 4. Selected Courses & Upcoming Intakes                                     */
/* -------------------------------------------------------------------------- */
function SelectedCoursesAndIntakes({
  onNavigate,
  onOpenSyllabus,
  toolsExpanded,
  setToolsExpanded,
}: {
  onNavigate: (path: string) => void;
  onOpenSyllabus: (courseOrSlug: ZiteCourse | string) => void;
  toolsExpanded: 'none' | 'advisor' | 'calculator';
  setToolsExpanded: (val: 'none' | 'advisor' | 'calculator') => void;
}) {
  const { toggleCourse, isInComparison, setDrawerOpen } = useComparison();

  // Flagship selected courses to showcase on homepage using stable canonical IDs (C01–C22)
  const featuredCourseIds = [
    'C07', // AWS Cloud Practitioner Preparation
    'C10', // Google Cloud Platform Training
    'C12', // Cybersecurity Courses
    'C05', // Artificial Intelligence
    'C03', // Virtual Assistant Training
    'C14', // Cisco Networking
  ];

  const featuredCourses = featuredCourseIds
    .map((id) => COURSES.find((c) => c.code === id || c.sourceCatalogueId === id || c.slug === id))
    .filter((c): c is ZiteCourse => Boolean(c));

  return (
    <section aria-labelledby="featured-heading">
      <Container className="space-y-8">
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
          <div className="space-y-1.5 max-w-xl">
            <Eyebrow>Featured Programmes</Eyebrow>
            <h2 id="featured-heading" className="text-3xl sm:text-4xl font-bold tracking-tight text-foreground">
              Upcoming intakes enrolling now.
            </h2>
            <p className="text-muted-foreground text-sm leading-relaxed">
              Select any track to view full course outcomes, weekly timetables, or download the syllabus.
            </p>
          </div>

          <div className="flex items-center gap-2">
            <Pill to="/programmes" variant="outline" arrow={true}>
              View Full Catalogue
            </Pill>
          </div>
        </div>

        {/* Selected Courses Grid */}
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
          {featuredCourses.map((course) => {
            const meta = SUBJECTS[course.subject];
            const cohort = getCohortForCourse(course.slug);
            const isCompared = isInComparison(course.slug);

            return (
              <div
                key={course.code}
                className="bg-card rounded-3xl border border-border p-6 flex flex-col justify-between shadow-xs hover:border-primary/40 transition-all group"
              >
                <div className="space-y-3">
                  <div className="flex items-center justify-between text-xs">
                    <span className={`font-bold px-2.5 py-0.5 rounded-full ${meta.bgSoft} ${meta.textColor}`}>
                      {course.provider || meta.short}
                    </span>
                    <span className="text-muted-foreground font-medium">
                      {COURSE_COMPARISON_DATA[course.slug]?.level.split(' ')[0] || 'Foundational'}
                    </span>
                  </div>

                  <h3
                    onClick={() => onNavigate(`/programmes/${course.slug}`)}
                    className="font-bold text-lg text-foreground hover:text-primary transition-colors cursor-pointer leading-snug"
                  >
                    {course.title}
                  </h3>

                  <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed">
                    {course.headline[0]} {course.headline[1]}
                  </p>

                  {/* Confirmed Cohort Intake Notice */}
                  {cohort && (
                    <div className="p-2.5 rounded-xl bg-secondary/80 text-xs flex items-center justify-between border border-border/60">
                      <div className="flex items-center gap-1.5 font-medium text-foreground">
                        <Calendar className="w-3.5 h-3.5 text-primary" aria-hidden="true" />
                        <span>Intake: {cohort.startDate}</span>
                      </div>
                      <span className="text-[11px] font-bold text-teal">
                        Admissions Open
                      </span>
                    </div>
                  )}
                </div>

                <div className="mt-6 pt-4 border-t border-border/50 space-y-2.5">
                  <div className="grid grid-cols-2 gap-2">
                    <button
                      onClick={() => onNavigate(`/programmes/${course.slug}`)}
                      className="min-h-[40px] px-3 rounded-full text-xs font-bold bg-primary text-primary-foreground hover:bg-[#072C24] transition text-center cursor-pointer"
                    >
                      View Details
                    </button>
                    <button
                      onClick={() => onOpenSyllabus(course)}
                      className="min-h-[40px] px-3 rounded-full text-xs font-semibold border border-border bg-card hover:bg-secondary text-foreground transition text-center cursor-pointer"
                    >
                      Syllabus
                    </button>
                  </div>

                  <button
                    onClick={() => {
                      toggleCourse(course.slug);
                      setDrawerOpen(true);
                    }}
                    className={`w-full py-1.5 text-[11px] font-semibold rounded-lg transition text-center cursor-pointer flex items-center justify-center gap-1 ${
                      isCompared
                        ? 'text-teal font-bold'
                        : 'text-muted-foreground hover:text-foreground'
                    }`}
                  >
                    <Scale className="w-3 h-3" aria-hidden="true" />
                    <span>{isCompared ? 'Added to Comparison' : 'Compare Track'}</span>
                  </button>
                </div>
              </div>
            );
          })}
        </div>

        {/* Expandable Planning Tools Drawer (Progressive Disclosure) */}
        <div className="mt-8 p-5 sm:p-6 rounded-3xl bg-secondary/50 border border-border space-y-4">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
              <h4 className="font-bold text-base text-foreground">
                Need guidance or financial planning?
              </h4>
              <p className="text-xs text-muted-foreground">
                Use our interactive tools to calculate installment breakdowns or discover which course matches your background.
              </p>
            </div>

            <div className="flex items-center gap-2">
              <button
                onClick={() => setToolsExpanded(toolsExpanded === 'advisor' ? 'none' : 'advisor')}
                className={`min-h-[38px] px-4 rounded-full text-xs font-semibold border transition cursor-pointer flex items-center gap-1.5 ${
                  toolsExpanded === 'advisor'
                    ? 'bg-primary text-primary-foreground border-primary'
                    : 'bg-card border-border hover:bg-secondary text-foreground'
                }`}
              >
                <Compass className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Pathway Advisor</span>
                {toolsExpanded === 'advisor' ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
              </button>

              <button
                onClick={() => setToolsExpanded(toolsExpanded === 'calculator' ? 'none' : 'calculator')}
                className={`min-h-[38px] px-4 rounded-full text-xs font-semibold border transition cursor-pointer flex items-center gap-1.5 ${
                  toolsExpanded === 'calculator'
                    ? 'bg-primary text-primary-foreground border-primary'
                    : 'bg-card border-border hover:bg-secondary text-foreground'
                }`}
              >
                <Calculator className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Tuition Calculator</span>
                {toolsExpanded === 'calculator' ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
              </button>
            </div>
          </div>

          {/* Conditional Expandable Panels */}
          {toolsExpanded === 'advisor' && (
            <div className="pt-4 border-t border-border animate-in fade-in duration-200">
              <PathwayAdvisor onNavigate={onNavigate} onOpenSyllabus={onOpenSyllabus} />
            </div>
          )}

          {toolsExpanded === 'calculator' && (
            <div className="pt-4 border-t border-border animate-in fade-in duration-200">
              <TuitionCalculator onNavigate={onNavigate} />
            </div>
          )}
        </div>
      </Container>
    </section>
  );
}

/* -------------------------------------------------------------------------- */
/* 6. Clear Admissions CTA                                                    */
/* -------------------------------------------------------------------------- */
function AdmissionsCta({ onNavigate }: { onNavigate: (path: string) => void }) {
  return (
    <Container className="mb-12">
      <div className="relative overflow-hidden bg-primary text-primary-foreground rounded-3xl p-8 sm:p-12 md:p-16 shadow-xl border border-primary/20">
        <div className="max-w-2xl space-y-4">
          <Eyebrow className="text-accent">Ready to Start?</Eyebrow>
          <h2 className="text-3xl sm:text-5xl font-bold tracking-tight leading-tight">
            Take your next step with <span className="serif-accent text-accent">confidence.</span>
          </h2>
          <p className="text-sm sm:text-base text-primary-foreground/80 leading-relaxed">
            Our admissions advisors are available on WhatsApp to answer prerequisite questions, confirm cohort seat availability, or arrange custom corporate training for your organisation.
          </p>

          <div className="flex flex-wrap items-center gap-3.5 pt-4">
            <Pill to="/contact?mode=learner" variant="accent">
              Apply for Enrolment
            </Pill>
            <Pill to="/organisations" variant="outline-light" arrow={false}>
              Corporate Enquiries
            </Pill>
          </div>
        </div>
      </div>
    </Container>
  );
}
