'use client';

import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { useWishlist } from '../../context/WishlistContext';
import { useUserStore } from '../../../store/useUserStore';
import { 
  Menu, 
  X, 
  ChevronDown, 
  UserCircle, 
  Heart, 
  User, 
  LogOut,
  Search,
  GraduationCap,
  Building2,
  Award,
  Globe,
  BookOpen,
  Wrench,
  Send,
  Sparkles,
  ArrowRight,
  Star,
  Zap,
  MapPin,
  TrendingUp,
} from 'lucide-react';

// ─────────────────────────────────────────────
// TYPES
// ─────────────────────────────────────────────

interface MenuItems {
  universities:    { title: string; slug: string }[];
  courses:         { title: string; slug: string; qualification: string; university_slug: string }[];
  scholarships:    { title: string; slug: string; ielts: number }[];
  countries:       { title: string; slug: string }[];
  qualifications:  { id: number; title: string; slug: string }[];
}

interface NavItem {
  name: string;
  href: string;
  disabled?: boolean;
  badge?: string;
  icon?: React.ElementType;
}

interface NavColumn {
  title: string;
  href:  string;
  icon?: React.ElementType;
  color?: string;
  items: NavItem[];
}

interface NavCategory {
  name:          string;
  href:          string;
  hasDropdown:   boolean;
  megaMenu?:     boolean;
  icon?:         React.ElementType;
  accentColor?:  string;
  featuredLabel?: string;
  columns?:      NavColumn[];
  validColumns?: NavColumn[];
  menuStyle?:    { width: string };
  items?:        NavItem[];
}

// ─────────────────────────────────────────────
// CONSTANTS
// ─────────────────────────────────────────────

const DASHBOARD_ROUTES: Record<string, string> = {
  admin:            '/admin',
  student:          '/dashboard',
  consultant:       '/consultant-dashboard',
  'foreign-student': '/foreign-student-dashboard',
};

const BASE_NAV_CATEGORIES: NavCategory[] = [
  { name: 'Home', href: '/', hasDropdown: false },
  { name: 'Programs', href: '/courses', hasDropdown: true, megaMenu: true, accentColor: '#0B6F78', columns: [] },
  { name: 'Universities', href: '/institutions', hasDropdown: true, megaMenu: true, accentColor: '#0a306b', columns: [] },
  { name: 'Scholarships', href: '/scholarships', hasDropdown: true, megaMenu: true, accentColor: '#0B6F78', columns: [] },
  {
    name: 'Study Destinations', href: '/none', hasDropdown: true, accentColor: '#0a306b',
    items: [
      { name: 'Study In China',       href: '/study-in-china',        icon: MapPin },
      { name: 'Study In UK',          href: '/study-in-united-kingdom', icon: MapPin },
      { name: 'Study In Italy',       href: '/study-in-italy',        icon: MapPin },
      { name: 'Study In Turkey',      href: '/study-in-turkey',       icon: MapPin },
      { name: 'Study In Finland',     href: '/study-in-finland',      icon: MapPin },
      { name: 'Study In South Korea', href: '/study-in-south-korea',  icon: MapPin },
      { name: 'Study In Sweden',      href: '/study-in-sweden',       icon: MapPin },
      { name: 'Study In Romania',     href: '/study-in-romania',      icon: MapPin },
      { name: 'Study In Cyprus',      href: '/study-in-cyprus',       icon: MapPin },
      { name: 'Study In France',      href: '/study-in-france',       icon: MapPin },
    ],
  },
  { name: 'Success Stories', href: '/success-stories', hasDropdown: false },
  {
    name: 'Resources', href: '/none', hasDropdown: true, accentColor: '#0B6F78',
    items: [
      { name: 'About Us',    href: '/about-us' },
      { name: 'Contact Us',  href: '/contact-us' },
      { name: 'Blog',        href: '/blog' },
      { name: 'Services',    href: '/services' },
      { name: 'Careers',     href: '/jobs', badge: 'Hiring' },
      { name: 'Our Team',    href: '/our-team' },
      { name: 'Consultants', href: '/consultant' },
      { name: 'Complaint',   href: '/complaint' },
      { name: 'Visit Visa',  href: '/visit-visa' },
      { name: 'Videos',      href: '/videos' },
    ],
  },
  {
    name: 'Apply', href: '/none', hasDropdown: true, accentColor: '#0a306b',
    items: [
      { name: 'Apply Online',               href: '/apply-online',                badge: 'Hot' },
      { name: 'Free Consultation',          href: '/free-consultation',            badge: 'Hot' },         
      { name: 'Discount Offer',             href: '/discount-offer',               badge: 'Hot' },
      { name: 'Track Application',          href: '/track-application' },
      { name: 'Student Support Documents',  href: '/student-support-documents' },
      { name: 'Minhaj University',          href: '/minhaj-university-lahore' },
    ],
  },
  {
    name: 'AI Tools', href: '/none', hasDropdown: true, accentColor: '#0B6F78',
    items: [
      { name: 'Compare Universities & Courses',      href: '/comparison',                      icon: TrendingUp },
      { name: 'Study Abroad Eligibility Calculator', href: '/eligibility-calculator',          icon: Zap },
      { name: 'Freelance Students',                  href: '/foreign-students',                icon: User },
      { name: 'Find My Consultant',                  href: '/find-my-consultant',              icon: Search },
      { name: 'Resume Builder',                      href: '/resume-builder',                  icon: Star },
      { name: 'Study Plan Generator',                href: '/ai-study-plan',                   icon: BookOpen },
      { name: 'AI Visa Predictor',                   href: '/ai-visa-predictor',               icon: Zap },
      { name: 'AI Embassy Interview Predictor',      href: '/ai-embassy-interview-predictor',  icon: Zap },
      { name: 'AI Scholarship Match',                href: '/ai-scholarship-match',            icon: Star },
    ],
  },
  {
    name: 'Search',
    href: '/search?type=all&country=Italy&sort=relevance&page=1&limit=12',
    hasDropdown: false,
    icon: Search,
  },
];

