"use client";

import Link from "next/link";
import { useState, useRef, useEffect, useCallback } from "react";
import { usePathname } from "next/navigation";
import { useIsAdmin } from "@/hooks/useIsAdmin";
import {
  Heart,
  GitCompare,
  Menu,
  X,
  Car,
  ChevronDown,
  ChevronRight,
  Zap,
  Newspaper,
  LayoutDashboard,
  Tag,
  FileText,
  DollarSign,
  Swords,
  ShieldCheck,
  Bell,
  ClipboardCheck,
  Bot,
  BarChart3,
  Gauge,
  Users,
  Search,
  BookDashed,
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import dynamic from "next/dynamic";
import SearchBar from "@/components/cars/SearchBar";
import { useWishlistStore } from "@/store/useWishlistStore";
import { useCarStore } from "@/store/useCarStore";
import { cn } from "@/lib/utils";

const NotificationBell = dynamic(
  () => import("@/components/notifications/NotificationBell"),
  { ssr: false, loading: () => null }
);

// ── Nav structure ─────────────────────────────────────────────────────────────

const NAV_PRIMARY = [
  { label: "New Cars",   href: "/cars" },
  { label: "Find a Car", href: "/wizard" },
  { label: "Electric",   href: "/cars?fuelType=Electric", icon: Zap },
  { label: "News",       href: "/news", icon: Newspaper },
   { label: "Blog",       href: "/blogs", icon: BookDashed},
];

const NAV_MORE = [
  { label: "Compare Cars", href: "/compare",  desc: "Compare up to 4 cars side-by-side" },
  { label: "Wishlist",     href: "/wishlist", desc: "Your saved cars" },
  { label: "My Garage",    href: "/garage",   desc: "Cars you own" },
];

const NAV_ADMIN_GROUPS = [
  {
    group: "Overview",
    items: [
      { label: "Dashboard",     href: "/admin",              icon: LayoutDashboard },
      { label: "Analytics",     href: "/admin/analytics",    icon: BarChart3 },
    ],
  },
  {
    group: "Cars",
    items: [
      { label: "Cars",          href: "/admin/enrichment",   icon: Car },
      { label: "Brands",        href: "/admin/brands",       icon: Tag },
      { label: "Price Tracking",href: "/admin/prices",       icon: DollarSign },
      { label: "Rivals",        href: "/admin/rivals",       icon: Swords },
    ],
  },
  {
    group: "Content",
    items: [
      { label: "Blogs",         href: "/admin/blogs",        icon: FileText },
      { label: "News",          href: "/admin/news",         icon: Newspaper },
    ],
  },
  {
    group: "Tools",
    items: [
      { label: "SEO Health",    href: "/admin/seo-health",   icon: ShieldCheck },
      { label: "Alerts",        href: "/admin/alerts",       icon: Bell },
      { label: "Leads",         href: "/admin/leads",        icon: Users },
      { label: "Reports",       href: "/admin/report",       icon: ClipboardCheck },
      { label: "AI Providers",  href: "/admin/ai-settings",  icon: Bot },
      { label: "Banners",       href: "/admin/banners",      icon: Gauge },
    ],
  },
];

const BODY_TYPES = ["SUV", "Sedan", "Hatchback", "MUV", "Coupe"];

// ── Sub-components ─────────────────────────────────────────────────────────────

function NavLink({
  href,
  label,
  active,
  onClick,
}: {
  href: string;
  label: string;
  active: boolean;
  onClick?: () => void;
}) {
  return (
    <Link
      href={href}
      onClick={onClick}
      className={cn(
        "group relative px-4 h-full flex items-center text-sm font-semibold transition-colors duration-200 whitespace-nowrap",
        active ? "text-blue-600" : "text-gray-600 hover:text-blue-600"
      )}
    >
      {label}
      <span
        className={cn(
          "absolute left-0 bottom-0 h-[2px] rounded-full bg-gradient-to-r from-blue-600 to-cyan-500 transition-all duration-300",
          active ? "w-full" : "w-0 group-hover:w-full"
        )}
      />
    </Link>
  );
}

/** "More" dropdown — Compare, Wishlist, Garage */
function MoreDropdown({ pathname }: { pathname: string }) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handler(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const anyActive = NAV_MORE.some(
    (l) => pathname === l.href || (l.href !== "/" && pathname.startsWith(l.href))
  );

  return (
    <div ref={ref} className="relative h-full flex items-center">
      <button
        onClick={() => setOpen((o) => !o)}
        onKeyDown={(e) => e.key === "Escape" && setOpen(false)}
        aria-expanded={open}
        aria-haspopup="true"
        className={cn(
          "group relative px-4 h-full flex items-center gap-1 text-sm font-semibold transition-colors duration-200",
          anyActive || open ? "text-blue-600" : "text-gray-600 hover:text-blue-600"
        )}
      >
        More
        <ChevronDown className={cn("w-3.5 h-3.5 transition-transform duration-200", open && "rotate-180")} />
        <span
          className={cn(
            "absolute left-0 bottom-0 h-[2px] rounded-full bg-gradient-to-r from-blue-600 to-cyan-500 transition-all duration-300",
            anyActive || open ? "w-full" : "w-0 group-hover:w-full"
          )}
        />
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: 8, scale: 0.97 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 8, scale: 0.97 }}
            transition={{ duration: 0.15 }}
            className="absolute top-full left-0 mt-1 w-56 bg-white rounded-2xl border border-gray-100 shadow-xl shadow-black/[0.08] z-50 overflow-hidden py-2"
            role="menu"
          >
            {NAV_MORE.map((item) => {
              const active =
                pathname === item.href ||
                (item.href !== "/" && pathname.startsWith(item.href));
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  role="menuitem"
                  onClick={() => setOpen(false)}
                  className={cn(
                    "flex flex-col px-4 py-3 transition-colors duration-150 hover:bg-blue-50",
                    active && "bg-blue-50"
                  )}
                >
                  <span className={cn("text-sm font-semibold", active ? "text-blue-600" : "text-gray-800")}>
                    {item.label}
                  </span>
                  <span className="text-xs text-gray-400 mt-0.5">{item.desc}</span>
                </Link>
              );
            })}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

