"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useCartStore } from "@/lib/cart-store";
import { useWishlistStore } from "@/lib/wishlist-store";
import { useAuthStore } from "@/lib/auth-store";
import { fetchWithAuth } from "@/lib/api-client";
import { useLanguage } from "@/lib/language-context";
import { useIsClient } from "@/lib/use-is-client";
import LanguageSwitcher from "./LanguageSwitcher";
import type { TemplateConfig } from "@/lib/template";

interface NavLink {
  href: string;
  label: string;
  label_ar?: string;
}

interface NavbarProps {
  storeName: string;
  logoUrl?: string | null;
  logoWidth?: number;
  logoHeight?: number;
  template?: TemplateConfig;
  /** Extra links (e.g. static pages, collections) when enabled in theme */
  extraNavLinks?: NavLink[];
}

export default function Navbar({
  storeName,
  logoUrl,
  logoWidth = 140,
  logoHeight = 44,
  template,
  extraNavLinks = [],
}: NavbarProps) {
  const isClient = useIsClient();
  const itemCount = useCartStore((s) => s.itemCount());
  const wishlistCount = useWishlistStore((s) => s.items.length);
  const isLoggedIn = useAuthStore((s) => s.isLoggedIn());
  const logout = useAuthStore((s) => s.logout);
  const { t, locale } = useLanguage();
  const router = useRouter();

  // Use "empty" state until client has mounted so server and first client render match (avoids React #418 hydration mismatch with persisted stores)
  const effectiveItemCount = isClient ? itemCount : 0;
  const effectiveWishlistCount = isClient ? wishlistCount : 0;
  const effectiveIsLoggedIn = isClient && isLoggedIn;

  const handleLogout = async () => {
    try {
      // Attempt to logout on server (will return null if 401, which is fine)
      await fetchWithAuth("/api/storefront-proxy/auth/logout", {
        method: "POST",
      });
    } catch {
      /* ignore network errors */
    }
    // Always clear local state regardless of server response
    logout();
    router.push("/");
    router.refresh();
  };
  const navStyle = template?.navStyle ?? "default";
  const [mobileOpen, setMobileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const searchInputRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    if (searchOpen) searchInputRef.current?.focus();
  }, [searchOpen]);

  // Lock body scroll when mobile menu is open
  useEffect(() => {
    if (mobileOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [mobileOpen]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const q = searchQuery.trim();
    if (!q) return;
    router.push(`/search?q=${encodeURIComponent(q)}`);
    setSearchQuery("");
    setSearchOpen(false);
    setMobileOpen(false);
  };

  // Localize extra nav links dynamically based on current locale
  const localizedExtraLinks = extraNavLinks.map((link) => ({
    href: link.href,
    label: locale === "ar" && link.label_ar ? link.label_ar : link.label,
  }));

  const links: NavLink[] = [
    { href: "/products", label: t.nav.products },
    { href: "/categories", label: t.nav.categories },
    ...localizedExtraLinks,
  ];

  const SearchButton = ({ className = "" }: { className?: string }) => (
    <button
      onClick={() => setSearchOpen((v) => !v)}
      className={`w-11 h-11 flex items-center justify-center rounded-xl hover:bg-black/5 transition-colors ${className}`}
      aria-label={t.nav.search}
    >
      <svg
        className="h-[18px] w-[18px]"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
        strokeWidth={1.75}
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"
        />
      </svg>
    </button>
  );

  const WishlistIcon = ({ className = "" }: { className?: string }) => (
    <Link
      href="/wishlist"
      className={`relative w-11 h-11 flex items-center justify-center rounded-xl hover:bg-black/5 transition-colors ${className}`}
      aria-label={`${t.nav.wishlist}${
        effectiveWishlistCount > 0 ? ` (${effectiveWishlistCount})` : ""
      }`}
    >
      <svg
        className="h-[18px] w-[18px]"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
        strokeWidth={1.75}
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
        />
      </svg>
      {effectiveWishlistCount > 0 && (
        <span
          className="absolute top-1 right-1 text-white text-[9px] font-bold rounded-full h-[16px] w-[16px] flex items-center justify-center leading-none"
          style={{ backgroundColor: "var(--color-primary)" }}
        >
          {effectiveWishlistCount > 9 ? "9+" : effectiveWishlistCount}
        </span>
      )}
    </Link>
  );

  const UserDropdown = ({
    className = "",
    light = false,
  }: {
    className?: string;
    light?: boolean;
  }) => {
    const [dropdownOpen, setDropdownOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
      const handleClickOutside = (e: MouseEvent) => {
        if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
          setDropdownOpen(false);
        }
      };
      if (dropdownOpen) {
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
      }
    }, [dropdownOpen]);

    return (
      <div className={`relative ${className}`} ref={dropdownRef}>
        <button
          onClick={() => setDropdownOpen((v) => !v)}
          className={`relative w-11 h-11 flex items-center justify-center rounded-xl transition-colors ${
            light
              ? "hover:bg-white/10 text-white"
              : "hover:bg-black/5 text-gray-600"
          }`}
          aria-label={t.auth.account}
        >
          <svg
            className="h-[18px] w-[18px]"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={1.75}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
            />
          </svg>
        </button>

        {dropdownOpen && (
          <div
            className={`absolute ${locale === "ar" ? "left-0" : "right-0"} mt-2 w-48 rounded-xl shadow-lg border overflow-hidden ${
              light
                ? "bg-black/90 backdrop-blur-lg border-white/10"
                : "bg-white border-gray-200"
            }`}
          >
            {effectiveIsLoggedIn ? (
              <>
                <Link
                  href="/account"
                  onClick={() => setDropdownOpen(false)}
                  className={`flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors ${
                    light
                      ? "text-white/85 hover:text-white hover:bg-white/10"
                      : "text-gray-700 hover:text-gray-900 hover:bg-gray-50"
                  }`}
                >
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={1.75}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                    />
                  </svg>
                  {t.auth.account}
                </Link>
                <button
                  type="button"
                  onClick={() => {
                    setDropdownOpen(false);
                    handleLogout();
                  }}
                  className={`w-full flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors text-left ${
                    light
                      ? "text-white/85 hover:text-white hover:bg-white/10"
                      : "text-gray-700 hover:text-gray-900 hover:bg-gray-50"
                  }`}
                >
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={1.75}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
                    />
                  </svg>
                  {t.auth.logout}
                </button>
              </>
            ) : (
              <>
                <Link
                  href="/login"
                  onClick={() => setDropdownOpen(false)}
                  className={`flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors ${
                    light
                      ? "text-white/85 hover:text-white hover:bg-white/10"
                      : "text-gray-700 hover:text-gray-900 hover:bg-gray-50"
                  }`}
                >
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={1.75}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"
                    />
                  </svg>
                  {t.auth.login}
                </Link>
                <Link
                  href="/signup"
                  onClick={() => setDropdownOpen(false)}
                  className={`flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors ${
                    light
                      ? "text-white/85 hover:text-white hover:bg-white/10"
                      : "text-gray-700 hover:text-gray-900 hover:bg-gray-50"
                  }`}
                >
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={1.75}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"
                    />
                  </svg>
                  {t.auth.signup}
                </Link>
              </>
            )}
          </div>
        )}
      </div>
    );
  };

  const CartIcon = ({ className = "" }: { className?: string }) => (
    <Link
      href="/cart"
      className={`relative w-11 h-11 flex items-center justify-center rounded-xl hover:bg-black/5 transition-colors ${className}`}
      aria-label={`${t.nav.cart}${
        effectiveItemCount > 0 ? ` (${effectiveItemCount})` : ""
      }`}
    >
      <svg
        className="h-[18px] w-[18px]"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
        strokeWidth={1.75}
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
        />
      </svg>
      {effectiveItemCount > 0 && (
        <span
          className="absolute top-1 right-1 text-white text-[9px] font-bold rounded-full h-[16px] w-[16px] flex items-center justify-center leading-none"
          style={{ backgroundColor: "var(--color-primary)" }}
        >
          {effectiveItemCount > 9 ? "9+" : effectiveItemCount}
        </span>
      )}
    </Link>
  );

  const HamburgerButton = ({ className }: { className?: string }) => (
    <button
      onClick={() => setMobileOpen((v) => !v)}
      className={`md:hidden w-11 h-11 flex items-center justify-center rounded-xl hover:bg-black/5 transition-colors ${
        className ?? ""
      }`}
      aria-label={t.nav.toggleMenu}
      aria-expanded={mobileOpen}
    >
      <span className="flex flex-col gap-[5px] w-5">
        <span
          className={`block h-[1.5px] bg-current rounded-full transition-all duration-200 ${
            mobileOpen ? "rotate-45 translate-y-[6.5px]" : ""
          }`}
        />
        <span
          className={`block h-[1.5px] bg-current rounded-full transition-all duration-200 ${
            mobileOpen ? "opacity-0 scale-x-0" : ""
          }`}
        />
        <span
          className={`block h-[1.5px] bg-current rounded-full transition-all duration-200 ${
            mobileOpen ? "-rotate-45 -translate-y-[6.5px]" : ""
          }`}
        />
      </span>
    </button>
  );

  const SearchBar = ({ dark = false }: { dark?: boolean }) => (
    <div
      className={`border-t ${
        dark
          ? "border-white/10 bg-black/80 backdrop-blur-nav"
          : "border-gray-100 bg-white/95 backdrop-blur-nav"
      }`}
    >
      <form
        onSubmit={handleSearch}
        className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3"
      >
        <div className="relative">
          <input
            ref={searchInputRef}
            type="search"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder={t.nav.search}
            className={`w-full pl-10 pr-4 py-2.5 text-sm rounded-xl border focus:outline-none transition-all ${
              dark
                ? "bg-white/10 border-white/20 text-white placeholder-white/50 focus:border-white/40 focus:bg-white/15"
                : "bg-gray-50 border-gray-200 text-gray-900 placeholder-gray-400 focus:border-gray-300 focus:bg-white"
            }`}
          />
          <svg
            className={`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 ${
              dark ? "text-white/50" : "text-gray-400"
            }`}
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"
            />
          </svg>
        </div>
      </form>
    </div>
  );

  const LogoContent = ({ light = false }: { light?: boolean }) =>
    logoUrl ? (
      <Image
        src={logoUrl}
        alt={storeName}
        width={logoWidth}
        height={logoHeight}
        className="object-contain"
        style={{ maxHeight: logoHeight, width: "auto" }}
      />
    ) : (
      <span
        className={`text-xl font-bold tracking-tight ${
          light ? "text-white" : ""
        }`}
        style={!light ? { color: "var(--color-secondary)" } : {}}
      >
        {storeName}
      </span>
    );

  // ── Transparent (Fashion) ─────────────────────────────────────────────────
  if (navStyle === "transparent") {
    const isOpaque = scrolled || mobileOpen || searchOpen;
    return (
      <>
        <header
          className={`sticky top-0 z-40 transition-all duration-300 ${
            isOpaque
              ? "bg-black/85 backdrop-blur-nav shadow-lg"
              : "bg-transparent"
          }`}
        >
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16">
              <Link href="/" className="flex-shrink-0">
                <LogoContent light />
              </Link>
              <nav className="hidden md:flex items-center gap-8 text-sm font-medium text-white/85">
                {links.map((l) => (
                  <Link
                    key={l.href}
                    href={l.href}
                    className="hover:text-white transition-colors relative after:absolute after:bottom-0 after:left-0 after:w-0 after:h-px after:bg-white after:transition-all hover:after:w-full"
                  >
                    {l.label}
                  </Link>
                ))}
              </nav>
              <div className="flex items-center gap-0.5 text-white">
                <LanguageSwitcher dark />
                <SearchButton />
                <UserDropdown light className="hidden md:flex" />
                <WishlistIcon />
                <CartIcon />
                <HamburgerButton />
              </div>
            </div>
          </div>
          {searchOpen && <SearchBar dark />}
        </header>
        <MobileMenu
          open={mobileOpen}
          links={links}
          onClose={() => setMobileOpen(false)}
          dark
          onSearch={handleSearch}
          searchQuery={searchQuery}
          setSearchQuery={setSearchQuery}
          searchPlaceholder={t.nav.search}
          wishlistLabel={t.nav.wishlist}
          isLoggedIn={effectiveIsLoggedIn}
          onLogout={handleLogout}
          accountLabel={t.auth.account}
          logoutLabel={t.auth.logout}
        />
      </>
    );
  }

  // ── Dark (Boutique) ───────────────────────────────────────────────────────
  if (navStyle === "dark") {
    return (
      <>
        <header
          className="sticky top-0 z-40 shadow-sm"
          style={{ backgroundColor: "var(--color-secondary)" }}
        >
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16">
              <Link href="/" className="flex-shrink-0">
                {logoUrl ? (
                  <Image
                    src={logoUrl}
                    alt={storeName}
                    width={logoWidth}
                    height={logoHeight}
                    className="object-contain"
                    style={{ maxHeight: logoHeight, width: "auto" }}
                  />
                ) : (
                  <span className="text-white font-serif text-xl tracking-wide">
                    {storeName}
                  </span>
                )}
              </Link>
              <nav className="hidden md:flex items-center gap-8 text-[11px] font-semibold uppercase tracking-[0.18em] text-white/70">
                {links.map((l) => (
                  <Link
                    key={l.href}
                    href={l.href}
                    className="hover:text-white transition-colors"
                  >
                    {l.label}
                  </Link>
                ))}
              </nav>
              <div className="flex items-center gap-0.5 text-white">
                <LanguageSwitcher dark />
                <SearchButton />
                <UserDropdown light className="hidden md:flex" />
                <WishlistIcon />
                <CartIcon />
                <HamburgerButton />
              </div>
            </div>
          </div>
          {searchOpen && <SearchBar dark />}
        </header>
        <MobileMenu
          open={mobileOpen}
          links={links}
          onClose={() => setMobileOpen(false)}
          dark
          onSearch={handleSearch}
          searchQuery={searchQuery}
          setSearchQuery={setSearchQuery}
          searchPlaceholder={t.nav.search}
          wishlistLabel={t.nav.wishlist}
          isLoggedIn={effectiveIsLoggedIn}
          onLogout={handleLogout}
          accountLabel={t.auth.account}
          logoutLabel={t.auth.logout}
        />
      </>
    );
  }

  // ── Minimal (Modern Minimal) ──────────────────────────────────────────────
  if (navStyle === "minimal") {
    return (
      <>
        <header
          className={`bg-white sticky top-0 z-40 transition-all duration-200 ${
            scrolled
              ? "border-b border-gray-200 shadow-sm"
              : "border-b border-gray-100"
          }`}
        >
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-14">
              <Link href="/" className="flex-shrink-0">
                {logoUrl ? (
                  <Image
                    src={logoUrl}
                    alt={storeName}
                    width={logoWidth}
                    height={logoHeight}
                    className="object-contain"
                    style={{ maxHeight: logoHeight, width: "auto" }}
                  />
                ) : (
                  <span className="font-black text-gray-900 text-lg tracking-tight">
                    {storeName}
                  </span>
                )}
              </Link>
              <nav className="hidden md:flex items-center gap-8 text-[11px] font-bold uppercase tracking-[0.22em] text-gray-400">
                {links.map((l) => (
                  <Link
                    key={l.href}
                    href={l.href}
                    className="hover:text-gray-900 transition-colors"
                  >
                    {l.label}
                  </Link>
                ))}
              </nav>
              <div className="flex items-center gap-0.5 text-gray-700">
                <LanguageSwitcher />
                <SearchButton />
                <UserDropdown className="hidden md:flex" />
                <WishlistIcon />
                <CartIcon />
                <HamburgerButton />
              </div>
            </div>
          </div>
          {searchOpen && <SearchBar />}
        </header>
        <MobileMenu
          open={mobileOpen}
          links={links}
          onClose={() => setMobileOpen(false)}
          onSearch={handleSearch}
          searchQuery={searchQuery}
          setSearchQuery={setSearchQuery}
          searchPlaceholder={t.nav.search}
          wishlistLabel={t.nav.wishlist}
          isLoggedIn={effectiveIsLoggedIn}
          onLogout={handleLogout}
          accountLabel={t.auth.account}
          logoutLabel={t.auth.logout}
        />
      </>
    );
  }

  // ── Default / Marketplace ─────────────────────────────────────────────────
  return (
    <>
      <header
        className={`bg-white/95 backdrop-blur-nav sticky top-0 z-40 transition-all duration-200 ${
          scrolled
            ? "border-b border-gray-200 shadow-sm"
            : "border-b border-gray-100"
        }`}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <Link href="/" className="flex items-center gap-2 flex-shrink-0">
              <LogoContent />
            </Link>

            {/* Desktop nav + inline search */}
            <div className="hidden md:flex items-center gap-6 flex-1 mx-8">
              <nav className="flex items-center gap-6 text-sm font-medium text-gray-600">
                {links.map((l) => (
                  <Link
                    key={l.href}
                    href={l.href}
                    className="hover:text-gray-900 transition-colors relative after:absolute after:bottom-[-2px] after:left-0 after:w-0 after:h-[1.5px] after:bg-current after:transition-all hover:after:w-full"
                  >
                    {l.label}
                  </Link>
                ))}
              </nav>
              <form
                onSubmit={handleSearch}
                className="flex-1 max-w-xs relative"
              >
                <input
                  type="search"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder={t.nav.search}
                  className="w-full pl-9 pr-3 py-2 rounded-xl text-sm border border-gray-200 bg-gray-50 focus:outline-none focus:border-gray-300 focus:bg-white transition-all"
                />
                <svg
                  className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"
                  />
                </svg>
              </form>
            </div>

            <div className="flex items-center gap-0.5 text-gray-600">
              <LanguageSwitcher />
              <SearchButton className="md:hidden" />
              <UserDropdown className="hidden md:flex" />
              <WishlistIcon />
              <CartIcon />
              <HamburgerButton />
            </div>
          </div>
        </div>

        {searchOpen && <SearchBar />}
      </header>
      <MobileMenu
        open={mobileOpen}
        links={links}
        onClose={() => setMobileOpen(false)}
        onSearch={handleSearch}
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
        searchPlaceholder={t.nav.search}
        wishlistLabel={t.nav.wishlist}
        isLoggedIn={effectiveIsLoggedIn}
        onLogout={handleLogout}
        accountLabel={t.auth.account}
        logoutLabel={t.auth.logout}
      />
    </>
  );
}