// ─────────────────────────────────────────────
// PURE HELPERS
// ─────────────────────────────────────────────

const hasValidItems = (items: NavItem[]) => items.some(item => !item.disabled);

const getMegaMenuStyle = (columnCount: number): { width: string } => {
  const widths: Record<number, string> = { 1: '300px', 2: '560px', 3: '760px', 4: '960px' };
  return { width: widths[columnCount] ?? '1060px' };
};

const buildNavigation = (menuItems?: MenuItems): NavCategory[] => {
  const navCategories: NavCategory[] = BASE_NAV_CATEGORIES.map(cat => ({ ...cat }));

  if (menuItems) {
    const programsIdx = navCategories.findIndex(c => c.name === 'Programs');
    if (programsIdx !== -1 && menuItems.qualifications && menuItems.courses) {
      const qualificationsColumn: NavColumn = {
        title: 'All Qualifications',
        href:  '/#',
        icon: Award,
        color: '#0B6F78',
        items: menuItems.qualifications.map(q => ({
          name: q.title,
          href: `/search?type=course&qualification=${q.id}`,
        })),
      };

      const bachelorCourses = menuItems.courses.filter(c => c.qualification.toLowerCase().includes('bachelor')).slice(0, 10);
      const masterCourses   = menuItems.courses.filter(c => c.qualification.toLowerCase().includes('master')).slice(0, 10);

      navCategories[programsIdx].columns = [
        qualificationsColumn,
        {
          title: 'Bachelor Programs', href: '/#', icon: GraduationCap, color: '#0a306b',
          items: bachelorCourses.length > 0
            ? bachelorCourses.map(c => ({ name: c.title, href: `/${c.university_slug}/${c.slug}` }))
            : [{ name: 'No Bachelor programs available', href: '#', disabled: true }],
        },
        {
          title: 'Master Programs', href: '/#', icon: Star, color: '#0B6F78',
          items: masterCourses.length > 0
            ? masterCourses.map(c => ({ name: c.title, href: `/${c.university_slug}/${c.slug}` }))
            : [{ name: 'No Master programs available', href: '#', disabled: true }],
        },
      ];
    }

    const univIdx = navCategories.findIndex(c => c.name === 'Universities');
    if (univIdx !== -1 && menuItems.countries && menuItems.universities) {
      navCategories[univIdx].columns = [
        {
          title: 'Countries', href: '/#', icon: Globe, color: '#0a306b',
          items: menuItems.countries.slice(0, 15).map(c => ({
            name: c.title,
            href: `/search?type=university&country=${c.title}`,
          })),
        },
        {
          title: 'Universities', href: '/institutions', icon: Building2, color: '#0B6F78',
          items: menuItems.universities.slice(0, 12).map(u => ({
            name: u.title,
            href: `/university/${u.slug}`,
          })),
        },
      ];
    }

    const scholIdx = navCategories.findIndex(c => c.name === 'Scholarships');
    if (scholIdx !== -1 && menuItems.scholarships) {
      const withIelts    = menuItems.scholarships.filter(s => s.ielts === 1).slice(0, 8);
      const withoutIelts = menuItems.scholarships.filter(s => s.ielts === 0).slice(0, 8);

      navCategories[scholIdx].columns = [
        {
          title: 'With IELTS', href: '/#', icon: Award, color: '#0B6F78',
          items: withIelts.length > 0
            ? withIelts.map(s => ({ name: s.title, href: `/scholarships/${s.slug}` }))
            : [{ name: 'No scholarships available', href: '#', disabled: true }],
        },
        {
          title: 'Without IELTS', href: '/#', icon: Star, color: '#0a306b',
          items: withoutIelts.length > 0
            ? withoutIelts.map(s => ({ name: s.title, href: `/scholarships/${s.slug}` }))
            : [{ name: 'No scholarships available', href: '#', disabled: true }],
        },
      ];
    }
  }

  navCategories.forEach(cat => {
    if (cat.megaMenu && cat.columns) {
      cat.validColumns = cat.columns.filter(col => hasValidItems(col.items));
      cat.menuStyle    = getMegaMenuStyle(cat.validColumns.length);
    }
  });

  return navCategories;
};