/** Admin mega-dropdown */
function AdminDropdown({ pathname }: { pathname: string }) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handler(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const isAdminActive = pathname.startsWith("/admin");

  return (
    <div ref={ref} className="relative h-full flex items-center">
      <button
        onClick={() => setOpen((o) => !o)}
        onKeyDown={(e) => e.key === "Escape" && setOpen(false)}
        aria-expanded={open}
        aria-haspopup="true"
        className={cn(
          "group relative px-4 h-full flex items-center gap-1.5 text-sm font-semibold transition-colors duration-200",
          isAdminActive || open
            ? "text-violet-600"
            : "text-gray-600 hover:text-violet-600"
        )}
      >
        <Gauge className="w-3.5 h-3.5" />
        Admin
        <ChevronDown className={cn("w-3.5 h-3.5 transition-transform duration-200", open && "rotate-180")} />
        <span
          className={cn(
            "absolute left-0 bottom-0 h-[2px] rounded-full bg-gradient-to-r from-violet-600 to-blue-500 transition-all duration-300",
            isAdminActive || open ? "w-full" : "w-0 group-hover:w-full"
          )}
        />
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: 8, scale: 0.97 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 8, scale: 0.97 }}
            transition={{ duration: 0.15 }}
            className="absolute top-full right-0 mt-1 w-[480px] bg-white rounded-2xl border border-gray-100 shadow-xl shadow-black/[0.1] z-50 p-4"
            role="menu"
          >
            <div className="grid grid-cols-2 gap-1">
              {NAV_ADMIN_GROUPS.map((group) => (
                <div key={group.group} className="mb-3">
                  <p className="text-[10px] font-black uppercase tracking-widest text-gray-400 px-2 mb-1.5">
                    {group.group}
                  </p>
                  {group.items.map((item) => {
                    const active =
                      item.href === "/admin"
                        ? pathname === "/admin"
                        : pathname.startsWith(item.href);
                    return (
                      <Link
                        key={item.href}
                        href={item.href}
                        role="menuitem"
                        onClick={() => setOpen(false)}
                        className={cn(
                          "flex items-center gap-2.5 px-2 py-2 rounded-xl text-sm transition-colors duration-150 hover:bg-violet-50",
                          active ? "bg-violet-50 text-violet-600 font-semibold" : "text-gray-700 font-medium"
                        )}
                      >
                        <item.icon className={cn("w-3.5 h-3.5 shrink-0", active ? "text-violet-600" : "text-gray-400")} />
                        {item.label}
                      </Link>
                    );
                  })}
                </div>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// ── Main component ─────────────────────────────────────────────────────────────

export default function SiteHeader() {
  const pathname = usePathname();
  const isAdmin  = useIsAdmin();
  const [mobileOpen, setMobileOpen]         = useState(false);
  const [moreOpen, setMoreOpen]             = useState(false);
  const [adminOpen, setAdminOpen]           = useState(false);
  const [searchVisible, setSearchVisible]   = useState(false);

  const wishCount    = useWishlistStore((s) => s.items.length);
  const compareCount = useCarStore((s) => s.compareList.length);

  // Close mobile menu on route change
  useEffect(() => {
    setMobileOpen(false);
    setSearchVisible(false);
  }, [pathname]);

  // Prevent body scroll when mobile menu open
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);

  const closeMobile = useCallback(() => setMobileOpen(false), []);

  // Shadow fades in after the user scrolls past the top of the page
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 4);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <>
    <header className={cn(
      "sticky top-0 z-[999] border-b border-gray-200/60 bg-white/95 backdrop-blur-2xl transition-shadow duration-300",
      scrolled ? "shadow-[0_2px_20px_rgba(0,0,0,0.08)]" : "shadow-none"
    )}>

      {/* ── Top bar: Logo | Search | Actions ───────────────────────────── */}
      <div className="max-w-[1280px] mx-auto px-3 sm:px-4 min-w-0">
        <div className="h-16 flex items-center gap-2 sm:gap-3 min-w-0">

          {/* Logo */}
          <Link href="/" className="flex items-center gap-2.5 shrink-0 group">
            <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-blue-600 via-cyan-500 to-sky-400 flex items-center justify-center shadow-md shadow-blue-500/25 group-hover:shadow-lg group-hover:shadow-blue-500/30 transition-shadow">
              <Car className="w-4.5 h-4.5 text-white w-[18px] h-[18px]" />
            </div>
            <div className="leading-none">
              <span className="text-[1.15rem] font-black tracking-tight text-gray-900">
                Drive<span className="text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-cyan-500">Hub</span>
              </span>
              <p className="text-[9px] uppercase tracking-[0.18em] text-gray-400 font-semibold hidden min-[375px]:block">
                Premium Cars
              </p>
            </div>
          </Link>

          {/* Desktop search bar */}
          <div className="flex-1 max-w-xl hidden md:block relative z-50">
            <div className="rounded-xl border border-gray-200 bg-gray-50/80 hover:bg-white hover:border-blue-300 hover:shadow-md transition-all px-2 py-1">
              <SearchBar />
            </div>
          </div>

          {/* Right actions */}
          <div className="flex items-center gap-1 sm:gap-1.5 ml-auto shrink-0">

            {/* Mobile search toggle */}
            <button
              className="md:hidden p-2 rounded-xl text-gray-600 hover:bg-gray-100 transition-colors"
              onClick={() => setSearchVisible((v) => !v)}
              aria-label="Search"
            >
              <Search className="w-5 h-5" />
            </button>

            {/* Compare */}
            <Link
              href="/compare"
              className="relative flex items-center gap-1.5 p-2 sm:px-3 sm:py-2 rounded-xl text-sm font-semibold text-gray-600 hover:text-blue-600 hover:bg-blue-50 border border-transparent hover:border-blue-100 transition-all"
              aria-label="Compare cars"
            >
              <GitCompare className="w-4 h-4" />
              <span className="hidden lg:inline">Compare</span>
              {compareCount > 0 && (
                <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 bg-red-500 text-white text-[9px] font-black rounded-full flex items-center justify-center">
                  {compareCount}
                </span>
              )}
            </Link>

            {/* Notification bell */}
            <NotificationBell />

            {/* Wishlist */}
            <Link
              href="/wishlist"
              className="relative flex items-center gap-1.5 p-2 sm:px-3 sm:py-2 rounded-xl text-sm font-semibold text-gray-600 hover:text-pink-600 hover:bg-pink-50 border border-transparent hover:border-pink-100 transition-all"
              aria-label="Saved cars"
            >
              <Heart className="w-4 h-4" />
              <span className="hidden lg:inline">Saved</span>
              {wishCount > 0 && (
                <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 bg-pink-500 text-white text-[9px] font-black rounded-full flex items-center justify-center">
                  {wishCount}
                </span>
              )}
            </Link>

            {/* Mobile hamburger */}
            <button
              type="button"
              className="md:hidden p-2 rounded-xl border border-gray-200 bg-white hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-400"
              onClick={() => { setMobileOpen((o) => !o); setSearchVisible(false); }}
              aria-label={mobileOpen ? "Close menu" : "Open menu"}
              aria-expanded={mobileOpen}
              aria-controls="mobile-nav"
            >
              <AnimatePresence mode="wait">
                {mobileOpen ? (
                  <motion.div key="close"
                    initial={{ rotate: -90, opacity: 0 }}
                    animate={{ rotate: 0, opacity: 1 }}
                    exit={{ rotate: 90, opacity: 0 }}
                    transition={{ duration: 0.18 }}
                  >
                    <X className="w-5 h-5 text-gray-700" />
                  </motion.div>
                ) : (
                  <motion.div key="menu"
                    initial={{ rotate: 90, opacity: 0 }}
                    animate={{ rotate: 0, opacity: 1 }}
                    exit={{ rotate: -90, opacity: 0 }}
                    transition={{ duration: 0.18 }}
                  >
                    <Menu className="w-5 h-5 text-gray-700" />
                  </motion.div>
                )}
              </AnimatePresence>
            </button>
          </div>
        </div>
      </div>

      {/* Mobile search reveal */}
      <AnimatePresence>
        {searchVisible && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="md:hidden overflow-hidden border-t border-gray-100 bg-white"
          >
            <div className="px-4 py-3">
              <div className="rounded-xl border border-gray-200 bg-gray-50 px-2 py-1 relative z-50">
                <SearchBar />
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* ── Desktop secondary nav ────────────────────────────────────── */}
      <div className="hidden md:block border-t border-gray-100/80 bg-white/80">
        <div className="max-w-[1280px] mx-auto px-4">
          <nav className="flex items-center h-11" aria-label="Primary navigation">

            {/* Primary links */}
            {NAV_PRIMARY.map(({ label, href }) => {
              const active =
                pathname === href ||
                (href !== "/" && href.includes("?")
                  ? pathname === href.split("?")[0]
                  : pathname.startsWith(href));
              return (
                <NavLink key={href} href={href} label={label} active={active} />
              );
            })}

            {/* More dropdown */}
            <MoreDropdown pathname={pathname} />

            {/* Admin dropdown — admin only */}
            {isAdmin && <AdminDropdown pathname={pathname} />}

            {/* Body-type quick filters — tablet nav is tight; show from lg up */}
            <div className="hidden lg:flex items-center ml-auto gap-0.5 shrink-0">
              {BODY_TYPES.map((type) => (
                <Link
                  key={type}
                  href={`/cars?bodyType=${type}`}
                  className={cn(
                    "px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors",
                    pathname === "/cars" && typeof window !== "undefined" && window.location.search.includes(`bodyType=${type}`)
                      ? "bg-blue-50 text-blue-600"
                      : "text-gray-500 hover:text-blue-600 hover:bg-blue-50"
                  )}
                >
                  {type}
                </Link>
              ))}
            </div>
          </nav>
        </div>
      </div>

    </header>

    {/*
      ── Mobile menu — rendered OUTSIDE <header> ──────────────────────────────
      backdrop-filter on <header> makes it a CSS containing block for position:fixed
      descendants, which collapses the drawer to 0 height. Moving here keeps fixed
      elements relative to the viewport (top-16 = 64 px below the sticky header).
    */}
    <AnimatePresence>
      {mobileOpen && (
        <motion.div
          key="mobile-backdrop"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="md:hidden fixed inset-0 top-16 z-[998] bg-black/30 backdrop-blur-sm"
          onClick={closeMobile}
        />
      )}
      {mobileOpen && (
        <motion.div
          key="mobile-drawer"
          id="mobile-nav"
          initial={{ x: "100%" }}
          animate={{ x: 0 }}
          exit={{ x: "100%" }}
          transition={{ type: "spring", damping: 30, stiffness: 300 }}
          className="md:hidden fixed top-16 right-0 bottom-0 z-[1000] w-[min(300px,85vw)] bg-white shadow-2xl overflow-y-auto"
        >
          <nav className="p-4 space-y-1" aria-label="Mobile navigation">

            {/* Primary links */}
            {NAV_PRIMARY.map(({ label, href }) => {
              const active =
                pathname === href ||
                (href !== "/" && pathname.startsWith(href.split("?")[0]));
              return (
                <Link
                  key={href}
                  href={href}
                  onClick={closeMobile}
                  className={cn(
                    "flex items-center px-4 py-3 rounded-xl text-sm font-semibold transition-colors",
                    active
                      ? "bg-blue-50 text-blue-600"
                      : "text-gray-700 hover:bg-gray-50"
                  )}
                >
                  {label}
                </Link>
              );
            })}

            {/* More section */}
            <MobileAccordion title="More" defaultOpen>
              {NAV_MORE.map((item) => {
                const active = pathname === item.href || pathname.startsWith(item.href);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    onClick={closeMobile}
                    className={cn(
                      "flex items-center justify-between px-4 py-2.5 rounded-xl text-sm font-medium transition-colors",
                      active ? "text-blue-600 bg-blue-50" : "text-gray-600 hover:bg-gray-50"
                    )}
                  >
                    <span>{item.label}</span>
                    <ChevronRight className="w-3.5 h-3.5 text-gray-300" />
                  </Link>
                );
              })}
            </MobileAccordion>

            {/* Browse by type */}
            <MobileAccordion title="Browse by Type">
              <div className="flex flex-wrap gap-2 px-4 pt-1 pb-2">
                {BODY_TYPES.map((type) => (
                  <Link
                    key={type}
                    href={`/cars?bodyType=${type}`}
                    onClick={closeMobile}
                    className="px-3 py-1.5 bg-gray-100 rounded-lg text-xs font-semibold text-gray-700 hover:bg-blue-50 hover:text-blue-600 transition-colors"
                  >
                    {type}
                  </Link>
                ))}
              </div>
            </MobileAccordion>

            {/* Admin section */}
            {isAdmin && (
              <MobileAccordion title="Admin" accent>
                {NAV_ADMIN_GROUPS.map((group) => (
                  <div key={group.group} className="mb-2">
                    <p className="px-4 py-1 text-[10px] font-black uppercase tracking-widest text-gray-400">
                      {group.group}
                    </p>
                    {group.items.map((item) => {
                      const active =
                        item.href === "/admin"
                          ? pathname === "/admin"
                          : pathname.startsWith(item.href);
                      return (
                        <Link
                          key={item.href}
                          href={item.href}
                          onClick={closeMobile}
                          className={cn(
                            "flex items-center gap-2.5 px-4 py-2 rounded-xl text-sm font-medium transition-colors",
                            active ? "text-violet-600 bg-violet-50" : "text-gray-600 hover:bg-gray-50"
                          )}
                        >
                          <item.icon className="w-3.5 h-3.5 shrink-0" />
                          {item.label}
                        </Link>
                      );
                    })}
                  </div>
                ))}
              </MobileAccordion>
            )}
          </nav>
        </motion.div>
      )}
    </AnimatePresence>
    </>
  );
}

