'use client';

/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useEffect, useState } from "react";
import {
  Users, Mic, Globe, Briefcase, GraduationCap, Target, TrendingUp,
  Award, BookOpen, Video, Building2, Search, DollarSign, Network,
} from "lucide-react";
import CVHeader from "@/components/layout/CVHeader";
import CVFooter from "@/components/layout/CVFooter";
import { voiceAccentIntroductionData } from "@/data/introduction-class/voice-and-accent/pageData";
import { HeroRegistrationSection } from "./sections/HeroRegistrationSection";
import { DiscoverSection } from "./sections/DiscoverSection";
import { AudienceSection } from "./sections/AudienceSection";
import { TrainerSection } from "./sections/TrainerSection";
import { CertificationPathSection } from "./sections/CertificationPathSection";
import { SocialProofSection } from "./sections/SocialProofSection";
import { VideoTestimonialsSection } from "./sections/VideoTestimonialsSection";
import { CareerBenefitsSection } from "./sections/CareerBenefitsSection";
import { UrgencySection } from "./sections/UrgencySection";
import { CertificateSection } from "./sections/CertificateSection";
import { FaqSection } from "./sections/FaqSection";
import { FinalCtaSection } from "./sections/FinalCtaSection";
import VoiceAccentInfoSection from "./sections/VoiceAccentInfoSection";
import { CountryCodeDropdown } from "@/components/ui/CountryCodeDropdown";

const PRIMARY_BTN = "inline-flex items-center justify-center gap-3 px-10 py-5 rounded-2xl font-black text-lg bg-[#8B1C1C] text-white hover:bg-[#6B1010] transition-all duration-300 shadow-lg hover:scale-[1.02]";

