import { Link, useNavigate } from "@tanstack/react-router";
import logoAsset from "@/assets/peptidewinkel-logo.png.asset.json";
import {
  ShoppingCart,
  Newspaper,
  User,
  Sun,
  Moon,
  Menu,
  X,
  Clock,
  Truck,
  ShieldCheck,
  CreditCard,
  ChevronDown,
  Syringe,
  Store,
  TestTube,
  Building2,
  HelpCircle,
  LogIn,
  LogOut,
  UserPlus,
  Package,
  Award,
  MessageCircle,
  Link2,
} from "lucide-react";
import { useGqlCart } from "@/hooks/useGqlCart";
import { useThemeStore } from "@/stores/themeStore";
import LanguageSwitch from "@/components/LanguageSwitch";
import { useCartDrawerStore } from "@/stores/cartDrawerStore";
import { useAuthStore } from "@/stores/authStore";
import { useCategories } from "@/hooks/useWooCommerce";
import type { Category } from "@/data/mockProducts";
import { getCategoryIcon } from "@/lib/categoryIcons";
import SearchBox from "@/components/SearchBox";

import { useState, useRef, useEffect } from "react";
import { useT } from "@/lib/i18n";

const navLinks = [
  { nl: "Home", en: "Home", to: "/" as const },
  { nl: "Kennisbank", en: "Knowledge Base", to: "/kennisbank" as const },
  { nl: "Peptidewijzer", en: "Peptide Guide", to: "/peptidewijzer" as const },
  { nl: "Labtesten", en: "Lab Tests", to: "/labtesten" as const },
  { nl: "Reviews", en: "Reviews", to: "/reviews" as const },
];

const infoLinks = [
  { nl: "Over Ons", en: "About Us", to: "/over-ons" as const, icon: Building2 },
  { nl: "Blog", en: "Blog", to: "/blog" as const, icon: Newspaper },
  { nl: "FAQ", en: "FAQ", to: "/veelgestelde-vragen" as const, icon: HelpCircle },
  { nl: "Contact", en: "Contact", to: "/contact-us" as const, icon: MessageCircle },
];