// ─────────────────────────────────────────────
// GLOBAL STYLES
// ─────────────────────────────────────────────
const GLOBAL_STYLES = `
  @keyframes mega-in {
    0%   { opacity: 0; transform: translateY(-8px) scale(0.98); }
    100% { opacity: 1; transform: translateY(0)   scale(1); }
  }
  @keyframes dropdown-in {
    0%   { opacity: 0; transform: translateY(-6px); }
    100% { opacity: 1; transform: translateY(0); }
  }
  .mega-menu-enter  { animation: mega-in 0.18s cubic-bezier(0.16,1,0.3,1) forwards; }
  .dropdown-enter   { animation: dropdown-in 0.15s cubic-bezier(0.16,1,0.3,1) forwards; }

  /* ── Success Stories glow dot animation ── */
  @keyframes ss-glow-pulse {
    0%, 100% {
      box-shadow: 0 0 0 0 rgba(11, 111, 120, 0.7);
      transform: scale(1);
    }
    50% {
      box-shadow: 0 0 0 5px rgba(11, 111, 120, 0);
      transform: scale(1.15);
    }
  }

  .ss-glow-dot {
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: linear-gradient(135deg, #0B6F78, #0a306b);
    animation: ss-glow-pulse 1.8s ease-in-out infinite;
    display: inline-block;
    flex-shrink: 0;
  }
`;

// ─────────────────────────────────────────────
// GLOW DOT COMPONENT
// ─────────────────────────────────────────────
const GlowDot = () => (
  <span className="ss-glow-dot" aria-hidden="true" />
);

// ─────────────────────────────────────────────
// COMPONENT
// ─────────────────────────────────────────────