export default function LiveClass() {
  const [sessions, setSessions] = useState(null);
  const [form, setForm] = useState({ firstName: "", lastName: "", email: "", countryCode: "+1", phone: "", profession: "", session: "", interest: "" });

  // Derive the label of the currently selected session for dynamic display
  const selectedSessionLabel = sessions?.find(o => o.value === form.session)?.label || "";
  const hasSessions = Array.isArray(sessions) && sessions.length > 0;
  const [expanded, setExpanded] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    let cancelled = false;
    fetch(voiceAccentIntroductionData.apiPath)
      .then((res) => res.json())
      .then((data) => {
        if (cancelled) return;
        const list = data?.ok && Array.isArray(data.sessions) ? data.sessions : [];
        setSessions(list);
        setForm((current) => ({ ...current, session: list[0]?.value || "" }));
      })
      .catch(() => {
        if (!cancelled) {
          setSessions([]);
          setForm((current) => ({ ...current, session: "" }));
        }
      });

  return () => { cancelled = true; };
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.session) {
      setError("No upcoming sessions are available right now. Please check back soon.");
      return;
    }
    setError("");
    setSubmitting(true);
    try {
      const response = await fetch(voiceAccentIntroductionData.apiPath, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          firstName: form.firstName,
          lastName: form.lastName,
          email: form.email,
          countryCode: form.countryCode,
          phone: form.phone,
          profession: form.profession,
          interest: form.interest,
          webinarId: form.session,
        }),
      });
      const data = await response.json();
      if (!response.ok || !data?.ok) {
        setError(data?.message || "Unable to submit right now. Please try again.");
        return;
      }
      window.location.assign(`${voiceAccentIntroductionData.confirmationPath}/${data.webinarId}/${data.token}/confermation`);
    } catch {
      setError("Unable to submit right now. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const benefits = [
    { icon: Target, text: "Understand what professional Voice & Accent trainers actually do" },
    { icon: Mic, text: "Experience live pronunciation and accent analysis" },
    { icon: BookOpen, text: "Explore phonetics, stress, rhythm, and intonation" },
    { icon: TrendingUp, text: "See the CVAT\u00ae trainer pathway and ask questions" },
  ];

  const audience = [
    { icon: Users, label: "English and TESOL Teachers" },
    { icon: Award, label: "IELTS / OET Trainers" },
    { icon: Briefcase, label: "Corporate Trainers & L&D Professionals" },
    { icon: Mic, label: "Aspiring Voice & Accent Coaches" },
    { icon: Globe, label: "Customer-Service & BPO Trainers" },
    { icon: GraduationCap, label: "Students Exploring Trainer Careers" },
  ];

  const videoTestimonials = [
    {
      name: "Radhni Dhingra",
      outcome: "Corporate Trainer → ₹2,800/hour",
      youtubeId: "dQw4w9WgXcQ",
      thumb: "https://img.youtube.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
    },
    {
      name: "Jatin Vashisht",
      outcome: "IELTS Trainer → 40% Higher Pass Rates",
      youtubeId: "dQw4w9WgXcQ",
      thumb: "https://img.youtube.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
    },
    {
      name: "Sarthak Kumari",
      outcome: "MNC Professional → Promoted in 3 Months",
      youtubeId: "dQw4w9WgXcQ",
      thumb: "https://img.youtube.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
    },
    {
      name: "Meera Iyer",
      outcome: "IT → Full-Time Voice Trainer",
      youtubeId: "dQw4w9WgXcQ",
      thumb: "https://img.youtube.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
    },
  ];

  const certPath = [
    {
      step: "01",
      icon: BookOpen,
      title: "Attend the Free Introduction Class",
      desc: "Explore what voice and accent trainers do, how pronunciation coaching works, and whether this pathway fits your goals.",
    },
    {
      step: "02",
      icon: Video,
      title: "Complete Professional Training",
      desc: "The full CVAT\u00ae programme covers phonetics, pronunciation, accent modification, methodology, guided practice, and portfolio work.",
    },
    {
      step: "03",
      icon: Target,
      title: "Demonstrate Your Skills",
      desc: "Build evidence through speech analysis, session planning, feedback practice, teaching demonstrations, and a final trainer presentation.",
    },
    {
      step: "04",
      icon: Award,
      title: "Earn Your CVAT\u00ae Credential",
      desc: "The CVAT\u00ae certificate is awarded after completing the full programme and its assessment requirements.",
    },
  ];

  const employmentBenefits = [
    { icon: Search, title: "Understand Trainer Roles", desc: "Learn where voice and accent trainers work: language schools, online coaching, L&D teams, customer-service training, and corporate communication." },
    { icon: Building2, title: "Map Corporate Use Cases", desc: "See how pronunciation, intelligibility, voice clarity, and feedback skills apply in workplace communication training." },
    { icon: Network, title: "Plan Portfolio Evidence", desc: "Discover why trainer profiles, speech-analysis samples, teaching demonstrations, and verified credentials matter." },
  ];

  const matchedVideoTestimonials = [
    {
      name: "Arjun Nair",
      outcome: "L&D Consultant -> CVAT\u00ae graduate story",
      youtubeUrl: "https://www.youtube.com/watch?v=gUbg-279fbA",
      thumb: "https://cambridgeveritas.com/uploads/course-testimonials/images/1772477448_e3331679979106afef96.jpg",
      alt: "Arjun Nair sharing his CVAT Voice and Accent Trainer experience",
    },
    {
      name: "Jasbir Reid",
      outcome: "English speaker -> pronunciation trainer pathway",
      youtubeUrl: "https://www.youtube.com/watch?v=UpkUIczJQSc",
      thumb: "https://cambridgeveritas.com/uploads/course-testimonials/images/1772477584_a1b5b194098a9005fdfb.jpg",
      alt: "Jasbir Reid sharing a pronunciation trainer pathway experience",
    },
    {
      name: "Kanwaldeep Kang",
      outcome: "Life coach -> voice and accent coaching evidence",
      youtubeUrl: "https://www.youtube.com/watch?v=DFKvgBZYU2M",
      thumb: "https://cambridgeveritas.com/uploads/course-testimonials/images/1772477697_fde2a2d416b565def348.jpg",
      alt: "Kanwaldeep Kang sharing voice and accent coaching evidence",
    },
    {
      name: "Shikha Jain",
      outcome: "Voiceover artist -> phonetics and pronunciation learning",
      youtubeUrl: "https://youtu.be/-YzoTTx56VA",
      thumb: "https://cambridgeveritas.com/uploads/course-testimonials/images/1772477267_eb9c06a8a7d1efdfd5bc.jpg",
      alt: "Shikha Jain sharing her phonetics and pronunciation learning experience",
    },
  ];

  const matchedEmploymentBenefits = [
    { icon: Search, title: "Voice & Accent Trainer Roles", desc: "Explore the skills language schools, online learners, L&D teams, and corporate communication programmes often need." },
    { icon: Building2, title: "Corporate Communication Settings", desc: "Learn how accent clarity, voice modulation, pace, tone, and intelligibility apply in professional training contexts." },
    { icon: Network, title: "Portfolio-Based Credibility", desc: "Understand how teaching samples, final presentations, speech analysis, and credential verification support a trainer profile." },
    { icon: TrendingUp, title: "Next-Step Pathway", desc: "Use the free class to decide whether the full CVAT\u00ae trainer certification is the right professional next step." },
  ];

  const faqs = [
    { q: "Is the Voice & Accent Trainer introduction class free?", a: "Yes. The introduction class is free to attend and is designed to help you understand the trainer pathway before choosing the full CVAT\u00ae programme." },
    { q: "How long is the Voice & Accent introduction class?", a: "The live class is approximately 90 minutes, including trainer-led explanation, examples, and time for questions." },
    { q: "Will the session be interactive?", a: "Yes. The class includes live interaction, pronunciation examples, and opportunities to ask questions about voice and accent trainer skills." },
    { q: "Who should attend the Voice & Accent Trainer introduction class?", a: "English teachers, TESOL teachers, IELTS or OET trainers, corporate trainers, BPO trainers, L&D professionals, students, and aspiring coaches can attend." },
    { q: "Do I receive the CVAT\u00ae certification after the free introduction class?", a: "No. The free class explains the pathway. The CVAT\u00ae certificate is awarded only after completing the full programme and assessment requirements." },
    { q: "Do I need prior teaching experience to attend?", a: "No. Prior teaching experience is helpful but not required for the free introduction class." },
    { q: "Will I learn phonetics or IPA in the free class?", a: "You will get an introduction to how phonetics, IPA awareness, pronunciation, stress, rhythm, and intonation fit into trainer development." },
    { q: "Is this class for improving my own accent?", a: "The class is mainly for people exploring how to become a trainer, but you will also understand how pronunciation and accent coaching can improve speech clarity." },
    { q: "Can TESOL or IELTS teachers specialise in Voice & Accent training?", a: "Yes. TESOL, IELTS, and OET teachers often add voice and accent training to specialise in pronunciation, intelligibility, speech analysis, and spoken communication coaching." },
    { q: "What happens after the introduction class?", a: "You can ask questions about the full CVAT\u00ae certification pathway, assessment requirements, portfolio work, and whether the programme fits your goals." },
  ];

  const sectionContext = { PRIMARY_BTN, form, setForm, sessions, selectedSessionLabel, hasSessions, expanded, setExpanded, submitting, error, handleSubmit, benefits, audience, videoTestimonials, certPath, employmentBenefits, matchedVideoTestimonials, matchedEmploymentBenefits, faqs };

  return (
    <div className="cv-intro-page min-h-screen bg-white">
      <CVHeader />

      {/* ══════════════════════════════════════════════════
          1. HERO + FORM (split layout)
      ══════════════════════════════════════════════════ */}
      <HeroRegistrationSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          2. WHAT YOU'LL DISCOVER
      ══════════════════════════════════════════════════ */}
      <DiscoverSection course="voice-and-accent" context={sectionContext} />

      <VoiceAccentInfoSection />

      {/* ══════════════════════════════════════════════════
          3. WHO IT IS FOR
      ══════════════════════════════════════════════════ */}
      <AudienceSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          4. TRAINER AUTHORITY
      ══════════════════════════════════════════════════ */}
      <TrainerSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          5. CERTIFICATION PATH — NEW
      ══════════════════════════════════════════════════ */}
      <CertificationPathSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          6. SOCIAL PROOF STRIP
      ══════════════════════════════════════════════════ */}
      <SocialProofSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          7. VIDEO TESTIMONIALS
      ══════════════════════════════════════════════════ */}
      <VideoTestimonialsSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          8. EMPLOYMENT & CAREER CREDIBILITY — NEW
      ══════════════════════════════════════════════════ */}
      <CareerBenefitsSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          9. URGENCY BLOCK
      ══════════════════════════════════════════════════ */}
      <UrgencySection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          10. CERTIFICATE VISUAL BLOCK — NEW
      ══════════════════════════════════════════════════ */}
      <CertificateSection course="voice-and-accent" context={sectionContext} />



      {/* ══════════════════════════════════════════════════
          12. FAQ
      ══════════════════════════════════════════════════ */}
      <FaqSection course="voice-and-accent" context={sectionContext} />

      {/* ══════════════════════════════════════════════════
          13. FINAL CTA
      ══════════════════════════════════════════════════ */}
      <FinalCtaSection course="voice-and-accent" context={sectionContext} />

      <CVFooter />
    </div>
  );
}