const Header = () => {
  const t = useT();
  const totalItems = useGqlCart().totals.itemCount;
  const { theme, toggleTheme } = useThemeStore();
  const openCart = useCartDrawerStore((s) => s.open);
  const { isLoggedIn, customer, logout } = useAuthStore();
  const { data: categories } = useCategories();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [shopOpen, setShopOpen] = useState(false);
  const [infoOpen, setInfoOpen] = useState(false);
  const [userOpen, setUserOpen] = useState(false);
  const [mobileInfoOpen, setMobileInfoOpen] = useState(false);
  const [mobileShopOpen, setMobileShopOpen] = useState(false);
  const shopRef = useRef<HTMLDivElement>(null);
  const infoRef = useRef<HTMLDivElement>(null);
  const userRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (shopRef.current && !shopRef.current.contains(e.target as Node)) setShopOpen(false);
      if (infoRef.current && !infoRef.current.contains(e.target as Node)) setInfoOpen(false);
      if (userRef.current && !userRef.current.contains(e.target as Node)) setUserOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  useEffect(() => {
    if (!mobileOpen) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setMobileOpen(false);
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      document.removeEventListener("keydown", onKey);
    };
  }, [mobileOpen]);

  /*
   * Cart pop. When the item count goes up, the badge punches and a gold ring
   * radiates off the cart icon once. Shoppers who just added something look for
   * "where did it go"; this points at the mini cart without a modal or a toast
   * competing for the same attention.
   */
  const [cartBumped, setCartBumped] = useState(false);
  const previousItemCount = useRef(totalItems);
  useEffect(() => {
    if (totalItems > previousItemCount.current) {
      setCartBumped(true);
      const id = window.setTimeout(() => setCartBumped(false), 700);
      previousItemCount.current = totalItems;
      return () => window.clearTimeout(id);
    }
    previousItemCount.current = totalItems;
  }, [totalItems]);

  const allCats: Category[] = categories || [];
  const topCategories = allCats.filter((c) => typeof c.parent !== "number" || c.parent === 0);
  const subCategoriesMap = new Map<number, Category[]>();
  allCats
    .filter((c) => typeof c.parent === "number" && c.parent > 0)
    .forEach((c) => {
      const parentId = c.parent as number;
      const list = subCategoriesMap.get(parentId) || [];
      list.push(c);
      subCategoriesMap.set(parentId, list);
    });

  /**
   * Announcements for the top bar. On mobile they rotate one at a time (see
   * below); from sm upwards they sit in a single row as before.
   */
  const announcements = [
    {
      key: "cutoff",
      Icon: Clock,
      hideBetweenSmAndMd: false,
      body: (
        <>
          {t("Werkdagen vóór", "Weekdays before")} <span className="text-brand-gold">12:00</span>{" "}
          {t("besteld = dezelfde dag verzonden", "ordered = shipped the same day")}
        </>
      ),
    },
    {
      key: "shipping",
      Icon: Truck,
      hideBetweenSmAndMd: false,
      body: (
        <>
          {t("Gratis verzending vanaf", "Free shipping from")}{" "}
          <span className="text-brand-gold">€150</span>
        </>
      ),
    },
    {
      key: "purity",
      Icon: ShieldCheck,
      hideBetweenSmAndMd: false,
      body: <>{t("Tot 99,9% zuiverheid", "Up to 99.9% purity")}</>,
    },
    {
      key: "payment",
      Icon: CreditCard,
      // The payment note only fits next to the others from md upwards.
      hideBetweenSmAndMd: true,
      body: (
        <>
          {t("Betaal via", "Pay via")} <span className="text-brand-gold">IDEAL / BANCONTACT</span>
        </>
      ),
    },
  ];

  const [announcementIndex, setAnnouncementIndex] = useState(0);

  useEffect(() => {
    if (typeof window === "undefined") return;
    // With reduced motion the first message simply stays put.
    if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;

    const id = window.setInterval(
      () => setAnnouncementIndex((current) => (current + 1) % announcements.length),
      4000,
    );

    return () => window.clearInterval(id);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <header className="sticky top-0 z-50">
      {/* Top announcement bar — dark with gold hairline */}
      <div className="bg-shell-elevated border-b border-brand-gold/20">
        {/* Mobile: one announcement at a time, rotating with a soft fade */}
        <div className="container grid py-2.5 text-[11px] font-medium uppercase tracking-wide text-shell-foreground/80 sm:hidden">
          {announcements.map((item, index) => (
            <div
              key={item.key}
              aria-hidden={index !== announcementIndex}
              className={`col-start-1 row-start-1 flex items-center justify-center gap-2 text-center leading-snug transition-all duration-500 ${
                index === announcementIndex
                  ? "opacity-100"
                  : "pointer-events-none -translate-y-1 opacity-0"
              }`}
            >
              <item.Icon className="w-3.5 h-3.5 shrink-0 text-brand-gold" aria-hidden="true" />
              <span>{item.body}</span>
            </div>
          ))}
        </div>

        {/* From sm upwards: the same announcements in one row */}
        <div className="container hidden items-center justify-between gap-4 overflow-x-auto py-2.5 text-[11px] font-medium uppercase tracking-wide text-shell-foreground/80 sm:flex">
          {announcements.map((item) => (
            <div
              key={item.key}
              className={`${item.hideBetweenSmAndMd ? "hidden md:flex" : "flex"} items-center gap-2 whitespace-nowrap`}
            >
              <item.Icon className="w-3.5 h-3.5 text-brand-gold" aria-hidden="true" />
              <span>{item.body}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Main navigation bar — clinical dark, gold accents */}
      <div className="bg-shell text-shell-foreground border-b border-shell-border relative">
        <div className="container flex items-center justify-between h-16 gap-6">
          <Link to="/" className="flex items-center gap-3 shrink-0 group">
            <div className="relative">
              <img
                src={logoAsset.url}
                alt="Peptidewinkel logo — research peptiden"
                width={40}
                height={40}
                loading="eager"
                decoding="async"
                fetchPriority="high"
                className="relative h-10 w-auto"
              />
            </div>
            <div className="flex flex-col leading-tight">
              <span className="font-display font-semibold text-sm sm:text-base tracking-tight text-shell-foreground whitespace-nowrap">
                <span className="text-brand-gold">Peptide</span>winkel
              </span>
              <span className="hidden sm:block text-[9px] text-shell-foreground/40 tracking-[0.2em] uppercase">
                Research Peptiden
              </span>
            </div>
          </Link>

          <div className="hidden md:flex flex-1 max-w-md relative">
            <SearchBox variant="header" />
          </div>

          <nav className="hidden lg:flex items-center gap-1">
            <Link
              to="/"
              className="px-3 py-2 text-[13px] font-medium text-shell-foreground/70 hover:text-brand-gold transition-colors"
            >
              {t("Home", "Home")}
            </Link>

            <div ref={shopRef} className="relative">
              <button
                onClick={() => setShopOpen(!shopOpen)}
                className="flex items-center gap-1 px-3 py-2 text-[13px] font-medium text-shell-foreground/70 hover:text-brand-gold transition-colors"
              >
                <ShoppingCart className="w-3.5 h-3.5" aria-hidden="true" />
                {t("Webshop", "Shop")}
                <ChevronDown
                  className={`w-3 h-3 opacity-60 transition-transform ${shopOpen ? "rotate-180" : ""}`}
                />
              </button>
              {shopOpen && (
                <div className="absolute top-full left-0 mt-2 w-64 bg-shell-elevated text-shell-foreground border border-shell-border rounded-lg shadow-2xl py-1 z-50 max-h-[70vh] overflow-y-auto">
                  <Link
                    to="/shop"
                    onClick={() => setShopOpen(false)}
                    className="flex items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-shell-foreground hover:bg-shell-foreground/5 transition-colors border-b border-shell-border"
                  >
                    <Store className="w-4 h-4 text-brand-gold" />
                    {t("Alle peptides", "All peptides")}
                  </Link>
                  {topCategories.map((cat) => {
                    const Icon = getCategoryIcon(cat.slug);
                    const subs = subCategoriesMap.get(cat.id) || [];
                    return (
                      <div key={cat.id}>
                        <Link
                          to="/product-category/$slug"
                          params={{ slug: cat.slug }}
                          onClick={() => setShopOpen(false)}
                          className="flex items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                        >
                          <Icon className="w-4 h-4 text-brand-gold" />
                          {cat.name}
                        </Link>
                        {subs.map((sub) => {
                          const SubIcon = getCategoryIcon(sub.slug);
                          return (
                            <Link
                              key={sub.id}
                              to="/product-category/$slug"
                              params={{ slug: sub.slug }}
                              onClick={() => setShopOpen(false)}
                              className="flex items-center gap-2.5 pl-10 pr-4 py-2 text-xs text-shell-foreground/60 hover:text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                            >
                              <SubIcon className="w-3.5 h-3.5" />
                              {sub.name}
                            </Link>
                          );
                        })}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            {navLinks
              .filter((l) => l.nl !== "Home")
              .map((link) => (
                <Link
                  key={link.to}
                  to={link.to}
                  className="px-3 py-2 text-[13px] font-medium text-shell-foreground/70 hover:text-brand-gold transition-colors"
                >
                  {t(link.nl, link.en)}
                </Link>
              ))}

            <Link
              to="/peptide-calculator"
              className="flex items-center gap-1.5 px-3 py-2 text-[13px] font-medium text-brand-gold/90 hover:text-brand-gold-hi transition-colors"
            >
              <Syringe className="w-3.5 h-3.5" />
              {t("Calculator", "Calculator")}
            </Link>

            <div ref={infoRef} className="relative">
              <button
                onClick={() => setInfoOpen(!infoOpen)}
                className="flex items-center gap-1 px-3 py-2 text-[13px] font-medium text-shell-foreground/70 hover:text-brand-gold transition-colors"
              >
                {t("Info", "Info")}
                <ChevronDown
                  className={`w-3 h-3 opacity-60 transition-transform ${infoOpen ? "rotate-180" : ""}`}
                />
              </button>
              {infoOpen && (
                <div className="absolute top-full right-0 mt-2 w-52 bg-shell-elevated text-shell-foreground border border-shell-border rounded-lg shadow-2xl py-1 z-50">
                  {infoLinks.map((item) => {
                    const Icon = item.icon;
                    return (
                      <Link
                        key={item.to}
                        to={item.to}
                        onClick={() => setInfoOpen(false)}
                        className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-shell-foreground/70 hover:text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                      >
                        <Icon className="w-4 h-4" />
                        {t(item.nl, item.en)}
                      </Link>
                    );
                  })}
                </div>
              )}
            </div>
          </nav>

          {/* Actions */}
          <div className="flex items-center gap-1 border-l border-shell-border pl-4">
            {/* Below lg the drawer owns both the language and the theme control: keeping
                them here as well made the row wider than a phone (measured 442px of
                content at a 390px viewport), which made the browser zoom the whole page
                out. The drawer sits below this breakpoint, so nothing is lost. */}
            <LanguageSwitch className="hidden lg:inline-flex" />
            <button
              onClick={toggleTheme}
              className="hidden h-9 w-9 items-center justify-center text-shell-foreground/60 hover:text-brand-gold transition-colors lg:inline-flex"
              aria-label="Toggle theme"
            >
              {theme === "light" ? <Moon className="w-5 h-5" /> : <Sun className="w-5 h-5" />}
            </button>
            <div ref={userRef} className="relative flex items-center">
              <button
                onClick={() => setUserOpen(!userOpen)}
                className="relative inline-flex h-9 w-9 items-center justify-center text-shell-foreground/60 hover:text-brand-gold transition-colors"
                title={isLoggedIn ? `${customer?.first_name}` : t("Account", "Account")}
                aria-label={t("Account menu", "Account menu")}
              >
                <User className="w-5 h-5" />
                {isLoggedIn && (
                  <span className="absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-brand-gold rounded-full border-2 border-shell" />
                )}
              </button>
              {userOpen && (
                <div className="absolute top-full right-0 mt-2 w-60 bg-shell-elevated text-shell-foreground border border-shell-border rounded-lg shadow-2xl py-1 z-50">
                  {isLoggedIn ? (
                    <>
                      <div className="px-4 py-3 border-b border-shell-border">
                        <div className="text-xs text-shell-foreground/50">
                          {t("Ingelogd als", "Logged in as")}
                        </div>
                        <div className="text-sm font-semibold text-shell-foreground truncate">
                          {customer?.first_name} {customer?.last_name}
                        </div>
                        <div className="text-xs text-shell-foreground/50 truncate">
                          {customer?.email}
                        </div>
                      </div>
                      <Link
                        to="/my-account"
                        onClick={() => setUserOpen(false)}
                        className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-shell-foreground/70 hover:text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                      >
                        <User className="w-4 h-4" />
                        {t("Mijn account", "My account")}
                      </Link>
                      <Link
                        to="/my-account"
                        hash="orders"
                        onClick={() => setUserOpen(false)}
                        className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-shell-foreground/70 hover:text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                      >
                        <Package className="w-4 h-4" />
                        {t("Mijn bestellingen", "My orders")}
                      </Link>
                      <Link
                        to="/my-account"
                        hash="loyalty"
                        onClick={() => setUserOpen(false)}
                        className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-shell-foreground/70 hover:text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                      >
                        <Award className="w-4 h-4" />
                        {t("Loyalty punten", "Loyalty points")}
                      </Link>
                      <Link
                        to="/my-account/affiliate"
                        onClick={() => setUserOpen(false)}
                        className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-shell-foreground/70 hover:text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                      >
                        <Link2 className="w-4 h-4" />
                        {t("Affiliate-dashboard", "Affiliate dashboard")}
                      </Link>
                      <button
                        onClick={() => {
                          logout();
                          setUserOpen(false);
                          navigate({ to: "/" });
                        }}
                        className="w-full flex items-center gap-2.5 px-4 py-2.5 text-sm text-red-400 hover:bg-shell-foreground/5 transition-colors border-t border-shell-border"
                      >
                        <LogOut className="w-4 h-4" />
                        {t("Uitloggen", "Log out")}
                      </button>
                    </>
                  ) : (
                    <>
                      <Link
                        to="/my-account"
                        onClick={() => setUserOpen(false)}
                        className="flex items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                      >
                        <LogIn className="w-4 h-4 text-brand-gold" />
                        {t("Inloggen", "Log in")}
                      </Link>
                      <Link
                        to="/my-account"
                        search={{ tab: "register" }}
                        onClick={() => setUserOpen(false)}
                        className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-shell-foreground/70 hover:text-shell-foreground hover:bg-shell-foreground/5 transition-colors"
                      >
                        <UserPlus className="w-4 h-4" />
                        {t("Registreren", "Register")}
                      </Link>
                    </>
                  )}
                </div>
              )}
            </div>
            <button
              onClick={openCart}
              aria-label={t("Winkelwagen", "Cart")}
              className={`relative inline-flex h-9 w-9 items-center justify-center text-shell-foreground/60 hover:text-brand-gold transition-colors ${cartBumped ? "pw-cart-ring" : ""}`}
            >
              <ShoppingCart className="w-5 h-5" />
              {/* A "0" badge reads as an error; it only appears once there is something in the cart. */}
              {totalItems > 0 && (
                <span
                  aria-hidden="true"
                  className={`absolute top-0 right-0 bg-brand-gold text-brand-gold-contrast text-[10px] font-bold min-w-4 h-4 px-1 rounded-full flex items-center justify-center ${cartBumped ? "pw-cart-pop" : ""}`}
                >
                  {totalItems}
                </span>
              )}
            </button>
            <button
              onClick={() => setMobileOpen(!mobileOpen)}
              className="lg:hidden inline-flex h-9 w-9 items-center justify-center text-shell-foreground/60 hover:text-brand-gold transition-colors"
              aria-label={t("Menu", "Menu")}
            >
              {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
            </button>
          </div>
        </div>

        {/* Mobile slide-in drawer */}
        <div
          className={`lg:hidden fixed inset-0 z-[60] transition-opacity duration-300 ${mobileOpen ? "opacity-100 pointer-events-auto" : "opacity-0 pointer-events-none"}`}
          aria-hidden={!mobileOpen}
        >
          {/* Backdrop */}
          <div
            onClick={() => setMobileOpen(false)}
            className="absolute inset-0 bg-black/70 backdrop-blur-sm"
          />
          {/* Drawer panel */}
          <aside
            role="dialog"
            aria-modal="true"
            aria-label={t("Hoofdmenu", "Main menu")}
            className={`absolute top-0 right-0 h-full w-[88%] max-w-sm bg-shell text-shell-foreground border-l border-brand-gold/20 shadow-2xl flex flex-col transform transition-transform duration-300 ease-out ${mobileOpen ? "translate-x-0" : "translate-x-full"}`}
          >
            {/* Drawer header */}
            <div className="flex items-center justify-between px-5 h-16 border-b border-shell-border shrink-0">
              <div className="flex items-center gap-2.5 min-w-0">
                <div className="relative shrink-0">
                  <img
                    src={logoAsset.url}
                    alt=""
                    aria-hidden="true"
                    width={32}
                    height={32}
                    loading="lazy"
                    decoding="async"
                    className="relative h-8 w-auto"
                  />
                </div>
                <div className="flex flex-col leading-tight min-w-0">
                  <span className="font-display font-semibold text-sm text-shell-foreground truncate">
                    <span className="text-brand-gold">Peptide</span>winkel
                  </span>

                  <span className="text-[9px] text-shell-foreground/40 tracking-[0.2em] uppercase">
                    {t("Menu", "Menu")}
                  </span>
                </div>
              </div>
              <button
                onClick={() => setMobileOpen(false)}
                className="text-shell-foreground/60 hover:text-brand-gold transition-colors p-2 -mr-2"
                aria-label={t("Sluit menu", "Close menu")}
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Drawer body */}
            <div className="flex-1 overflow-y-auto overscroll-contain">
              {/* Search */}
              <div className="p-5 border-b border-shell-border">
                <SearchBox variant="drawer" onNavigate={() => setMobileOpen(false)} />
              </div>

              {/* Primary links */}
              <nav className="px-3 py-3 border-b border-shell-border">
                {navLinks.map((link) => (
                  <Link
                    key={link.nl}
                    to={link.to}
                    onClick={() => setMobileOpen(false)}
                    className="block px-3 py-3 text-sm font-medium text-shell-foreground/85 hover:text-brand-gold hover:bg-shell-foreground/5 rounded-md transition-colors"
                  >
                    {t(link.nl, link.en)}
                  </Link>
                ))}
                <Link
                  to="/peptide-calculator"
                  onClick={() => setMobileOpen(false)}
                  className="flex items-center gap-2 px-3 py-3 text-sm font-medium text-brand-gold hover:bg-shell-foreground/5 rounded-md transition-colors"
                >
                  <Syringe className="w-4 h-4" />
                  {t("Peptide Calculator", "Peptide Calculator")}
                </Link>
              </nav>

              {/* Accordion: Peptides */}
              <div className="border-b border-shell-border">
                <button
                  onClick={() => setMobileShopOpen(!mobileShopOpen)}
                  aria-expanded={mobileShopOpen}
                  className="w-full flex items-center justify-between px-5 py-4 text-[11px] font-bold uppercase tracking-[0.18em] text-shell-foreground/60 hover:text-brand-gold transition-colors"
                >
                  <span className="flex items-center gap-2">
                    <span className="h-px w-6 bg-brand-gold/60" aria-hidden="true" />
                    <ShoppingCart className="w-3.5 h-3.5" aria-hidden="true" />
                    {t("Webshop", "Shop")}
                  </span>
                  <ChevronDown
                    className={`w-4 h-4 transition-transform ${mobileShopOpen ? "rotate-180 text-brand-gold" : ""}`}
                  />
                </button>
                <div
                  className={`grid transition-all duration-300 ease-out ${mobileShopOpen ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"}`}
                >
                  <div className="overflow-hidden">
                    <div className="pb-3 px-3 space-y-0.5">
                      <Link
                        to="/shop"
                        onClick={() => setMobileOpen(false)}
                        className="flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <Store className="w-4 h-4 text-brand-gold" />
                        {t("Alle peptides", "All peptides")}
                      </Link>
                      {topCategories.map((cat) => {
                        const Icon = getCategoryIcon(cat.slug);
                        return (
                          <Link
                            key={cat.id}
                            to="/product-category/$slug"
                            params={{ slug: cat.slug }}
                            onClick={() => setMobileOpen(false)}
                            className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-shell-foreground/75 hover:text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                          >
                            <Icon className="w-4 h-4 text-brand-gold/80" />
                            {cat.name}
                          </Link>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>

              {/* Accordion: Info */}
              <div className="border-b border-shell-border">
                <button
                  onClick={() => setMobileInfoOpen(!mobileInfoOpen)}
                  aria-expanded={mobileInfoOpen}
                  className="w-full flex items-center justify-between px-5 py-4 text-[11px] font-bold uppercase tracking-[0.18em] text-shell-foreground/60 hover:text-brand-gold transition-colors"
                >
                  <span className="flex items-center gap-2">
                    <span className="h-px w-6 bg-brand-gold/60" aria-hidden="true" />
                    {t("Info", "Info")}
                  </span>
                  <ChevronDown
                    className={`w-4 h-4 transition-transform ${mobileInfoOpen ? "rotate-180 text-brand-gold" : ""}`}
                  />
                </button>
                <div
                  className={`grid transition-all duration-300 ease-out ${mobileInfoOpen ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"}`}
                >
                  <div className="overflow-hidden">
                    <div className="pb-3 px-3 space-y-0.5">
                      {infoLinks.map((item) => {
                        const Icon = item.icon;
                        return (
                          <Link
                            key={item.to}
                            to={item.to}
                            onClick={() => setMobileOpen(false)}
                            className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-shell-foreground/75 hover:text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                          >
                            <Icon className="w-4 h-4 text-brand-gold/80" />
                            {t(item.nl, item.en)}
                          </Link>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>

              {/* Accordion: Account */}
              <div className="border-b border-shell-border">
                <div className="px-5 py-4 text-[11px] font-bold uppercase tracking-[0.18em] text-shell-foreground/60 flex items-center gap-2">
                  <span className="h-px w-6 bg-brand-gold/60" aria-hidden="true" />
                  {t("Account", "Account")}
                </div>
                <div className="pb-3 px-3 space-y-0.5">
                  {isLoggedIn ? (
                    <>
                      <div className="px-3 py-2 mb-1 rounded-md bg-shell-foreground/5">
                        <div className="text-[10px] uppercase tracking-wider text-shell-foreground/40">
                          {t("Ingelogd als", "Logged in as")}
                        </div>
                        <div className="text-sm font-semibold text-shell-foreground truncate">
                          {customer?.first_name} {customer?.last_name}
                        </div>
                        <div className="text-xs text-shell-foreground/50 truncate">
                          {customer?.email}
                        </div>
                      </div>
                      <Link
                        to="/my-account"
                        onClick={() => setMobileOpen(false)}
                        className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-shell-foreground/75 hover:text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <User className="w-4 h-4 text-brand-gold/80" />
                        {t("Mijn account", "My account")}
                      </Link>
                      <Link
                        to="/my-account"
                        hash="orders"
                        onClick={() => setMobileOpen(false)}
                        className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-shell-foreground/75 hover:text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <Package className="w-4 h-4 text-brand-gold/80" />
                        {t("Mijn bestellingen", "My orders")}
                      </Link>
                      <Link
                        to="/my-account"
                        hash="loyalty"
                        onClick={() => setMobileOpen(false)}
                        className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-shell-foreground/75 hover:text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <Award className="w-4 h-4 text-brand-gold/80" />
                        {t("Loyalty punten", "Loyalty points")}
                      </Link>
                      <Link
                        to="/my-account/affiliate"
                        onClick={() => setMobileOpen(false)}
                        className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-shell-foreground/75 hover:text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <Link2 className="w-4 h-4 text-brand-gold/80" />
                        {t("Affiliate-dashboard", "Affiliate dashboard")}
                      </Link>
                      <button
                        onClick={() => {
                          logout();
                          setMobileOpen(false);
                          navigate({ to: "/" });
                        }}
                        className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm text-red-400 hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <LogOut className="w-4 h-4" />
                        {t("Uitloggen", "Log out")}
                      </button>
                    </>
                  ) : (
                    <>
                      <Link
                        to="/my-account"
                        onClick={() => setMobileOpen(false)}
                        className="flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <LogIn className="w-4 h-4 text-brand-gold" />
                        {t("Inloggen", "Log in")}
                      </Link>
                      <Link
                        to="/my-account"
                        search={{ tab: "register" }}
                        onClick={() => setMobileOpen(false)}
                        className="flex items-center gap-2.5 px-3 py-2.5 text-sm text-shell-foreground/75 hover:text-shell-foreground hover:bg-shell-foreground/5 rounded-md transition-colors"
                      >
                        <UserPlus className="w-4 h-4 text-brand-gold/80" />
                        {t("Registreren", "Register")}
                      </Link>
                    </>
                  )}
                </div>
              </div>
            </div>

            {/* Drawer footer — quick actions */}
            <div className="shrink-0 border-t border-shell-border bg-shell-elevated px-5 py-4 grid grid-cols-2 gap-3">
              <button
                onClick={() => {
                  setMobileOpen(false);
                  openCart();
                }}
                className="flex items-center justify-center gap-2 py-2.5 rounded-full bg-gradient-to-r from-brand-gold-lo to-brand-gold text-brand-gold-contrast text-xs font-bold uppercase tracking-wider hover:brightness-110 transition-all"
              >
                <ShoppingCart className="w-4 h-4" />
                {t("Winkelmand", "Cart")} ({totalItems})
              </button>
              <button
                onClick={toggleTheme}
                className="flex items-center justify-center gap-2 py-2.5 rounded-full border border-shell-border text-shell-foreground/80 text-xs font-medium uppercase tracking-wider hover:border-brand-gold/50 hover:text-brand-gold transition-all"
              >
                {theme === "light" ? <Moon className="w-4 h-4" /> : <Sun className="w-4 h-4" />}
                {theme === "light" ? t("Donker", "Dark") : t("Licht", "Light")}
              </button>
              {/* Inline: a portalled dropdown would open behind this drawer's overlay. */}
              <div className="col-span-2">
                <LanguageSwitch inline className="w-full" onSwitch={() => setMobileOpen(false)} />
              </div>
            </div>
          </aside>
        </div>
      </div>
    </header>
  );
};

export default Header;