// ── Shared mobile menu ────────────────────────────────────────────────────────
function MobileMenu({
  open,
  links,
  onClose,
  dark = false,
  onSearch,
  searchQuery,
  setSearchQuery,
  searchPlaceholder,
  wishlistLabel,
  isLoggedIn = false,
  onLogout,
  accountLabel = "Account",
  logoutLabel = "Log out",
}: {
  open: boolean;
  links: { href: string; label: string }[];
  onClose: () => void;
  dark?: boolean;
  onSearch: (e: React.FormEvent) => void;
  searchQuery: string;
  setSearchQuery: (v: string) => void;
  searchPlaceholder?: string;
  wishlistLabel?: string;
  isLoggedIn?: boolean;
  onLogout?: () => void;
  accountLabel?: string;
  logoutLabel?: string;
}) {
  if (!open) return null;

  const linkClass = dark
    ? "text-white/80 hover:text-white hover:bg-white/8"
    : "text-gray-700 hover:text-gray-900 hover:bg-gray-50";

  return (
    <div
      className={`fixed inset-0 z-30 md:hidden flex flex-col ${
        dark ? "bg-black/95" : "bg-white"
      }`}
      style={{ top: dark ? "64px" : "64px" }}
    >
      {/* Mobile search */}
      <form
        onSubmit={onSearch}
        className={`px-4 pt-4 pb-3 border-b ${
          dark ? "border-white/10" : "border-gray-100"
        }`}
      >
        <div className="relative">
          <input
            type="search"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder={searchPlaceholder ?? "Search products…"}
            className={`w-full pl-10 pr-4 py-3 rounded-xl text-sm border focus:outline-none transition-all ${
              dark
                ? "bg-white/10 border-white/20 text-white placeholder-white/50 focus:border-white/40"
                : "bg-gray-50 border-gray-200 text-gray-900 placeholder-gray-400 focus:border-gray-300 focus:bg-white"
            }`}
          />
          <svg
            className={`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 ${
              dark ? "text-white/50" : "text-gray-400"
            }`}
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"
            />
          </svg>
        </div>
      </form>

      <nav className="flex-1 overflow-y-auto px-4 py-4 flex flex-col gap-1">
        {links.map((l) => (
          <Link
            key={l.href}
            href={l.href}
            onClick={onClose}
            className={`flex items-center px-4 py-3.5 rounded-xl text-base font-medium transition-colors ${linkClass}`}
          >
            {l.label}
          </Link>
        ))}
        <Link
          href="/wishlist"
          onClick={onClose}
          className={`flex items-center gap-3 px-4 py-3.5 rounded-xl text-base font-medium transition-colors ${linkClass}`}
        >
          <svg
            className="h-5 w-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={1.75}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
            />
          </svg>
          {wishlistLabel ?? "Wishlist"}
        </Link>
        {isLoggedIn && (
          <>
            <Link
              href="/account"
              onClick={onClose}
              className={`flex items-center gap-3 px-4 py-3.5 rounded-xl text-base font-medium transition-colors ${linkClass}`}
            >
              <svg
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.75}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                />
              </svg>
              {accountLabel}
            </Link>
            <button
              type="button"
              onClick={() => {
                onClose();
                onLogout?.();
              }}
              className={`flex items-center gap-3 px-4 py-3.5 rounded-xl text-base font-medium transition-colors w-full text-left ${linkClass}`}
            >
              <svg
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.75}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
                />
              </svg>
              {logoutLabel}
            </button>
          </>
        )}
      </nav>
    </div>
  );
}
