'use client';

import { Fragment, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import {
  ArrowRight,
  Award,
  BookOpen,
  Brain,
  Calculator,
  ChevronDown,
  Flame,
  Globe,
  GraduationCap,
  LayoutDashboard,
  LogOut,
  Menu,
  Search,
  Star,
  User,
  Wrench,
  X,
  Zap,
} from "lucide-react";
import InlineAuthForm from "@/components/auth/InlineAuthForm";
import { useAuth } from "@/lib/AuthContext";
import { getApiPath } from "@/lib/basePath";
import { canUseClientNavigation, getSameOriginHrefPath } from "@/lib/mainSiteUrl";

const BRAND = "#380f17";
const GOLD = "#D4AF37";
const GOLD_LIGHT = "#E6D3B1";
const LOGO_URL = "/logo/cambridge_veritas_logo.png";
const LIVE_CLASS_URL = "/introduction-class/voice-and-accent";
const IELTS_INTRO_CLASS_URL = "/introduction-class/ielts";
const TESOL_INTRO_CLASS_URL = "/introduction-class/tesol";
const YOUTUBE_LIVE_URL = "https://www.youtube.com/@CambridgeVeritas/streams";
const REG = "\u00AE";
const TM = "\u2122";
const EN_DASH = "\u2013";
const EM_DASH = "\u2014";

const E = {
  grad: "\u{1F393}",
  books: "\u{1F4DA}",
  globe: "\u{1F310}",
  write: "\u270D\uFE0F",
  memo: "\u{1F4DD}",
  medical: "\u{1FA7A}",
  pill: "\u{1F48A}",
  scales: "\u2696\uFE0F",
  gear: "\u2699\uFE0F",
  handshake: "\u{1F91D}",
  plane: "\u2708\uFE0F",
  chart: "\u{1F4CA}",
  headset: "\u{1F3A7}",
  microscope: "\u{1F52C}",
  hotel: "\u{1F3E8}",
  cart: "\u{1F6D2}",
  trophy: "\u{1F3C6}",
  mic: "\u{1F399}\uFE0F",
  briefcase: "\u{1F4BC}",
  film: "\u{1F4FD}\uFE0F",
  sound: "\u{1F50A}",
  idea: "\u{1F4A1}",
  robot: "\u{1F916}",
  video: "\u{1F3A5}",
  satellite: "\u{1F4E1}",
  chat: "\u{1F4AC}",
  camera: "\u{1F4F8}",
  sparkle: "\u{1F31F}",
  target: "\u{1F3AF}",
  people: "\u{1F5E3}\uFE0F",
  world: "\u{1F30D}",
  gift: "\u{1F381}",
  newspaper: "\u{1F4F0}",
  star: "\u2B50",
  laptop: "\u{1F4BB}",
  teacher: "\u{1F469}\u200D\u{1F3EB}",
};

const main = (slug = "") => {
  const cleanSlug = String(slug || "").replace(/^\/+/, "");
  return cleanSlug ? `/${cleanSlug}` : "/";
};
const tool = (slug) => `/${slug}`;

const HREFS = {
  [`Advanced Fluency (CVAF${REG})`]: main("certifications/cambridge-veritas-certificate-in-advanced-fluency"),
  [`Cambridge Veritas TESOL (CVTE${REG})`]: main("certifications/cambridge-veritas-certificate-in-TESOL"),
  [`TESOL (CVTE${REG})`]: main("certifications/cambridge-veritas-certificate-in-TESOL"),
  [`Communication Across Cultures (CVCAC${REG})`]: main("certifications/cambridge-veritas-communication-across-cultures-specialization"),
  [`Global Negotiations (CVCAC${REG})`]: main("certifications/cambridge-veritas-communication-across-cultures-specialization"),
  [`Creative Writing (CVCW${REG})`]: main("certifications/cambridge-veritas-certificate-in-creative-writing"),
  [`IELTS Preparation (CVIP${REG})`]: main("certifications/cambridge-veritas-certificate-for-ielts-preparation"),
  [`Medical Practitioners (CVMP${REG})`]: main("certifications/cambridge-veritas-certificate-for-medical-practitioners"),
  [`Veritas for Doctors (CVMP${REG})`]: main("certifications/cambridge-veritas-certificate-for-medical-practitioners"),
  [`IELTS Masterclass ${EN_DASH} TTT (CVIM${REG})`]: main("masterclass/cambridge-veritas-certificate-in-ielts-masterclass"),
  [`IELTS Masterclass (CVIM${REG})`]: main("masterclass/cambridge-veritas-certificate-in-ielts-masterclass"),
  [`Voice & Accent ${EN_DASH} TTT (CVAT${REG})`]: main("masterclass/cambridge-veritas-voice-and-accent-trainer-certification"),
  [`Voice & Accent (CVAT${REG})`]: main("masterclass/cambridge-veritas-voice-and-accent-trainer-certification"),
  [`Business English (CVBE${REG})`]: main("masterclass/cambridge-veritas-certificate-in-business-english"),
  [`Dynamic Presentations (CVDP${REG})`]: main("masterclass/cambridge-veritas-dynamic-presentations"),
  "Dynamic Presentations": main("masterclass/cambridge-veritas-dynamic-presentations"),
  [`Certificate for Universities (CYES${REG})`]: main("masterclass/vnaprofessionals"),
  [`University Partners (CYES${REG})`]: main("masterclass/vnaprofessionals"),
  [`CYES${REG} Programme`]: main("masterclass/vnaprofessionals"),
  "Voice & Accent Introduction": main("introduction-class/voice-and-accent"),
  "IELTS (TTT) Introduction": main("introduction-class/ielts"),
  "TESOL Introduction Class": main("introduction-class/tesol"),
  [`Veritas for Nurses (CVCN${REG})`]: main("specializations/cambridge-veritas-certificate-in-nursing"),
  [`Veritas for Legal Professionals (CVLP${REG})`]: main("specializations/cambridge-veritas-legal-proficiency-certificate"),
  [`Veritas for Engineers (CVEE${REG})`]: main("specializations/cambridge-veritas-certificate-in-engineering-english"),
  [`Veritas for HRs (CVHR${REG})`]: main("specializations/cambridge-veritas-hr-proficiency-certificate"),
  [`Veritas for Pilots (CVAP${REG})`]: main("specializations/cambridge-veritas-aviation-proficiency-certificate"),
  [`Veritas for Finance (CVFE${REG})`]: main("specializations/cambridge-veritas-certificate-in-financial-english"),
  [`Veritas for Customer Service (CVCS${REG})`]: main("specializations/cambridge-veritas-certificate-in-customer-service"),
  [`Veritas for Scientists (CVPS${REG})`]: main("specializations/cambridge-veritas-proficiency-for-scientists"),
  [`Veritas for Tourism & Hospitality (CVHT${REG})`]: main("specializations/cambridge-veritas-certificate-in-tourism-and-hospitality-management"),
  [`Veritas for Tourism & Hospitality (CVHM${REG})`]: main("specializations/cambridge-veritas-certificate-in-tourism-and-hospitality-management"),
  [`Veritas for Sales & Purchasing (CVSP${REG})`]: main("specializations/cambridge-veritas-proficiency-in-sales-and-purchasing"),
  "Accent Enhancer": tool("tools/accent-enhancer"),
  "Oral Drill": tool("tools/oral-drill"),
  "Photo Mode": tool("tools/photo-mode"),
  "Writing Analyser": tool("tools/writing-analyser"),
  "Speech Analyser": tool("tools/speech-analyser"),
  "English with Ella": tool("tools/practice-accent-with-ella"),
  "Practice Accent with Ella": tool("tools/practice-accent-with-ella"),
  "Practice IELTS with Emma": tool("tools/practice-ielts-with-emma"),
  "Practice English with Eva": tool("tools/practice-english-with-eva"),
  "Practice TESOL with Ellie": tool("tools/practice-tesol-with-ellie"),
  "Veritas Impact": main("veritas-impact"),
  "Hall of Fame": main("hall-of-fame"),
  "Conversation Clubs": main("conversation-clubs"),
  "Live Lessons": YOUTUBE_LIVE_URL,
  "Webinars": main("webinars"),
  "Grammar Lessons": main("grammar"),
  "Online English Practice": main("practice"),
  "Teacher Webinars": main("webinars"),
  "CEFR Levels": main("cefr-levels"),
  "Presentations": main("presentations"),
  "Free Resources": main("free-resources"),
  "Blogs": main("blog"),
  "Reviews": main("reviews"),
  "Writing for Impact": main("certifications/cambridge-veritas-certificate-in-creative-writing"),
  "Certifications": main("certifications"),
  "Specializations": main("specializations"),
  "Masterclass": main("masterclass"),
  "Algebra 1 Tutoring for Grades 8–9": main("online-algebra-1-tutoring"),
  Pricing: main("pricing"),
};

const href = (name) => HREFS[name] || "#";

const COURSES_SIDEBAR = [
  { key: "certifications", label: "Earn a Certification", Icon: Award, color: "#C9963A" },
  { key: "expert", label: "Become an Expert", Icon: Star, color: "#D4AF37" },
  { key: "masterclass", label: "Masterclass", Icon: GraduationCap, color: "#8B3A8B" },
  { key: "intro", label: "Introduction Class", Icon: BookOpen, color: "#2E7D5E" },
  { key: "mathTutoring", label: "Math Tutoring", Icon: Calculator, color: "#2563A5" },
  { key: "popular", label: "Popular Topics", Icon: Flame, color: "#C0392B" },
];

const COURSES_CONTENT = {
  certifications: {
    countLabel: 6,
    items: [
      { name: `Advanced Fluency (CVAF${REG})`, emoji: E.grad, tag: "Certificate", href: href(`Advanced Fluency (CVAF${REG})`) },
      { name: `Cambridge Veritas TESOL (CVTE${REG})`, emoji: E.books, tag: "Certificate", href: href(`Cambridge Veritas TESOL (CVTE${REG})`) },
      { name: `Global Negotiations (CVCAC${REG})`, emoji: E.globe, tag: "Certificate", href: href(`Global Negotiations (CVCAC${REG})`) },
      { name: `Creative Writing (CVCW${REG})`, emoji: E.write, tag: "Certificate", href: href(`Creative Writing (CVCW${REG})`) },
      { name: `IELTS Preparation (CVIP${REG})`, emoji: E.memo, tag: "Certificate", href: href(`IELTS Preparation (CVIP${REG})`) },
      { name: `Veritas for Doctors (CVMP${REG})`, emoji: E.medical, tag: "Medical", href: href(`Veritas for Doctors (CVMP${REG})`) },
    ],
  },
  expert: {
    items: [
      { name: `Veritas for Nurses (CVCN${REG})`, emoji: E.pill, desc: "Clinical English for nursing professionals" },
      { name: `Veritas for Legal Professionals (CVLP${REG})`, emoji: E.scales, desc: "Precision language for law" },
      { name: `Veritas for Engineers (CVEE${REG})`, emoji: E.gear, desc: "Technical communication mastery" },
      { name: `Veritas for HRs (CVHR${REG})`, emoji: E.handshake, desc: "Workplace English for HR teams" },
      { name: `Veritas for Pilots (CVAP${REG})`, emoji: E.plane, desc: "Aviation English certification" },
      { name: `Veritas for Finance (CVFE${REG})`, emoji: E.chart, desc: "Finance & markets communication" },
      { name: `Veritas for Customer Service (CVCS${REG})`, emoji: E.headset, desc: "Client-facing English excellence" },
      { name: `Veritas for Scientists (CVPS${REG})`, emoji: E.microscope, desc: "Scientific & research communication" },
      { name: `Veritas for Tourism & Hospitality (CVHM${REG})`, emoji: E.hotel, desc: "Guest-facing English for hospitality teams" },
      { name: `Veritas for Sales & Purchasing (CVSP${REG})`, emoji: E.cart, desc: "Sales, negotiation & procurement English" },
    ],
  },
  masterclass: {
    items: [
      { name: `IELTS Masterclass ${EN_DASH} TTT (CVIM${REG})`, emoji: E.trophy, desc: "Train the Trainer - IELTS specialist path" },
      { name: `Voice & Accent ${EN_DASH} TTT (CVAT${REG})`, emoji: E.mic, desc: "Professional accent coaching certification" },
      { name: `Business English (CVBE${REG})`, emoji: E.briefcase, desc: "Corporate communication excellence" },
      { name: `Dynamic Presentations (CVDP${REG})`, emoji: E.film, desc: "High-impact presentation skills" },
      { name: `University Partners (CYES${REG})`, emoji: E.grad, desc: "Youth Employability Skills programme" },
    ],
  },
  intro: {
    items: [
      { name: "Voice & Accent Introduction", emoji: E.mic, desc: "Free taster to discover your accent potential", tag: "Free" },
      { name: "IELTS (TTT) Introduction", emoji: E.memo, desc: "Intro to our Train the Trainer methodology", tag: "Free" },
      { name: "TESOL Introduction Class", emoji: E.books, desc: "Explore the Cambridge Veritas TESOL path", tag: "Free" },
    ],
  },
  mathTutoring: {
    href: main("online-algebra-1-tutoring"),
    items: [
      {
        name: "Algebra 1 Tutoring for Grades 8–9",
        emoji: "🧮",
        desc: "Live online Algebra 1 tutoring for students in Grades 8 and 9",
        href: main("online-algebra-1-tutoring"),
      },
    ],
  },
  popular: {
    items: [
      { name: "Accent Enhancer", emoji: E.sound, desc: "AI-powered accent coaching tool" },
      { name: "Writing Analyser", emoji: E.write, desc: "Real-time writing feedback engine" },
      { name: "Dynamic Presentations", emoji: E.film, desc: "Confident, impactful delivery" },
      { name: "Speech Analyser", emoji: E.people, desc: "Measure your spoken clarity & pace" },
      { name: "Writing for Impact", emoji: E.idea, desc: "Persuasive and professional writing" },
      { name: "English with Ella", emoji: E.robot, desc: "AI conversational English tutor" },
    ],
  },
};

const TOOLS_QUICK = [
  { name: "Live Lessons", emoji: E.video },
  { name: "Webinars", emoji: E.satellite },
  { name: "Grammar Lessons", emoji: E.memo },
  { name: "Online English Practice", emoji: E.chat },
];

const TOOLS_LANG = [
  { name: "Accent Enhancer", emoji: E.mic },
  { name: "Oral Drill", emoji: E.sound },
  { name: "Photo Mode", emoji: E.camera },
  { name: "Writing Analyser", emoji: E.write },
];

const TOOLS_AI = [
  { name: "Practice Accent with Ella", emoji: E.sparkle },
  { name: "Practice IELTS with Emma", emoji: E.chart },
  { name: "Practice English with Eva", emoji: E.idea },
  { name: "Practice TESOL with Ellie", emoji: E.grad },
];

const RESOURCES_COLS = [
  {
    heading: "Community",
    items: [
      { name: "Conversation Clubs", emoji: E.people },
      { name: "Live Lessons", emoji: E.video },
      { name: "Veritas Impact", emoji: E.world },
      { name: "Hall of Fame", emoji: E.trophy },
    ],
  },
  {
    heading: "Learning",
    items: [
      { name: "Grammar Lessons", emoji: E.memo },
      { name: "Teacher Webinars", emoji: E.teacher },
      { name: "CEFR Levels", emoji: E.chart },
      { name: "Presentations", emoji: E.film },
    ],
  },
  {
    heading: "Content",
    items: [
      { name: "Online English Practice", emoji: E.laptop },
      { name: "Free Resources", emoji: E.gift },
      { name: "Blogs", emoji: E.newspaper },
      { name: "Reviews", emoji: E.star },
    ],
  },
];

const PRICING_ITEMS = [
  { name: "Certifications", href: main("certifications"), desc: "Globally accredited courses", emoji: E.grad },
  { name: "Specializations", href: main("specializations"), desc: "Professional industry tracks", emoji: "\u{1F3C5}" },
  { name: "Masterclass", href: main("masterclass"), desc: "Train-the-trainer programmes", emoji: E.trophy },
];

const SEARCH_ITEMS = [
  ...Object.entries(HREFS).map(([name, itemHref]) => ({ name, href: itemHref })),
  { name: "Veritas Speech Analyser", href: tool("tools/speech-analyser") },
  { name: "Take the Level Test", href: "/level-test" },
];

function SmartLink({ href: itemHref = "#", children, className, onClick, style, ...props }) {
  const router = useRouter();
  const isExternal = /^(https?:|mailto:|tel:)/i.test(itemHref);
  const isHash = itemHref === "#" || itemHref.startsWith("#");
  const handleClick = (event) => {
    if (!canUseClientNavigation(event)) return;

    onClick?.(event);
    if (event.defaultPrevented) return;

    const sameOriginPath = getSameOriginHrefPath(itemHref);
    if (!sameOriginPath) return;

    event.preventDefault();
    router.push(sameOriginPath);
  };

  if (isExternal || isHash) {
    return (
      <a href={itemHref} className={className} onClick={handleClick} style={style} {...props}>
        {children}
      </a>
    );
  }

  return (
    <Link href={itemHref} className={className} onClick={handleClick} style={style} {...props}>
      {children}
    </Link>
  );
}

function useCountdown() {
  const [time, setTime] = useState({ h: 6, m: 32, s: 0 });

  useEffect(() => {
    const target = Date.now() + (6 * 3600 + 32 * 60) * 1000;
    const update = () => {
      const diff = Math.max(0, target - Date.now());
      setTime({
        h: Math.floor(diff / 3600000),
        m: Math.floor((diff % 3600000) / 60000),
        s: Math.floor((diff % 60000) / 1000),
      });
    };
    const id = window.setInterval(update, 1000);
    const firstUpdate = window.setTimeout(update, 1000);
    return () => {
      window.clearInterval(id);
      window.clearTimeout(firstUpdate);
    };
  }, []);

  return time;
}

function DigitBlock({ value, label, small = false }) {
  const digits = String(value).padStart(2, "0").split("");

  if (small) {
    return (
      <div className="flex flex-col items-center gap-0.5">
        <div className="flex gap-0.5">
          {digits.map((digit, index) => (
            <span
              key={`${label}-${index}`}
              className="flex h-5 w-[15px] items-center justify-center rounded text-[11px] font-black text-white tabular-nums"
              style={{
                background: "rgba(255,255,255,0.14)",
                border: "1px solid rgba(212,175,55,0.28)",
                letterSpacing: 0,
              }}
            >
              {digit}
            </span>
          ))}
        </div>
        <span className="text-[7px] font-black uppercase tracking-widest" style={{ color: GOLD, opacity: 0.75 }}>
          {label}
        </span>
      </div>
    );
  }

  return (
    <div className="flex items-center gap-1.5">
      <div className="flex gap-0.5">
        {digits.map((digit, index) => (
          <span
            key={`${label}-${index}`}
            className="flex h-[26px] w-[18px] items-center justify-center rounded text-sm font-black text-white tabular-nums"
            style={{
              background: "rgba(255,255,255,0.13)",
              border: "1px solid rgba(212,175,55,0.3)",
              letterSpacing: 0,
            }}
          >
            {digit}
          </span>
        ))}
      </div>
      <span className="text-[13px] font-black uppercase tracking-[0.12em]" style={{ color: GOLD, opacity: 0.9 }}>
        {label}
      </span>
    </div>
  );
}

function getDisplayName(user) {
  if (!user) return "Student";
  const first = user.firstName || user.first_name || user.firstname || user.f_name || "";
  const last = user.lastName || user.last_name || user.lastname || user.l_name || "";
  const fullName = `${first} ${last}`.trim();
  return fullName || user.name || user.username || user.email || "Student";
}

function DownloadLeadModal({ onClose }) {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [downloadUrl, setDownloadUrl] = useState("");
  const [downloadFileName, setDownloadFileName] = useState("");
  const [form, setForm] = useState({
    firstName: "",
    lastName: "",
    email: "",
    countryCode: "+91",
    phoneNumber: "",
  });

  const setField = (key) => (event) => {
    setForm((current) => ({ ...current, [key]: event.target.value }));
    setSubmitError("");
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (submitting) return;

    setSubmitting(true);
    setSubmitError("");

    try {
      const response = await fetch(getApiPath("/api/resources/vna-trainer-guide"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          sourcePath: typeof window === "undefined"
            ? ""
            : `${window.location.pathname}${window.location.search}`,
        }),
      });
      const payload = await response.json().catch(() => ({}));

      if (!response.ok || !payload.downloadUrl) {
        throw new Error(payload.message || "We could not prepare your guide. Please try again.");
      }

      setDownloadUrl(payload.downloadUrl);
      setDownloadFileName(payload.fileName || "vna-trainer-guide.pdf");
      setSubmitted(true);
    } catch (error) {
      setSubmitError(error.message || "We could not prepare your guide. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-[300] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.94, y: 16 }}
        animate={{ scale: 1, y: 0 }}
        exit={{ scale: 0.94, y: 16 }}
        transition={{ duration: 0.18 }}
        className="w-full max-w-md overflow-hidden rounded-3xl border-4 bg-white shadow-2xl"
        style={{ borderColor: GOLD }}
        onClick={(event) => event.stopPropagation()}
      >
        <div className="flex items-start justify-between gap-4 px-7 py-5" style={{ background: BRAND }}>
          <div>
            <span className="text-[10px] font-black uppercase tracking-widest" style={{ color: GOLD }}>Free Resource</span>
            <h3 className="mt-1 text-lg font-black leading-tight text-white">Exclusive VnA Trainer Guide</h3>
            <p className="mt-1 text-xs" style={{ color: `${GOLD_LIGHT}99` }}>Expert strategies for teaching English pronunciation</p>
          </div>
          <button type="button" onClick={onClose} className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-white/10 transition-colors hover:bg-white/20" aria-label="Close download modal">
            <X className="h-4 w-4 text-white" />
          </button>
        </div>

        <div className="px-7 py-6">
          {submitted ? (
            <div className="py-4 text-center">
              <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full shadow-xl" style={{ background: GOLD }}>
                <svg viewBox="0 0 20 20" fill="none" className="h-8 w-8" stroke="white" strokeWidth="2.5">
                  <path d="M4 10l4 4 8-8" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>
              <h4 className="mb-2 text-xl font-black" style={{ color: BRAND }}>Your Guide is Ready!</h4>
              <p className="mb-6 text-sm text-[#4A141E]/60">Click below to download your free guide.</p>
              <a href={downloadUrl} download={downloadFileName} onClick={onClose} className="inline-flex w-full items-center justify-center gap-2 rounded-xl border border-[#D4AF37]/30 px-6 py-3.5 text-sm font-black text-white" style={{ background: BRAND }}>
                Download Free Guide
              </a>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-3.5">
              <p className="mb-2 text-xs text-[#4A141E]/55">Enter your details for instant access.</p>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <div>
                  <label htmlFor="vna-guide-first-name" className="mb-1.5 block text-xs font-bold text-[#4A141E]/60">First Name *</label>
                  <input id="vna-guide-first-name" name="firstName" autoComplete="given-name" required type="text" placeholder="Jane" value={form.firstName} onChange={setField("firstName")} className="w-full rounded-xl border-2 border-[#E6D3B1]/50 bg-[#FDFAF7] px-3.5 py-2.5 text-sm text-[#4A141E] outline-none focus:border-[#D4AF37]" />
                </div>
                <div>
                  <label htmlFor="vna-guide-last-name" className="mb-1.5 block text-xs font-bold text-[#4A141E]/60">Last Name *</label>
                  <input id="vna-guide-last-name" name="lastName" autoComplete="family-name" required type="text" placeholder="Smith" value={form.lastName} onChange={setField("lastName")} className="w-full rounded-xl border-2 border-[#E6D3B1]/50 bg-[#FDFAF7] px-3.5 py-2.5 text-sm text-[#4A141E] outline-none focus:border-[#D4AF37]" />
                </div>
              </div>
              <div>
                <label htmlFor="vna-guide-email" className="mb-1.5 block text-xs font-bold text-[#4A141E]/60">Email Address *</label>
                <input id="vna-guide-email" name="email" autoComplete="email" required type="email" placeholder="jane@example.com" value={form.email} onChange={setField("email")} className="w-full rounded-xl border-2 border-[#E6D3B1]/50 bg-[#FDFAF7] px-3.5 py-2.5 text-sm text-[#4A141E] outline-none focus:border-[#D4AF37]" />
              </div>
              <div>
                <label htmlFor="vna-guide-phone" className="mb-1.5 block text-xs font-bold text-[#4A141E]/60">Phone Number *</label>
                <div className="flex min-h-12 rounded-xl border-2 border-[#E6D3B1]/50 bg-[#FDFAF7] focus-within:border-[#D4AF37]">
                  <input aria-label="Country code" name="countryCode" autoComplete="tel-country-code" inputMode="tel" required type="tel" pattern="\+\d{1,4}" maxLength={5} placeholder="+91" value={form.countryCode} onChange={setField("countryCode")} className="w-20 flex-none rounded-l-xl border-r border-[#E6D3B1]/60 bg-transparent px-3.5 py-2.5 text-center text-sm font-bold text-[#4A141E] outline-none" />
                  <input id="vna-guide-phone" name="phoneNumber" autoComplete="tel-national" inputMode="tel" required type="tel" placeholder="7700 900000" value={form.phoneNumber} onChange={setField("phoneNumber")} className="min-w-0 flex-1 rounded-r-xl bg-transparent px-3.5 py-2.5 text-sm text-[#4A141E] outline-none" />
                </div>
              </div>
              {submitError ? <p role="alert" className="rounded-lg bg-red-50 px-3 py-2 text-xs font-semibold text-red-600">{submitError}</p> : null}
              <button type="submit" disabled={submitting} className="flex w-full items-center justify-center gap-2 rounded-xl border border-[#D4AF37]/30 py-3.5 text-sm font-black text-white disabled:cursor-wait disabled:opacity-65" style={{ background: BRAND }}>
                <ArrowRight className="h-4 w-4" /> {submitting ? "Preparing Your Guide..." : "Get My Free Guide"}
              </button>
              <p className="text-center text-[10px] text-[#4A141E]/35">We respect your privacy. No spam, ever.</p>
            </form>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}

function SearchOverlay({ onClose }) {
  const [query, setQuery] = useState("");
  const inputRef = useRef(null);
  const results = query.trim()
    ? SEARCH_ITEMS.filter((item) => item.name.toLowerCase().includes(query.trim().toLowerCase())).slice(0, 10)
    : [];

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  const topCertifications = [
    { name: `Advanced Fluency (CVAF${REG})`, href: href(`Advanced Fluency (CVAF${REG})`) },
    { name: `IELTS Masterclass (CVIM${REG})`, href: href(`IELTS Masterclass (CVIM${REG})`) },
    { name: `TESOL (CVTE${REG})`, href: href(`TESOL (CVTE${REG})`) },
    { name: `Voice & Accent (CVAT${REG})`, href: href(`Voice & Accent (CVAT${REG})`) },
  ];

  const quickLinks = ["Veritas Impact", "Hall of Fame", "Live Lessons", `CYES${REG} Programme`];

  return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-[200] bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <motion.div initial={{ y: -10, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: -10, opacity: 0 }} transition={{ duration: 0.18 }} className="min-h-[100dvh] w-full overflow-auto bg-white shadow-2xl" onClick={(event) => event.stopPropagation()}>
        <div className="border-b border-[#F0E6D4]">
          <div className="mx-auto flex max-w-4xl items-center gap-3 px-4 py-4 sm:px-6">
            <div className="flex flex-1 items-center gap-3 rounded-xl border-2 border-[#D4AF37]/40 bg-[#FDFAF7] px-4 py-3 focus-within:border-[#8B1C1C]/60">
              <Search className="h-4 w-4 flex-shrink-0 text-[#8B1C1C]" />
              <input ref={inputRef} value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search courses, lessons and resources..." className="flex-1 bg-transparent text-sm font-medium text-[#2B0A11] outline-none placeholder:text-[#4A141E]/35" />
              {query ? (
                <button type="button" onClick={() => setQuery("")} aria-label="Clear search">
                  <X className="h-4 w-4 text-gray-400" />
                </button>
              ) : null}
            </div>
            <button type="button" onClick={onClose} className="flex h-9 w-9 items-center justify-center rounded-xl bg-gray-100 hover:bg-gray-200" aria-label="Close search">
              <X className="h-4 w-4 text-gray-500" />
            </button>
          </div>
        </div>

        <div className="mx-auto max-w-4xl px-4 py-6 sm:px-6">
          {query ? (
            <div>
              <p className="mb-3 text-xs text-[#4A141E]/50">Results for &quot;<strong>{query}</strong>&quot;</p>
              {results.length === 0 ? (
                <p className="py-4 text-sm text-[#4A141E]/50">No results found.</p>
              ) : (
                results.map((item) => (
                  <SmartLink key={`${item.name}-${item.href}`} href={item.href} onClick={onClose} className="group flex items-center gap-3 rounded-xl border border-transparent px-4 py-3 transition-all hover:border-[#E6D3B1]/60 hover:bg-[#F6EFE9]">
                    <Search className="h-4 w-4 text-[#8B1C1C]" />
                    <span className="text-sm font-semibold text-[#4A141E]">{item.name}</span>
                    <ArrowRight className="ml-auto h-3.5 w-3.5 text-[#D4AF37] opacity-0 transition-opacity group-hover:opacity-100" />
                  </SmartLink>
                ))
              )}
            </div>
          ) : (
            <div className="grid gap-8 sm:grid-cols-2">
              <div>
                <p className="mb-3 text-[11px] font-black uppercase tracking-widest text-[#4A141E]/40">Top Certifications</p>
                <div className="grid grid-cols-2 gap-2">
                  {topCertifications.map((item) => (
                    <SmartLink key={item.name} href={item.href} onClick={onClose} className="rounded-xl border-2 border-[#E6D3B1]/50 p-3 transition-all hover:border-[#D4AF37] hover:bg-[#F6EFE9]">
                      <div className="mb-2 flex h-7 w-7 items-center justify-center rounded-lg" style={{ background: BRAND }}>
                        <span className="text-[9px] font-black" style={{ color: GOLD }}>CV</span>
                      </div>
                      <p className="text-xs font-bold leading-snug text-[#4A141E]">{item.name}</p>
                    </SmartLink>
                  ))}
                </div>
              </div>
              <div>
                <p className="mb-3 text-[11px] font-black uppercase tracking-widest text-[#4A141E]/40">Quick Links</p>
                {quickLinks.map((name) => (
                  <SmartLink key={name} href={href(name)} onClick={onClose} className="group flex items-center justify-between rounded-lg px-3 py-2.5 transition-all hover:bg-[#F6EFE9]">
                    <span className="text-sm font-semibold text-[#4A141E]/75 group-hover:text-[#8B1C1C]">{name}</span>
                    <ArrowRight className="h-3.5 w-3.5 text-[#D4AF37] opacity-0 transition-opacity group-hover:opacity-100" />
                  </SmartLink>
                ))}
              </div>
            </div>
          )}
        </div>
      </motion.div>
    </motion.div>
  );
}

function MenuGridItem({ item, onClose, compact = false, tabKey = "" }) {
  const isFree = item.tag === "Free";
  const isProgrammeCard = tabKey === "intro" || tabKey === "selfPaced";

  return (
    <SmartLink
      href={item.href || href(item.name)}
      onClick={onClose}
      className={`group flex transition-all hover:bg-[#F6EFE9] ${isProgrammeCard ? "border border-[#E6D3B1]/80 hover:border-[#D4AF37]/70" : ""}`}
      style={{
        alignItems: compact ? "center" : "flex-start",
        gap: isProgrammeCard ? "0.875rem" : "0.75rem",
        padding: isProgrammeCard ? "1rem 1.25rem" : compact ? "0.625rem 0.75rem" : "0.75rem",
        borderRadius: "0.75rem",
      }}
    >
      <span style={{ marginTop: compact ? 0 : "0.125rem", width: "1.25rem", flexShrink: 0, textAlign: "center", fontSize: "1.25rem", lineHeight: 1 }}>{item.emoji}</span>
      <div style={{ minWidth: 0, flex: "1 1 0%" }}>
        <div style={{ display: "flex", minWidth: 0, flexDirection: isProgrammeCard ? "row" : "column", alignItems: isProgrammeCard ? "center" : "flex-start", gap: isProgrammeCard ? "0.625rem" : "0.25rem" }}>
          <p className="transition-colors group-hover:text-[#8B1C1C]" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: "0.875rem", fontWeight: 700, lineHeight: 1.375, color: "#4A141E" }}>{item.name}</p>
          {item.tag ? (
            <span style={{ display: "inline-flex", flexShrink: 0, borderRadius: isFree ? "9999px" : "4px", background: isFree ? "rgba(46, 125, 94, 0.12)" : "rgba(56, 15, 23, 0.08)", padding: "0.125rem 0.5rem", fontSize: isFree ? "9px" : "10px", fontWeight: isFree ? 900 : 700, lineHeight: 1, letterSpacing: isFree ? "0.05em" : "normal", textTransform: "uppercase", color: isFree ? "#2E7D5E" : BRAND }}>
              {item.tag}
            </span>
          ) : null}
        </div>
        {item.desc ? <p style={{ marginTop: isProgrammeCard ? "0.25rem" : "0.125rem", fontSize: isProgrammeCard ? "0.75rem" : "11px", lineHeight: 1.375, color: "rgba(74, 20, 30, 0.45)" }}>{item.desc}</p> : null}
      </div>
    </SmartLink>
  );
}

function CoursesMenu({ onClose }) {
  const [active, setActive] = useState("certifications");
  const content = COURSES_CONTENT[active];
  const programmeCount = content.countLabel || content.items.length;
  const sideItem = COURSES_SIDEBAR.find((item) => item.key === active) || COURSES_SIDEBAR[0];
  const Icon = sideItem.Icon;

  return (
    <div className="flex min-h-[340px] overflow-hidden rounded-b-2xl border border-[#DDD0BB] bg-white shadow-2xl">
      <div className="flex w-52 flex-shrink-0 flex-col py-2" style={{ background: "#FAF6F0", borderRight: "1px solid #EDE0CC" }}>
        {COURSES_SIDEBAR.map((item) => {
          const isActive = active === item.key;
          const ItemIcon = item.Icon;
          return (
            <button key={item.key} type="button" onMouseEnter={() => setActive(item.key)} onClick={() => setActive(item.key)} className="flex w-full items-center gap-3 px-4 py-3.5 text-left text-sm font-semibold transition-all" style={{ color: isActive ? item.color : "rgba(74,20,30,0.6)", background: isActive ? "#fff" : "transparent", borderRight: isActive ? `2px solid ${item.color}` : "2px solid transparent" }}>
              <ItemIcon className="h-4 w-4 flex-shrink-0" style={{ color: isActive ? item.color : "rgba(74,20,30,0.25)" }} />
              {item.label}
            </button>
          );
        })}
        <div className="mt-auto p-3">
          <SmartLink href={content.href || main("certifications")} onClick={onClose} className="flex w-full items-center justify-center gap-1.5 rounded-lg py-2.5 text-xs font-black transition-all hover:opacity-90" style={{ background: BRAND, color: GOLD }}>
            View All <ArrowRight className="h-3 w-3" />
          </SmartLink>
        </div>
      </div>

      <div className="flex flex-1 flex-col p-6">
        <div className="mb-4 flex items-center gap-2 border-b border-[#EDE0CC] pb-3">
          <Icon className="h-4 w-4" style={{ color: sideItem.color }} />
          <span className="text-sm font-black text-[#4A141E]">{sideItem.label}</span>
          <span className="ml-auto text-[10px] font-medium text-[#4A141E]/30">{programmeCount} {programmeCount === 1 ? "programme" : "programmes"}</span>
        </div>
        <div className="grid grid-cols-2 gap-2">
          {content.items.map((item) => (
            <MenuGridItem key={item.name} item={item} onClose={onClose} compact={active === "certifications"} tabKey={active} />
          ))}
        </div>
      </div>
    </div>
  );
}

function ToolsMenu({ onClose }) {
  const groups = [
    { heading: "Quick Access", Icon: Globe, items: TOOLS_QUICK },
    { heading: "Language Tools", Icon: Wrench, items: TOOLS_LANG },
    { heading: "AI Trainers", Icon: Brain, items: TOOLS_AI },
  ];

  return (
    <div className="rounded-b-2xl border border-[#DDD0BB] bg-white p-6 shadow-2xl">
      <div className="grid grid-cols-3 gap-6">
        {groups.map((group) => {
          const GroupIcon = group.Icon;
          return (
            <div key={group.heading}>
              <div className="mb-3 flex items-center gap-2 border-b border-[#EDE0CC] pb-2.5">
                <GroupIcon className="h-4 w-4" style={{ color: BRAND }} />
                <p className="text-[11px] font-black uppercase tracking-widest text-[#4A141E]/50">{group.heading}</p>
              </div>
              <div className="space-y-0.5">
                {group.items.map((item) => (
                  <SmartLink key={item.name} href={href(item.name)} onClick={onClose} className="group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium text-[#4A141E]/70 transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
                    <span className="w-5 flex-shrink-0 text-center text-base leading-none">{item.emoji}</span>
                    <span className="transition-transform group-hover:translate-x-0.5">{item.name}</span>
                  </SmartLink>
                ))}
              </div>
              {group.heading === "Quick Access" ? (
                <div className="mt-4 border-t border-[#EDE0CC] pt-3">
                  <SmartLink href={main("level-test")} onClick={onClose} className="flex w-full items-center justify-center gap-2 rounded-xl border border-[#D4AF37]/20 px-4 py-2.5 text-sm font-black text-white shadow-md transition-all hover:opacity-90" style={{ background: BRAND }}>
                    <Zap className="h-3.5 w-3.5 text-[#D4AF37]" /> Take the Level Test
                  </SmartLink>
                </div>
              ) : null}
              {group.heading === "AI Trainers" ? (
                <div className="mt-4 border-t border-[#EDE0CC] pt-3">
                  <SmartLink href={tool("tools/speech-analyser")} onClick={onClose} className="group flex items-center gap-3 rounded-xl border border-[#D4AF37]/40 px-3 py-3 transition-all hover:border-[#D4AF37]" style={{ background: "linear-gradient(135deg, rgba(56,15,23,0.06) 0%, rgba(212,175,55,0.10) 100%)" }}>
                    <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg text-lg" style={{ background: BRAND }}>{E.target}</div>
                    <div className="min-w-0 flex-1">
                      <p className="text-xs font-black text-[#4A141E]">Veritas Speech Analyser{TM}</p>
                      <p className="text-[10px] text-[#4A141E]/50">AI-powered real-time spoken English analysis</p>
                    </div>
                    <ArrowRight className="h-3.5 w-3.5 flex-shrink-0 text-[#D4AF37] opacity-0 transition-opacity group-hover:opacity-100" />
                  </SmartLink>
                </div>
              ) : null}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ResourcesMenu({ onClose, onDownloadClick }) {
  return (
    <div className="rounded-b-2xl border border-[#DDD0BB] bg-white p-6 shadow-2xl">
      <div className="grid grid-cols-4 gap-6">
        <div className="flex flex-col rounded-2xl border border-[#D4AF37]/30 p-5 shadow-md" style={{ background: BRAND }}>
          <div className="mb-3 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-[#D4AF37]/40 bg-[#D4AF37]/20">
            <BookOpen className="h-5 w-5" style={{ color: GOLD }} />
          </div>
          <p className="mb-1.5 text-sm font-black leading-snug" style={{ color: GOLD }}>Exclusive VnA Trainer Guide</p>
          <p className="mb-4 flex-1 text-xs leading-relaxed" style={{ color: `${GOLD_LIGHT}99` }}>Expert strategies for teaching English pronunciation, free for educators.</p>
          <button type="button" onClick={onDownloadClick} className="inline-flex items-center gap-1.5 rounded-xl px-3 py-2.5 text-xs font-black text-[#4A141E] shadow-md transition-all hover:opacity-90" style={{ background: GOLD }}>
            Download Free <ArrowRight className="h-3.5 w-3.5" />
          </button>
        </div>

        {RESOURCES_COLS.map((column) => (
          <div key={column.heading}>
            <p className="mb-3 border-b border-[#EDE0CC] pb-2 text-[11px] font-black uppercase tracking-widest text-[#4A141E]/40">{column.heading}</p>
            <div className="space-y-0.5">
              {column.items.map((item) => (
                <SmartLink key={item.name} href={href(item.name)} onClick={onClose} className="group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium text-[#4A141E]/70 transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
                  <span className="w-5 flex-shrink-0 text-center text-base leading-none">{item.emoji}</span>
                  <span className="transition-transform group-hover:translate-x-0.5">{item.name}</span>
                </SmartLink>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PricingMenu({ onClose }) {
  return (
    <div className="w-[340px] rounded-b-2xl border border-[#DDD0BB] bg-white p-4 shadow-2xl">
      <p className="mb-2 px-2 text-[11px] font-black uppercase tracking-widest text-[#4A141E]/40">Plans</p>
      <div className="space-y-0.5">
        {PRICING_ITEMS.map((item, index) => (
          <Fragment key={item.name}>
            <SmartLink href={item.href || href(item.name)} onClick={onClose} className="group flex items-center gap-3 rounded-xl px-4 py-3.5 transition-all hover:bg-[#F6EFE9]">
              <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-xl text-lg" style={{ background: `${BRAND}10` }}>{item.emoji}</div>
              <div className="min-w-0 flex-1">
                <p className="text-sm font-bold text-[#4A141E] transition-colors group-hover:text-[#8B1C1C]">{item.name}</p>
                <p className="mt-0.5 whitespace-nowrap text-xs text-[#4A141E]/45">{item.desc}</p>
              </div>
              <ArrowRight className="h-4 w-4 flex-shrink-0 text-[#D4AF37] opacity-0 transition-opacity group-hover:opacity-100" />
            </SmartLink>
            {index < PRICING_ITEMS.length - 1 ? <div className="mx-4 border-t border-[#F0E6D4]" /> : null}
          </Fragment>
        ))}
      </div>
    </div>
  );
}

function AccountDropdown({ user, hasCourse, hasSelfPaced, hasSpeechAnalyser, hasAlgebra, isAdmin, onLogout }) {
  return (
    <motion.div initial={{ opacity: 0, y: -6, scale: 0.97 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={{ opacity: 0, y: -6, scale: 0.97 }} transition={{ duration: 0.14 }} className="absolute right-0 top-full z-50 mt-1 w-52 overflow-hidden rounded-2xl border border-[#DDD0BB] bg-white shadow-2xl">
      <div className="border-b border-[#F0E6D4] px-4 py-3">
        <p className="text-[10px] font-black uppercase tracking-widest text-[#4A141E]/40">Signed in as</p>
        <p className="mt-0.5 truncate text-sm font-bold text-[#4A141E]">{getDisplayName(user)}</p>
      </div>
      <div className="p-1.5">
        {hasCourse ? (
          <SmartLink href="/account" className="flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-semibold text-[#4A141E] transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
            <User className="h-4 w-4 text-[#8B1C1C]" /> My Account
          </SmartLink>
        ) : null}
        {hasSelfPaced ? (
          <SmartLink href="/dashboard" className="flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-semibold text-[#4A141E] transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
            <LayoutDashboard className="h-4 w-4 text-[#8B1C1C]" /> Dashboard
          </SmartLink>
        ) : null}
        {hasSpeechAnalyser ? (
          <SmartLink href="/tools/dashboard" className="flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-semibold text-[#4A141E] transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
            <Brain className="h-4 w-4 text-[#8B1C1C]" /> Speech Analyser
          </SmartLink>
        ) : null}
        {hasAlgebra ? (
          <SmartLink href="/algebra-dashboard" className="flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-semibold text-[#4A141E] transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
            <Calculator className="h-4 w-4 text-[#8B1C1C]" /> Algebra Dashboard
          </SmartLink>
        ) : null}
        {isAdmin ? (
          <SmartLink href="/algebra-teacher" className="flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-semibold text-[#4A141E] transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
            <GraduationCap className="h-4 w-4 text-[#8B1C1C]" /> Algebra Teacher Panel
          </SmartLink>
        ) : null}
        <button type="button" onClick={onLogout} className="flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-semibold text-[#4A141E] transition-all hover:bg-red-50 hover:text-red-600">
          <LogOut className="h-4 w-4 text-red-400" /> Log Out
        </button>
      </div>
    </motion.div>
  );
}

function AuthDrawer({ mode, onModeChange, onClose, onSuccess }) {
  return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-[260] bg-black/45 backdrop-blur-sm" onClick={onClose}>
      <motion.div initial={{ x: "100%" }} animate={{ x: 0 }} exit={{ x: "100%" }} transition={{ type: "tween", duration: 0.24 }} className="absolute bottom-0 right-0 top-0 w-[92vw] max-w-[430px] overflow-y-auto bg-[#250912] shadow-2xl" onClick={(event) => event.stopPropagation()}>
        <div className="sticky top-0 z-10 border-b border-[#D4AF37]/25 px-5 py-4" style={{ background: BRAND }}>
          <div className="flex items-center justify-between gap-3">
            <div>
              <p className="mb-1 text-[11px] font-extrabold uppercase tracking-widest text-[#D4AF37]/80">Welcome</p>
              <h4 className="text-xl font-black leading-tight text-[#E6D3B1]">Cambridge Veritas</h4>
            </div>
            <button type="button" onClick={onClose} className="flex h-9 w-9 items-center justify-center rounded-xl bg-[#D4AF37]/15" aria-label="Close auth drawer">
              <X className="h-5 w-5" style={{ color: GOLD }} />
            </button>
          </div>
        </div>
        <div className="p-5">
          <div className="mb-5 flex gap-2 rounded-xl border border-[#D4AF37]/25 bg-white/5 p-1">
            <button type="button" onClick={() => onModeChange("signin")} className={`flex-1 rounded-lg px-3 py-2 text-sm font-black transition-colors ${mode === "signin" ? "bg-[#D4AF37] text-[#380f17]" : "text-[#E6D3B1]/70"}`}>
              Sign In
            </button>
            <button type="button" onClick={() => onModeChange("register")} className={`flex-1 rounded-lg px-3 py-2 text-sm font-black transition-colors ${mode === "register" ? "bg-[#D4AF37] text-[#380f17]" : "text-[#E6D3B1]/70"}`}>
              Sign Up
            </button>
          </div>
          <InlineAuthForm key={mode} defaultMode={mode} onSuccess={onSuccess} onSignUp={() => onModeChange("register")} />
        </div>
      </motion.div>
    </motion.div>
  );
}

export default function CVHeader() {
  const router = useRouter();
  const pathname = usePathname();
  const timer = useCountdown();
  const auth = useAuth() || {};
  const isAuthenticated = !!auth.isAuthenticated;
  const isLoadingAuth = !!auth.isLoadingAuth;
  const user = auth.user;
  const [open, setOpen] = useState(null);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [downloadOpen, setDownloadOpen] = useState(false);
  const authOpen = !!auth.authModalOpen;
  const authMode = auth.authModalMode || "signin";
  const setAuthMode = (mode) => auth.setAuthModalMode?.(mode);
  const [mobileSection, setMobileSection] = useState(null);
  const [accountOpen, setAccountOpen] = useState(false);
  const [accountEntitlements, setAccountEntitlements] = useState({
    hasCourse: false,
    hasSelfPaced: false,
    hasSpeechAnalyser: false,
    hasAlgebra: false,
  });
  const headerRef = useRef(null);
  const accountRef = useRef(null);
  const closeMenuTimerRef = useRef(null);
  const liveClassPromo = pathname?.startsWith(IELTS_INTRO_CLASS_URL)
    ? {
        href: IELTS_INTRO_CLASS_URL,
        label: `Free IELTS Train-the-Trainer Class ${EM_DASH} Next Session`,
      }
    : pathname?.startsWith(TESOL_INTRO_CLASS_URL)
      ? {
          href: TESOL_INTRO_CLASS_URL,
          label: `TESOL Introduction Class ${EM_DASH} Next Live Session`,
        }
      : {
          href: LIVE_CLASS_URL,
          label: `Voice & Accent Certification ${EM_DASH} Intro Class Tonight`,
        };

  useEffect(() => {
    if (!isAuthenticated || !user?.id) {
      setAccountEntitlements({ hasCourse: false, hasSelfPaced: false, hasSpeechAnalyser: false, hasAlgebra: false });
      return undefined;
    }

    const controller = new AbortController();

    async function loadAccountEntitlements() {
      try {
        const response = await fetch(getApiPath('/api/auth/entitlements'), {
          cache: 'no-store',
          credentials: 'same-origin',
          signal: controller.signal,
        });
        if (!response.ok) throw new Error('Unable to load account access');

        const data = await response.json();
        setAccountEntitlements({
          hasCourse: Boolean(data?.hasCourse),
          hasSelfPaced: Boolean(data?.hasSelfPaced),
          hasSpeechAnalyser: Boolean(data?.hasSpeechAnalyser),
          hasAlgebra: Boolean(data?.hasAlgebra),
        });
      } catch (error) {
        if (error?.name === 'AbortError') return;
        setAccountEntitlements({ hasCourse: false, hasSelfPaced: false, hasSpeechAnalyser: false, hasAlgebra: false });
      }
    }

    loadAccountEntitlements();
    return () => controller.abort();
  }, [isAuthenticated, user?.id]);

  const nav = [
    { key: "courses", label: "Explore Courses" },
    { key: "tools", label: "Veritas Tools" },
    { key: "resources", label: "Resources" },
    { key: "pricing", label: "Pricing" },
  ];

  const mobileSections = [
    {
      key: "courses",
      label: "Explore Courses",
      groups: [
        { heading: "Certifications", items: COURSES_CONTENT.certifications.items },
        { heading: "Specializations", items: COURSES_CONTENT.expert.items },
        { heading: "Masterclass", items: COURSES_CONTENT.masterclass.items },
        { heading: "Introduction Classes", items: COURSES_CONTENT.intro.items },
        { heading: "Math Tutoring", items: COURSES_CONTENT.mathTutoring.items },
      ],
    },
    {
      key: "tools",
      label: "Veritas Tools",
      groups: [
        { heading: "Language Tools", items: TOOLS_LANG },
        { heading: "AI Trainers", items: TOOLS_AI },
        { heading: "Quick Access", items: TOOLS_QUICK },
      ],
    },
    {
      key: "resources",
      label: "Resources",
      groups: RESOURCES_COLS,
    },
    {
      key: "pricing",
      label: "Pricing",
      groups: [{ heading: "Plans", items: PRICING_ITEMS }],
    },
  ];

  useEffect(() => {
    const handleDocumentMouseDown = (event) => {
      if (headerRef.current && !headerRef.current.contains(event.target)) setOpen(null);
      if (accountRef.current && !accountRef.current.contains(event.target)) setAccountOpen(false);
    };
    document.addEventListener("mousedown", handleDocumentMouseDown);
    return () => document.removeEventListener("mousedown", handleDocumentMouseDown);
  }, []);

  useEffect(() => {
    if (!open) return undefined;

    const clearCloseMenuTimer = () => {
      if (!closeMenuTimerRef.current) return;
      window.clearTimeout(closeMenuTimerRef.current);
      closeMenuTimerRef.current = null;
    };

    const scheduleCloseMenu = () => {
      if (closeMenuTimerRef.current) return;
      closeMenuTimerRef.current = window.setTimeout(() => {
        setOpen(null);
        closeMenuTimerRef.current = null;
      }, 180);
    };

    const handleDocumentMouseMove = (event) => {
      const target = event.target;
      if (!(target instanceof Element)) return;

      if (
        target.closest(`[data-desktop-nav-key="${open}"]`)
        || target.closest(`[data-desktop-menu-key="${open}"]`)
      ) {
        clearCloseMenuTimer();
        return;
      }

      scheduleCloseMenu();
    };

    document.addEventListener("mousemove", handleDocumentMouseMove);
    return () => {
      document.removeEventListener("mousemove", handleDocumentMouseMove);
      clearCloseMenuTimer();
    };
  }, [open]);

  useEffect(() => {
    document.body.style.overflow = mobileOpen || searchOpen || downloadOpen || authOpen ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [mobileOpen, searchOpen, downloadOpen, authOpen]);

  return (
    <>
      <AnimatePresence>{searchOpen ? <SearchOverlay onClose={() => setSearchOpen(false)} /> : null}</AnimatePresence>
      <AnimatePresence>{downloadOpen ? <DownloadLeadModal onClose={() => setDownloadOpen(false)} /> : null}</AnimatePresence>
      <AnimatePresence>
        {authOpen ? (
          <AuthDrawer
            mode={authMode}
            onModeChange={setAuthMode}
            onClose={() => auth.closeAuthModal?.()}
            onSuccess={(authUser) => {
              auth.login?.(authUser);
              auth.closeAuthModal?.();
              router.push("/");
            }}
          />
        ) : null}
      </AnimatePresence>

      <header ref={headerRef} className="cv-site-header relative z-50">
        <div style={{ background: BRAND, borderBottom: "1px solid rgba(212,175,55,0.15)" }}>
          <div className="mx-auto max-w-7xl px-3 sm:px-8">
            <div data-nosnippet className="flex flex-col items-center justify-center gap-1.5 py-2 sm:hidden">
              <div className="flex items-center gap-1.5">
                <span className="h-1.5 w-1.5 flex-shrink-0 animate-pulse rounded-full" style={{ background: GOLD }} />
                <span className="text-[11px] font-semibold tracking-wide" style={{ color: GOLD_LIGHT }}>
                  {liveClassPromo.label}
                </span>
              </div>
              <div className="flex items-center gap-2">
                {[["HRS", timer.h], ["MIN", timer.m], ["SEC", timer.s]].map(([label, value], index) => (
                  <Fragment key={label}>
                    {index > 0 ? <span className="mb-3 text-sm font-black leading-none" style={{ color: GOLD, opacity: 0.7 }}>:</span> : null}
                    <DigitBlock value={value} label={label} small />
                  </Fragment>
                ))}
                <SmartLink href={liveClassPromo.href} className="ml-2 inline-flex items-center gap-1 rounded-full px-3 py-1.5 text-[10px] font-black whitespace-nowrap shadow-md transition-all hover:opacity-90" style={{ background: GOLD, color: BRAND }}>
                  JOIN NOW <ArrowRight className="h-2.5 w-2.5" />
                </SmartLink>
              </div>
            </div>

            <div data-nosnippet className="hidden h-12 items-center justify-center gap-6 sm:flex">
              <div className="flex min-w-0 flex-shrink items-center gap-2">
                <span className="h-1.5 w-1.5 flex-shrink-0 animate-pulse rounded-full" style={{ background: GOLD }} />
                <span className="whitespace-nowrap text-sm font-semibold tracking-wide" style={{ color: GOLD_LIGHT }}>
                  {liveClassPromo.label}
                </span>
              </div>
              <div className="flex flex-shrink-0 items-center gap-2">
                {[["HRS", timer.h], ["MIN", timer.m], ["SEC", timer.s]].map(([label, value], index) => (
                  <Fragment key={label}>
                    {index > 0 ? <span className="text-base font-black leading-none" style={{ color: GOLD, opacity: 0.65 }}>:</span> : null}
                    <DigitBlock value={value} label={label} />
                  </Fragment>
                ))}
              </div>
              <SmartLink href={liveClassPromo.href} className="inline-flex flex-shrink-0 items-center gap-1.5 rounded-full px-4 py-2 text-xs font-black whitespace-nowrap shadow-md transition-all hover:opacity-90" style={{ background: GOLD, color: BRAND, boxShadow: "0 2px 12px rgba(212,175,55,0.3)" }}>
                JOIN NOW <ArrowRight className="h-3 w-3" />
              </SmartLink>
            </div>
          </div>
        </div>

        <div style={{ background: BRAND, borderBottom: "1px solid rgba(212,175,55,0.12)", boxShadow: "0 8px 48px rgba(0,0,0,0.4)" }}>
          <div className="mx-auto max-w-7xl px-4 sm:px-8">
            <div className="flex h-14 items-center gap-3 sm:h-20 sm:gap-5">
              <SmartLink href="/" className="flex flex-shrink-0 items-center">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={LOGO_URL} alt="Cambridge Veritas" className="h-8 w-auto object-contain sm:h-11" />
              </SmartLink>
              <div className="cv-header-desktop-divider hidden h-9 w-px flex-shrink-0 lg:block" style={{ background: "rgba(212,175,55,0.18)" }} />

              <nav className="cv-header-desktop-nav hidden flex-1 items-center gap-0.5 lg:flex">
                {nav.map((item) => {
                  const isOpen = open === item.key;
                  return (
                    <div
                      key={item.key}
                      className="relative"
                      data-desktop-nav-key={item.key}
                      onMouseLeave={item.key === "pricing" ? () => setOpen(null) : undefined}
                    >
                      <button type="button" onMouseEnter={() => setOpen(item.key)} onClick={() => setOpen(isOpen ? null : item.key)} className="cv-header-nav-button relative flex items-center gap-1.5 rounded-lg px-5 py-3 text-[15px] font-semibold whitespace-nowrap transition-all duration-150" style={{ color: isOpen ? GOLD : GOLD_LIGHT, background: isOpen ? "rgba(212,175,55,0.10)" : "transparent" }}>
                        {item.label}
                        <ChevronDown className="h-3.5 w-3.5 transition-transform duration-150" style={{ transform: isOpen ? "rotate(180deg)" : "none", opacity: 0.6 }} />
                        {isOpen ? <span className="absolute inset-x-4 bottom-0 h-0.5 rounded-full" style={{ background: GOLD }} /> : null}
                      </button>
                      <AnimatePresence>
                        {item.key === "pricing" && isOpen ? (
                          <motion.div data-desktop-menu-key={item.key} initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -4 }} transition={{ duration: 0.14 }} className="absolute left-0 z-50 pt-[17px]" style={{ top: "100%" }}>
                            <PricingMenu onClose={() => setOpen(null)} />
                          </motion.div>
                        ) : null}
                      </AnimatePresence>
                    </div>
                  );
                })}
              </nav>

              <div className="cv-header-desktop-actions ml-auto hidden items-center gap-1.5 lg:flex">
                <button type="button" onClick={() => setSearchOpen(true)} className="cv-header-search-button flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium transition-all hover:bg-white/10" style={{ color: GOLD_LIGHT }}>
                  <Search className="h-[18px] w-[18px]" />
                  <span className="cv-header-search-label hidden text-[15px] xl:inline">Search</span>
                </button>
                <div className="h-8 w-px" style={{ background: "rgba(212,175,55,0.18)" }} />
                <div className="relative" ref={accountRef}>
                  {isLoadingAuth ? (
                    <div className="flex items-center gap-2.5 px-4 py-2.5" aria-hidden="true">
                      <div className="h-8 w-8 animate-pulse rounded-full bg-[#D4AF37]/15" />
                      <div className="hidden h-4 w-16 animate-pulse rounded bg-[#E6D3B1]/15 xl:block" />
                    </div>
                  ) : isAuthenticated ? (
                    <>
                      <button type="button" onClick={() => setAccountOpen((value) => !value)} className="cv-header-account-button flex items-center gap-2.5 rounded-lg px-4 py-2.5 text-[15px] font-semibold transition-all hover:bg-white/10" style={{ color: accountOpen ? GOLD : GOLD_LIGHT, background: accountOpen ? "rgba(212,175,55,0.10)" : "transparent" }}>
                        <div className="flex h-8 w-8 items-center justify-center rounded-full border" style={{ background: "rgba(212,175,55,0.15)", borderColor: "rgba(212,175,55,0.40)" }}>
                          <User className="h-4 w-4" style={{ color: GOLD }} />
                        </div>
                        <span className="cv-header-account-label hidden xl:inline">Account</span>
                        <ChevronDown className="cv-header-account-chevron hidden h-3.5 w-3.5 transition-transform duration-150 xl:block" style={{ transform: accountOpen ? "rotate(180deg)" : "none", opacity: 0.6 }} />
                      </button>
                      <AnimatePresence>
                        {accountOpen ? (
                          <AccountDropdown
                            user={user}
                            hasCourse={accountEntitlements.hasCourse}
                            hasSelfPaced={accountEntitlements.hasSelfPaced}
                            hasSpeechAnalyser={accountEntitlements.hasSpeechAnalyser}
                            hasAlgebra={accountEntitlements.hasAlgebra}
                            isAdmin={user?.role === 'admin'}
                            onLogout={() => auth.logout?.()}
                          />
                        ) : null}
                      </AnimatePresence>
                    </>
                  ) : (
                    <button type="button" onClick={() => auth.navigateToLogin?.("/login")} className="cv-header-login-link flex items-center gap-2 rounded-lg border border-[#D4AF37]/35 px-4 py-2.5 text-[15px] font-bold transition-all hover:bg-[#D4AF37]/10" style={{ color: GOLD_LIGHT }}>
                      <User className="h-4 w-4" style={{ color: GOLD }} />
                      <span className="cv-header-login-label">Login / Register</span>
                    </button>
                  )}
                </div>
              </div>

              <div className="cv-header-mobile-actions ml-auto flex items-center gap-1 lg:hidden">
                <button type="button" onClick={() => setSearchOpen(true)} className="rounded-lg p-2.5" style={{ color: GOLD_LIGHT }} aria-label="Open search">
                  <Search className="h-5 w-5" />
                </button>
                <button type="button" onClick={() => setMobileOpen((value) => !value)} className="rounded-lg p-2.5" style={{ color: GOLD_LIGHT }} aria-label="Open menu">
                  {mobileOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
                </button>
              </div>
            </div>
          </div>
        </div>

        <AnimatePresence>
          {open && open !== "pricing" ? (
            <motion.div key={open} data-desktop-menu-key={open} initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -4 }} transition={{ duration: 0.14 }} onMouseLeave={() => setOpen(null)} className="cv-header-desktop-menu absolute left-0 right-0 z-40 hidden lg:block">
              <div className="mx-auto max-w-7xl px-4 sm:px-8">
                {open === "courses" ? <CoursesMenu onClose={() => setOpen(null)} /> : null}
                {open === "tools" ? <ToolsMenu onClose={() => setOpen(null)} /> : null}
                {open === "resources" ? <ResourcesMenu onClose={() => setOpen(null)} onDownloadClick={() => { setOpen(null); setDownloadOpen(true); }} /> : null}
              </div>
            </motion.div>
          ) : null}
        </AnimatePresence>
      </header>

      <AnimatePresence>
        {mobileOpen ? (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="cv-header-mobile-menu fixed inset-0 z-[220] bg-black/60 lg:hidden" onClick={() => setMobileOpen(false)}>
            <motion.div initial={{ x: "100%" }} animate={{ x: 0 }} exit={{ x: "100%" }} transition={{ type: "tween", duration: 0.22 }} className="absolute inset-y-0 right-0 w-screen overflow-y-auto bg-white shadow-2xl" onClick={(event) => event.stopPropagation()}>
              <div className="sticky top-0 z-10 flex items-center justify-between border-b border-[#D4AF37]/20 px-5 py-4" style={{ background: BRAND }}>
                <div>
                  <span className="text-base font-black" style={{ color: GOLD_LIGHT }}>Menu</span>
                  <p className="mt-0.5 text-[10px] font-semibold" style={{ color: `${GOLD}80` }}>Cambridge Veritas</p>
                </div>
                <button type="button" onClick={() => setMobileOpen(false)} className="flex h-9 w-9 items-center justify-center rounded-xl" style={{ background: "rgba(212,175,55,0.15)" }} aria-label="Close menu">
                  <X className="h-5 w-5" style={{ color: GOLD }} />
                </button>
              </div>

              <div className="px-4 pb-2 pt-4">
                <SmartLink href={liveClassPromo.href} onClick={() => setMobileOpen(false)} className="flex w-full items-center justify-center gap-2 rounded-xl py-3.5 text-sm font-black" style={{ background: GOLD, color: BRAND }}>
                  JOIN CLASS NOW <ArrowRight className="h-4 w-4" />
                </SmartLink>
              </div>

              <div className="px-4 pb-3">
                <SmartLink href={tool("tools/speech-analyser")} onClick={() => setMobileOpen(false)} className="flex items-center gap-3 rounded-xl border-2 px-4 py-3.5 transition-all" style={{ background: "linear-gradient(135deg, rgba(56,15,23,0.05) 0%, rgba(212,175,55,0.12) 100%)", borderColor: "rgba(212,175,55,0.35)" }}>
                  <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl text-xl" style={{ background: BRAND }}>{E.target}</div>
                  <div className="min-w-0 flex-1">
                    <p className="mb-0.5 text-[11px] font-black uppercase tracking-wider text-[#8B1C1C]">Featured Tool</p>
                    <p className="text-sm font-black text-[#4A141E]">Veritas Speech Analyser{TM}</p>
                    <p className="text-[11px] text-[#4A141E]/55">AI-powered spoken English analysis</p>
                  </div>
                  <ArrowRight className="h-4 w-4 flex-shrink-0" style={{ color: GOLD }} />
                </SmartLink>
              </div>

              <div className="px-4 pb-4">
                <div className="mb-3 border-t border-[#EDE0CC]" />
                {mobileSections.map((section, sectionIndex) => (
                  <div key={section.key} className="mb-1">
                    <button type="button" onClick={() => setMobileSection(mobileSection === section.key ? null : section.key)} className="flex w-full items-center justify-between rounded-xl px-4 py-4 text-sm font-bold text-[#4A141E] transition-colors hover:bg-[#F6EFE9]">
                      <span className="text-[15px]">{section.label}</span>
                      <ChevronDown className={`h-5 w-5 transition-transform duration-200 ${mobileSection === section.key ? "rotate-180" : ""}`} style={{ color: GOLD }} />
                    </button>
                    {sectionIndex < mobileSections.length - 1 && mobileSection !== section.key ? <div className="mx-4 border-t border-[#EDE0CC]" /> : null}
                    <AnimatePresence>
                      {mobileSection === section.key ? (
                        <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={{ duration: 0.15 }} className="overflow-hidden">
                          <div className="pb-3">
                            {section.groups.map((group, groupIndex) => (
                              <div key={group.heading} className="mb-2">
                                <p className="px-4 pb-1 pt-2 text-[10px] font-black uppercase tracking-widest" style={{ color: `${GOLD}99` }}>{group.heading}</p>
                                {group.items.map((item) => (
                                  <SmartLink key={item.name} href={item.href || href(item.name)} onClick={() => setMobileOpen(false)} className="flex items-center gap-3 rounded-xl px-4 py-2.5 text-sm font-medium text-[#4A141E]/80 transition-all hover:bg-[#F6EFE9] hover:text-[#8B1C1C]">
                                    <span className="w-5 flex-shrink-0 text-center text-base">{item.emoji}</span>
                                    <span className="flex min-w-0 flex-1 items-center gap-2">
                                      <span className="truncate">{item.name}</span>
                                      {item.tag ? <span className="inline-flex flex-shrink-0 rounded-full bg-[#2E7D5E]/10 px-2 py-0.5 text-[10px] font-black uppercase leading-none tracking-wide text-[#2E7D5E]">{item.tag}</span> : null}
                                    </span>
                                  </SmartLink>
                                ))}
                                {groupIndex < section.groups.length - 1 ? <div className="mx-4 mt-1 border-t border-[#EDE0CC]" /> : null}
                              </div>
                            ))}
                          </div>
                        </motion.div>
                      ) : null}
                    </AnimatePresence>
                  </div>
                ))}

                <div className="mt-4 space-y-2 border-t border-[#EDE0CC] pt-4">
                  {isLoadingAuth ? (
                    <div className="h-[54px] w-full animate-pulse rounded-xl bg-[#380f17]/10" aria-hidden="true" />
                  ) : isAuthenticated ? (
                    <>
                      {accountEntitlements.hasCourse ? (
                        <SmartLink href="/account" onClick={() => setMobileOpen(false)} className="flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-4 text-sm font-black" style={{ background: BRAND, color: GOLD, borderColor: "rgba(212,175,55,0.3)" }}>
                          <User className="h-4 w-4" /> My Account
                        </SmartLink>
                      ) : null}
                      {accountEntitlements.hasSelfPaced ? (
                        <SmartLink href="/dashboard" onClick={() => setMobileOpen(false)} className="flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-4 text-sm font-black" style={{ background: BRAND, color: GOLD, borderColor: "rgba(212,175,55,0.3)" }}>
                          <LayoutDashboard className="h-4 w-4" /> Dashboard
                        </SmartLink>
                      ) : null}
                      {accountEntitlements.hasSpeechAnalyser ? (
                        <SmartLink href="/tools/dashboard" onClick={() => setMobileOpen(false)} className="flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-4 text-sm font-black" style={{ background: BRAND, color: GOLD, borderColor: "rgba(212,175,55,0.3)" }}>
                          <Brain className="h-4 w-4" /> Speech Analyser
                        </SmartLink>
                      ) : null}
                      {accountEntitlements.hasAlgebra ? (
                        <SmartLink href="/algebra-dashboard" onClick={() => setMobileOpen(false)} className="flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-4 text-sm font-black" style={{ background: BRAND, color: GOLD, borderColor: "rgba(212,175,55,0.3)" }}>
                          <Calculator className="h-4 w-4" /> Algebra Dashboard
                        </SmartLink>
                      ) : null}
                      {user?.role === 'admin' ? (
                        <SmartLink href="/algebra-teacher" onClick={() => setMobileOpen(false)} className="flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-4 text-sm font-black" style={{ background: BRAND, color: GOLD, borderColor: "rgba(212,175,55,0.3)" }}>
                          <GraduationCap className="h-4 w-4" /> Algebra Teacher Panel
                        </SmartLink>
                      ) : null}
                      <button type="button" onClick={() => auth.logout?.()} className="flex w-full items-center justify-center gap-2 rounded-xl border border-red-200 bg-red-50 py-3.5 text-sm font-black text-red-500">
                        <LogOut className="h-4 w-4" /> Log Out
                      </button>
                    </>
                  ) : (
                    <button type="button" onClick={() => { setMobileOpen(false); auth.navigateToLogin?.("/login"); }} className="flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-4 text-sm font-black" style={{ background: BRAND, color: GOLD, borderColor: "rgba(212,175,55,0.3)" }}>
                      <User className="h-4 w-4" /> Login / Register
                    </button>
                  )}
                </div>
              </div>
            </motion.div>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </>
  );
}