const Header = ({ menuItems }: { menuItems?: MenuItems }) => {
  const [isOpen,              setIsOpen]              = useState(false);
  const [showMenu,            setShowMenu]            = useState(false);
  const [activeCategory,      setActiveCategory]      = useState<string | null>(null);
  const [isScrolled,          setIsScrolled]          = useState(false);
  const [mobileSubmenu,       setMobileSubmenu]       = useState<string | null>(null);
  const [mobileColumnSubmenu, setMobileColumnSubmenu] = useState<string | null>(null);
  const [isLoginOpen,         setIsLoginOpen]         = useState(false);
  const [megaMenuPosition,    setMegaMenuPosition]    = useState<'left' | 'right'>('left');

  const router       = useRouter();
  const { wishlist } = useWishlist();
  const { user, logout, isLoggedIn } = useUserStore();

  const mobileMenuRef = useRef<HTMLDivElement>(null);
  const navItemRefs   = useRef<Record<string, HTMLDivElement | null>>({});

  // Inject global styles once
  useEffect(() => {
    const id = 'header-global-styles';
    if (!document.getElementById(id)) {
      const style = document.createElement('style');
      style.id = id;
      style.textContent = GLOBAL_STYLES;
      document.head.appendChild(style);
    }
    return () => { /* leave styles in place for perf */ };
  }, []);

  const NAV_CATEGORIES = useMemo(() => buildNavigation(menuItems), [menuItems]);

  // Scroll handler
  useEffect(() => {
    let ticking = false;
    const handleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => { setIsScrolled(window.scrollY > 50); ticking = false; });
        ticking = true;
      }
    };
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  // Click-outside mobile
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (mobileMenuRef.current && !mobileMenuRef.current.contains(e.target as Node)) {
        setIsOpen(false); setMobileSubmenu(null); setMobileColumnSubmenu(null);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // Body scroll lock
  useEffect(() => {
    document.body.style.overflow = isOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [isOpen]);

  // Mega-menu position
  useEffect(() => {
    if (!activeCategory) return;
    const activeElement = navItemRefs.current[activeCategory];
    const cat = NAV_CATEGORIES.find(c => c.name === activeCategory);
    if (activeElement && cat?.megaMenu && cat.menuStyle) {
      const rect = activeElement.getBoundingClientRect();
      const menuWidth = parseInt(cat.menuStyle.width);
      setMegaMenuPosition(rect.left + menuWidth > window.innerWidth - 20 ? 'right' : 'left');
    }
    const handler = (e: MouseEvent) => {
      if (!(e.target as Element).closest('.dropdown-menu')) setActiveCategory(null);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [activeCategory, NAV_CATEGORIES]);

  // Handlers
  const handleDashboard = useCallback(() => {
    if (!user?.role) return;
    router.push(DASHBOARD_ROUTES[user.role] || '/');
    setShowMenu(false); setIsOpen(false); setMobileSubmenu(null); setMobileColumnSubmenu(null);
  }, [user, router]);

  const handleLogout = useCallback(async () => {
    try {
      const response = await fetch('/api/frontend/logout', { method: 'POST' });
      if (response.ok) {
        logout(); setShowMenu(false); setIsOpen(false);
        setMobileSubmenu(null); setMobileColumnSubmenu(null);
        router.push('/');
      }
    } catch (error) { console.error('Logout error:', error); }
  }, [logout, router]);

  const closeMobileMenu = useCallback(() => {
    setIsOpen(false); setMobileSubmenu(null); setMobileColumnSubmenu(null);
  }, []);

  const handleMobileSubmenu = useCallback((categoryName: string) => {
    setMobileSubmenu(prev => prev === categoryName ? null : categoryName);
    setMobileColumnSubmenu(null);
  }, []);

  const handleMobileColumnSubmenu = useCallback((columnTitle: string) => {
    setMobileColumnSubmenu(prev => prev === columnTitle ? null : columnTitle);
  }, []);

  // ─────────────────────────────────────────────
  // RENDER
  // ─────────────────────────────────────────────
  return (
    <header className="relative z-50 font-sans" ref={mobileMenuRef}>

      {/* Top Bar */}
      <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-2">
        <div className="container mx-auto px-4">
          <div className="flex justify-end items-center">
            <div className="flex items-center gap-2 bg-white h-8 text-black px-2 py-1 rounded-lg">
              <div className="flex flex-col">
                <span className="text-xs text-[#136E79] font-normal">Pakistan's Largest</span>
                <span className="text-[10px] font-bold text-gray-900 leading-tight">Study Abroad Portal</span>
              </div>
              <Image src="/assets/first-icon.webp" alt="Portal Icon" width={20} height={20} className="drop-shadow-md" priority />
            </div>
          </div>
        </div>
      </div>

      {/* Desktop Header */}
      <div className={`hidden lg:block bg-white border-b border-gray-100 transition-shadow duration-300 ${isScrolled ? 'fixed w-full top-0 shadow-md' : ''}`}>
        <div className="container mx-auto px-4">
          <div className="flex items-center justify-between py-3">

            {/* Logo */}
            <Link href="/" className="shrink-0" aria-label="Home">
              <div className="flex items-center gap-2">
                <div className="w-10 h-10 relative">
                  <Image src="/assets/logo.webp" alt="UniversitiesPage Logo" fill className="object-contain rounded-xl" priority sizes="40px" />
                </div>
                <div className="text-xl font-bold bg-gradient-to-r from-[#0B6F78] to-[#0a306b] bg-clip-text text-transparent">
                  Universities Page
                </div>
              </div>
            </Link>

            {/* Navigation */}
            <nav className="flex items-center space-x-0.5" aria-label="Main navigation">
              {NAV_CATEGORIES.map((category) => {
                const validColumns    = category.validColumns ?? [];
                const hasValidContent = category.hasDropdown && (
                  category.megaMenu ? validColumns.length > 0 : (category.items?.length ?? 0) > 0
                );
                const isActive = activeCategory === category.name;
                const isSuccessStories = category.name === 'Success Stories';

                return (
                  <div
                    key={category.name}
                    className="relative"
                    ref={(el) => { navItemRefs.current[category.name] = el; }}
                    onMouseEnter={() => hasValidContent && setActiveCategory(category.name)}
                    onMouseLeave={() => setActiveCategory(null)}
                  >
                    {hasValidContent ? (
                      <button
                        className={`flex items-center gap-1 px-3 py-2 text-sm font-bold rounded-lg transition-all duration-150 ${
                          isActive ? 'text-[#0B6F78] bg-[#0B6F78]/8' : 'text-gray-600 hover:text-[#0B6F78] hover:bg-gray-50'
                        }`}
                      >
                        {category.name}
                        <ChevronDown className={`w-3.5 h-3.5 transition-transform duration-200 ${isActive ? 'rotate-180 text-[#0B6F78]' : ''}`} />
                      </button>
                    ) : isSuccessStories ? (
                      /* ── Success Stories: glowing dot before the label ── */
                      <Link
                        href={category.href}
                        className="flex items-center gap-2 px-3 py-2 text-sm font-bold text-gray-600 hover:text-[#0B6F78] hover:bg-gray-50 rounded-lg transition-all duration-150"
                        prefetch={false}
                      >
                        <GlowDot />
                        {category.name}
                      </Link>
                    ) : (
                      <Link
                        href={category.href}
                        className="flex items-center gap-1.5 px-3 py-2 text-sm font-bold text-gray-600 hover:text-[#0B6F78] hover:bg-gray-50 rounded-lg transition-all duration-150"
                        prefetch={false}
                      >
                        {category.icon && <category.icon className="w-4 h-4" />}
                        {category.name}
                      </Link>
                    )}

                    {/* ───── MODERN MEGA MENU ───── */}
                    {hasValidContent && isActive && category.megaMenu && (
                      <div
                        className="absolute top-full mt-2 dropdown-menu mega-menu-enter"
                        style={{
                          ...category.menuStyle,
                          ...(megaMenuPosition === 'right' ? { right: 0 } : { left: 0 }),
                        }}
                      >
                        {/* invisible bridge */}
                        <div className="absolute -top-2 left-0 right-0 h-2" />

                        <div className="bg-white rounded-2xl border border-gray-100 shadow-2xl shadow-gray-300/40 overflow-hidden">
                          {/* Accent top bar */}
                          <div className="h-1 w-full bg-gradient-to-r from-[#0B6F78] via-[#136E79] to-[#0a306b]" />

                          {/* Header bar */}
                          <div className="flex items-center justify-between px-5 py-3 bg-gray-50/70 border-b border-gray-100">
                            <div className="flex items-center gap-2">
                              <span className="text-xs font-bold uppercase tracking-widest text-[#0B6F78]">
                                {category.name}
                              </span>
                            </div>
                            <Link
                              href={category.href}
                              className="flex items-center gap-1 text-xs font-semibold text-[#0B6F78] hover:text-[#0a306b] transition-colors group"
                              onClick={() => setActiveCategory(null)}
                            >
                              View All
                              <ArrowRight className="w-3 h-3 group-hover:translate-x-0.5 transition-transform" />
                            </Link>
                          </div>

                          {/* Columns */}
                          <div
                            className="p-5 grid gap-px"
                            style={{
                              gridTemplateColumns: validColumns.length > 1 ? `repeat(${validColumns.length}, 1fr)` : '1fr',
                            }}
                          >
                            {validColumns.map((column, idx) => {
                              const ColIcon = column.icon;
                              return (
                                <div
                                  key={idx}
                                  className={`${validColumns.length > 1 && idx < validColumns.length - 1 ? 'border-r border-gray-100 pr-5 mr-1' : ''}`}
                                >
                                  {/* Column header */}
                                  <Link
                                    href={column.href}
                                    className="flex items-center gap-2 mb-3 group"
                                    onClick={() => setActiveCategory(null)}
                                  >
                                    {ColIcon && (
                                      <span
                                        className="w-6 h-6 rounded-lg flex items-center justify-center shrink-0"
                                        style={{ backgroundColor: (column.color || '#0B6F78') + '18' }}
                                      >
                                        <ColIcon className="w-3.5 h-3.5" style={{ color: column.color || '#0B6F78' }} />
                                      </span>
                                    )}
                                    <span
                                      className="text-xs font-bold uppercase tracking-wider transition-colors"
                                      style={{ color: column.color || '#0B6F78' }}
                                    >
                                      {column.title}
                                    </span>
                                  </Link>

                                  {/* Items */}
                                  <div className="space-y-px">
                                    {column.items.map((item, itemIdx) =>
                                      item.disabled ? (
                                        <span key={itemIdx} className="block text-sm text-gray-300 py-1.5 px-2.5 italic">
                                          {item.name}
                                        </span>
                                      ) : (
                                        <Link
                                          key={item.name}
                                          href={item.href}
                                          className="group flex items-center justify-between py-1.5 px-2.5 rounded-lg hover:bg-gradient-to-r hover:from-[#0B6F78]/6 hover:to-transparent transition-all duration-100"
                                          onClick={() => setActiveCategory(null)}
                                          prefetch={false}
                                        >
                                          <span className="text-sm text-gray-600 group-hover:text-[#0B6F78] transition-colors leading-snug">
                                            {item.name}
                                          </span>
                                          <ArrowRight
                                            className="w-3 h-3 text-gray-300 group-hover:text-[#0B6F78] opacity-0 group-hover:opacity-100 -translate-x-1 group-hover:translate-x-0 transition-all duration-150 shrink-0"
                                          />
                                        </Link>
                                      )
                                    )}
                                  </div>
                                </div>
                              );
                            })}
                          </div>

                          {/* Footer CTA */}
                          <div className="mx-5 mb-4 p-3 rounded-xl bg-gradient-to-r from-[#0B6F78]/8 to-[#0a306b]/8 border border-[#0B6F78]/10 flex items-center justify-between">
                            <span className="text-xs text-gray-500">Can't find what you're looking for?</span>
                            <Link
                              href="/free-consultation"
                              className="text-xs font-semibold text-[#0B6F78] hover:text-[#0a306b] transition-colors flex items-center gap-1"
                              onClick={() => setActiveCategory(null)}
                            >
                              Get Free Advice <ArrowRight className="w-3 h-3" />
                            </Link>
                          </div>
                        </div>
                      </div>
                    )}

                    {/* ───── MODERN REGULAR DROPDOWN ───── */}
                    {hasValidContent && isActive && !category.megaMenu && (
                      <div className="absolute top-full mt-2 w-60 dropdown-menu dropdown-enter" style={{ left: 0 }}>
                        <div className="absolute -top-2 left-0 right-0 h-2" />
                        <div className="bg-white rounded-2xl border border-gray-100 shadow-2xl shadow-gray-300/40 overflow-hidden">
                          <div className="h-1 w-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b]" />
                          <div className="p-2">
                            {category.items?.map((item) => {
                              const ItemIcon = item.icon;
                              return (
                                <Link
                                  key={item.name}
                                  href={item.href}
                                  className="group flex items-center justify-between gap-2 px-3 py-2.5 text-sm text-gray-700 hover:bg-gradient-to-r hover:from-[#0B6F78]/6 hover:to-transparent hover:text-[#0B6F78] rounded-xl transition-all duration-100"
                                  onClick={() => setActiveCategory(null)}
                                  prefetch={false}
                                >
                                  <div className="flex items-center gap-2.5">
                                    {ItemIcon
                                      ? <ItemIcon className="w-3.5 h-3.5 text-gray-300 group-hover:text-[#0B6F78] transition-colors shrink-0" />
                                      : <span className="w-1.5 h-1.5 rounded-full bg-gray-200 group-hover:bg-[#0B6F78] transition-colors shrink-0" />
                                    }
                                    <span>{item.name}</span>
                                  </div>
                                  <div className="flex items-center gap-1.5 shrink-0">
                                    {item.badge && (
                                      <span className="text-[9px] font-bold px-1.5 py-0.5 rounded-full bg-[#0B6F78]/10 text-[#0B6F78] uppercase tracking-wider">
                                        {item.badge}
                                      </span>
                                    )}
                                    <ArrowRight className="w-3 h-3 text-gray-200 group-hover:text-[#0B6F78] opacity-0 group-hover:opacity-100 -translate-x-1 group-hover:translate-x-0 transition-all" />
                                  </div>
                                </Link>
                              );
                            })}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </nav>

            {/* Right Side — Auth */}
            <div className="flex items-center gap-3">
              {!isLoggedIn ? (
                <div className="relative">
                  <button
                    className="flex items-center gap-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white hover:shadow-lg hover:shadow-[#0B6F78]/25 font-semibold px-5 py-2.5 rounded-xl transition-all duration-200"
                    onClick={() => setIsLoginOpen(prev => !prev)}
                  >
                    Login
                    <ChevronDown className={`w-4 h-4 transition-transform duration-200 ${isLoginOpen ? 'rotate-180' : ''}`} />
                  </button>

                  {isLoginOpen && (
                    <div className="absolute right-0 top-full mt-2 w-56 bg-white rounded-2xl shadow-2xl border border-gray-100 z-50 overflow-hidden dropdown-enter">
                      <div className="h-1 w-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b]" />
                      <div className="p-2">
                        <Link href="/student-login" onClick={() => setIsLoginOpen(false)}
                          className="group flex items-center gap-3 px-4 py-3 hover:bg-[#0B6F78]/6 text-gray-800 hover:text-[#0B6F78] transition-colors rounded-xl">
                          <User className="w-4 h-4 text-[#0B6F78]" />
                          <span className="font-medium text-sm">Student Login</span>
                          <ArrowRight className="w-3.5 h-3.5 ml-auto text-gray-200 group-hover:text-[#0B6F78] opacity-0 group-hover:opacity-100 transition-all" />
                        </Link>
                        <Link href="/consultant-login" onClick={() => setIsLoginOpen(false)}
                          className="group flex items-center gap-3 px-4 py-3 hover:bg-[#0B6F78]/6 text-gray-800 hover:text-[#0B6F78] transition-colors rounded-xl">
                          <Wrench className="w-4 h-4 text-[#0B6F78]" />
                          <span className="font-medium text-sm">Consultant Login</span>
                          <ArrowRight className="w-3.5 h-3.5 ml-auto text-gray-200 group-hover:text-[#0B6F78] opacity-0 group-hover:opacity-100 transition-all" />
                        </Link>
                        <Link href="/foreign-students/login" onClick={() => setIsLoginOpen(false)}
                          className="group flex items-center gap-3 px-4 py-3 hover:bg-[#0B6F78]/6 text-gray-800 hover:text-[#0B6F78] transition-colors rounded-xl">
                          <GraduationCap className="w-4 h-4 text-[#0B6F78]" />
                          <span className="font-medium text-sm">Freelance Student</span>
                          <ArrowRight className="w-3.5 h-3.5 ml-auto text-gray-200 group-hover:text-[#0B6F78] opacity-0 group-hover:opacity-100 transition-all" />
                        </Link>
                      </div>
                    </div>
                  )}
                </div>
              ) : (
                <div className="relative">
                  <button
                    onClick={() => setShowMenu(prev => !prev)}
                    className="flex items-center gap-2 cursor-pointer px-4 py-2 rounded-xl bg-white border border-gray-200 hover:border-[#0B6F78] hover:shadow-sm transition-all"
                    aria-label="User menu"
                  >
                    <UserCircle className="text-[#0B6F78] w-5 h-5" />
                    <span className="text-sm font-medium text-gray-700 max-w-30 truncate">{user?.name}</span>
                    <ChevronDown className={`w-4 h-4 text-gray-500 transition-transform duration-200 ${showMenu ? 'rotate-180' : ''}`} />
                  </button>

                  {showMenu && (
                    <div className="absolute right-0 mt-2 w-56 bg-white border border-gray-100 rounded-2xl shadow-2xl z-50 overflow-hidden dropdown-enter">
                      <div className="h-1 w-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b]" />
                      <div className="px-4 py-3 bg-gray-50/60">
                        <p className="text-sm font-semibold text-gray-800">Welcome back</p>
                        <p className="text-xs text-gray-500 truncate">{user?.email}</p>
                      </div>
                      <div className="p-2">
                        {user?.role !== 'admin' && (
                          <button
                            onClick={handleDashboard}
                            className="flex items-center gap-3 w-full px-3 py-2.5 text-sm text-gray-700 hover:bg-[#0B6F78]/6 hover:text-[#0B6F78] transition-colors rounded-xl"
                          >
                            <User className="w-4 h-4" /> Dashboard
                          </button>
                        )}
                        <button
                          onClick={handleLogout}
                          className="flex items-center gap-3 w-full px-3 py-2.5 text-sm text-red-500 hover:bg-red-50 transition-colors rounded-xl mt-1 border-t border-gray-100"
                        >
                          <LogOut className="w-4 h-4" /> Logout
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>

          </div>
        </div>
      </div>

      {/* ── Mobile Header ── */}
      <div className={`lg:hidden bg-white border-b border-gray-200 transition-all ${isScrolled ? 'fixed w-full top-0 shadow-sm' : ''}`}>
        <div className="flex items-center justify-between p-3">
          <button onClick={() => setIsOpen(true)} className="p-2 rounded-lg hover:bg-gray-100" aria-label="Open menu">
            <Menu className="w-6 h-6 text-gray-700" />
          </button>
          <Link href="/" className="flex items-center gap-2" onClick={closeMobileMenu}>
            <div className="w-8 h-8 relative">
              <Image src="/assets/logo.webp" alt="Logo" fill className="object-contain rounded-lg" priority sizes="32px" />
            </div>
            <div className="text-lg font-bold bg-gradient-to-r from-[#0B6F78] to-[#0a306b] bg-clip-text text-transparent">
              University Page
            </div>
          </Link>
          <div className="flex items-center gap-2">
            {isLoggedIn && wishlist.length > 0 && (
              <Link href="/wishlist" className="relative p-2" onClick={closeMobileMenu}>
                <Heart className="w-6 h-6 text-red-500" />
                <span className="absolute -top-1 -right-1 bg-red-500 text-white rounded-full w-4 h-4 flex items-center justify-center text-[10px] font-bold">
                  {wishlist.length}
                </span>
              </Link>
            )}
            {isLoggedIn ? (
              <button onClick={() => setShowMenu(prev => !prev)} className="p-2 rounded-lg hover:bg-gray-100">
                <UserCircle className="w-6 h-6 text-gray-700" />
              </button>
            ) : (
              <button
                onClick={() => setIsOpen(true)}
                className="px-3 py-1.5 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white text-sm font-semibold rounded-lg"
              >
                Login
              </button>
            )}
          </div>
        </div>
      </div>

      {/* ── Mobile Menu ── */}
      {isOpen && (
        <div className="lg:hidden fixed inset-0 z-50">
          <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={closeMobileMenu} />
          <div className="relative w-72 h-full bg-white overflow-y-auto shadow-2xl">
            <div className="flex items-center justify-between p-4 border-b border-white/20 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white">
              <div className="flex items-center gap-2">
                <div className="w-7 h-7 bg-white/20 rounded-lg flex items-center justify-center">
                  <GraduationCap className="w-4 h-4" />
                </div>
                <span className="text-lg font-bold">Menu</span>
              </div>
              <button onClick={closeMobileMenu} className="p-2 rounded-full hover:bg-white/10 transition-colors" aria-label="Close menu">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4">
              {/* Auth section */}
              {!isLoggedIn ? (
                <div className="mb-5 space-y-2">
                  <Link href="/student-login" onClick={closeMobileMenu}
                    className="flex items-center justify-center gap-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-2.5 rounded-xl font-semibold text-sm">
                    <User className="w-4 h-4" /> Student Login
                  </Link>
                  <Link href="/consultant-login" onClick={closeMobileMenu}
                    className="flex items-center justify-center gap-2 border border-[#0B6F78] text-[#0B6F78] py-2.5 rounded-xl font-semibold text-sm hover:bg-[#0B6F78]/5 transition-colors">
                    <Wrench className="w-4 h-4" /> Consultant Login
                  </Link>
                  <Link href="/foreign-students/login" onClick={closeMobileMenu}
                    className="flex items-center justify-center gap-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-2.5 rounded-xl font-semibold text-sm">
                    <GraduationCap className="w-4 h-4" /> Freelance Student Login
                  </Link>
                </div>
              ) : (
                <div className="mb-4 p-3 bg-gradient-to-r from-[#0B6F78]/8 to-[#0a306b]/8 rounded-xl border border-[#0B6F78]/15">
                  <p className="font-semibold text-gray-800 text-sm">{user?.name}</p>
                  <p className="text-xs text-gray-500 truncate">{user?.email}</p>
                </div>
              )}

              {/* Nav items */}
              <nav className="space-y-0.5">
                {NAV_CATEGORIES.map((category) => {
                  const validColumns    = category.validColumns ?? [];
                  const hasValidContent = category.hasDropdown && (
                    category.megaMenu ? validColumns.length > 0 : (category.items?.length ?? 0) > 0
                  );
                  const isExpanded = mobileSubmenu === category.name;
                  const isSuccessStories = category.name === 'Success Stories';

                  return (
                    <div key={category.name}>
                      {hasValidContent ? (
                        <>
                          <button
                            onClick={() => handleMobileSubmenu(category.name)}
                            className={`flex items-center justify-between w-full py-2.5 px-3 rounded-xl text-left transition-colors ${
                              isExpanded ? 'bg-[#0B6F78]/8 text-[#0B6F78]' : 'text-gray-700 hover:bg-gray-50'
                            }`}
                          >
                            <div className="flex items-center gap-2.5">
                              {category.icon && <category.icon className={`w-4 h-4 ${isExpanded ? 'text-[#0B6F78]' : 'text-gray-400'}`} />}
                              <span className="font-semibold text-sm">{category.name}</span>
                            </div>
                            <ChevronDown className={`w-4 h-4 transition-transform duration-200 ${isExpanded ? 'rotate-180' : ''}`} />
                          </button>

                          {isExpanded && (
                            <div className="mt-1 ml-3 mb-2 border-l-2 border-[#0B6F78]/15 pl-3 space-y-0.5">
                              {category.megaMenu ? (
                                validColumns.map((column, idx) => (
                                  <div key={idx}>
                                    <button
                                      onClick={() => handleMobileColumnSubmenu(column.title)}
                                      className="flex items-center justify-between w-full py-2 px-2 text-left rounded-lg hover:bg-gray-50 transition-colors"
                                    >
                                      <span className="text-xs font-bold uppercase tracking-wider text-[#0B6F78]">{column.title}</span>
                                      <ChevronDown className={`w-3.5 h-3.5 text-gray-400 transition-transform duration-200 ${mobileColumnSubmenu === column.title ? 'rotate-180' : ''}`} />
                                    </button>
                                    {mobileColumnSubmenu === column.title && (
                                      <div className="ml-2 mt-0.5 mb-1 space-y-0.5">
                                        {column.items.map((item, itemIdx) =>
                                          item.disabled ? (
                                            <span key={itemIdx} className="block py-1.5 px-2 text-xs text-gray-400 italic cursor-not-allowed">{item.name}</span>
                                          ) : (
                                            <Link key={item.name} href={item.href} onClick={closeMobileMenu}
                                              className="flex items-center gap-2 py-1.5 px-2 text-sm text-gray-600 hover:text-[#0B6F78] hover:bg-[#0B6F78]/5 rounded-lg transition-colors">
                                              <span className="w-1 h-1 rounded-full bg-gray-300 shrink-0" />
                                              {item.name}
                                            </Link>
                                          )
                                        )}
                                      </div>
                                    )}
                                  </div>
                                ))
                              ) : (
                                category.items?.map((item) => (
                                  <Link key={item.name} href={item.href} onClick={closeMobileMenu}
                                    className="flex items-center justify-between gap-2 py-2 px-2 text-sm text-gray-600 hover:text-[#0B6F78] hover:bg-[#0B6F78]/5 rounded-lg transition-colors">
                                    <div className="flex items-center gap-2">
                                      <span className="w-1 h-1 rounded-full bg-gray-300 shrink-0" />
                                      {item.name}
                                    </div>
                                    {item.badge && (
                                      <span className="text-[9px] font-bold px-1.5 py-0.5 rounded-full bg-[#0B6F78]/10 text-[#0B6F78] uppercase">
                                        {item.badge}
                                      </span>
                                    )}
                                  </Link>
                                ))
                              )}
                            </div>
                          )}
                        </>
                      ) : isSuccessStories ? (
                        /* ── Mobile Success Stories: glowing dot ── */
                        <Link
                          href={category.href}
                          onClick={closeMobileMenu}
                          className="flex items-center gap-2.5 py-2.5 px-3 text-gray-700 hover:bg-gray-50 hover:text-[#0B6F78] rounded-xl transition-colors"
                        >
                          <GlowDot />
                          <span className="font-semibold text-sm">{category.name}</span>
                        </Link>
                      ) : (
                        <Link
                          href={category.href}
                          onClick={closeMobileMenu}
                          className="flex items-center gap-2.5 py-2.5 px-3 text-gray-700 hover:bg-gray-50 hover:text-[#0B6F78] rounded-xl transition-colors"
                        >
                          {category.icon && <category.icon className="w-4 h-4 text-gray-400" />}
                          <span className="font-semibold text-sm">{category.name}</span>
                        </Link>
                      )}
                    </div>
                  );
                })}
              </nav>

              {/* Logged-in actions */}
              {isLoggedIn && (
                <div className="mt-5 pt-4 border-t border-gray-200 space-y-1">
                  <button onClick={handleDashboard}
                    className="flex items-center w-full py-2.5 px-3 text-gray-700 hover:bg-gray-50 rounded-xl text-left font-semibold text-sm">
                    <User className="w-4 h-4 mr-3 text-[#0B6F78]" /> Dashboard
                  </button>
                  <button onClick={handleLogout}
                    className="flex items-center w-full py-2.5 px-3 text-red-600 hover:bg-red-50 rounded-xl text-left font-semibold text-sm">
                    <LogOut className="w-4 h-4 mr-3" /> Logout
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

    </header>
  );
};

export default Header;