// ── MobileAccordion ────────────────────────────────────────────────────────────

function MobileAccordion({
  title,
  children,
  defaultOpen = false,
  accent = false,
}: {
  title: string;
  children: React.ReactNode;
  defaultOpen?: boolean;
  accent?: boolean;
}) {
  const [open, setOpen] = useState(defaultOpen);

  return (
    <div className="border border-gray-100 rounded-xl overflow-hidden">
      <button
        onClick={() => setOpen((o) => !o)}
        className={cn(
          "w-full flex items-center justify-between px-4 py-3 text-sm font-semibold transition-colors",
          accent
            ? open ? "bg-violet-50 text-violet-700" : "text-gray-700 hover:bg-gray-50"
            : open ? "bg-gray-50 text-gray-900" : "text-gray-700 hover:bg-gray-50"
        )}
      >
        {title}
        <ChevronDown className={cn("w-4 h-4 text-gray-400 transition-transform duration-200", open && "rotate-180")} />
      </button>
      <AnimatePresence initial={false}>
        {open && (
          <motion.div
            initial={{ height: 0 }}
            animate={{ height: "auto" }}
            exit={{ height: 0 }}
            transition={{ duration: 0.2 }}
            className="overflow-hidden"
          >
            <div className="border-t border-gray-100 py-1">
              {children}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
