"use client";

import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";

type Item = { label: string; href: string; children: { label: string; href: string }[] };
type Suggestion = { name: string; slug: string; image: string | null; price: string; category: string };

export default function HeaderClient({ brand, wordmark, menu, cartCount, signedIn }: { brand: string; wordmark: string; menu: Item[]; cartCount: number; signedIn: boolean }) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState(false);
  const pathname = usePathname();
  useEffect(() => { setOpen(false); setSearch(false); }, [pathname]);
  useEffect(() => {
    document.body.style.overflow = open || search ? "hidden" : "";
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { setOpen(false); setSearch(false); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, search]);

  return (
    <header className="sticky top-0 z-40 bg-paper/95 backdrop-blur-sm border-b border-sand/60">
      <div className="wrap grid grid-cols-[1fr_auto_1fr] items-center h-[var(--header-h)]">
        <nav aria-label="Main" className="hidden xl:flex gap-6 whitespace-nowrap">
          {menu.map((m) => (
            <div key={m.href} className="relative group">
              <Link href={m.href} className={`nav-type hover:text-gilt transition-colors py-5 inline-block ${pathname === m.href ? "text-gilt" : ""}`}>{m.label}</Link>
              {m.children.length > 0 && (
                <div className="absolute left-0 top-full hidden group-hover:block group-focus-within:block bg-paper border border-sand min-w-[200px] py-2 z-50">
                  {m.children.map((c) => <Link key={c.href} href={c.href} className="block px-4 py-2 text-[14px] hover:text-gilt">{c.label}</Link>)}
                </div>)}
            </div>
          ))}
        </nav>
        <button className="xl:hidden nav-type justify-self-start py-3 pr-3" aria-expanded={open} aria-controls="mobile-menu" onClick={() => setOpen(true)}>Menu</button>
        <Link href="/" aria-label={`${brand} home`} className="block">
          <Image src={wordmark} alt={brand} width={1000} height={216} priority className="h-[18px] sm:h-[22px] md:h-[26px] w-auto" />
        </Link>
        <div className="flex justify-end items-center gap-4 md:gap-7 whitespace-nowrap">
          <button className="nav-type hover:text-gilt" onClick={() => setSearch(true)} aria-haspopup="dialog" aria-label="Search"><span className="hidden sm:inline">Search</span><svg className="sm:hidden" width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg></button>
          <Link href={signedIn ? "/account" : "/account/login"} className="nav-type hover:text-gilt hidden md:inline">Account</Link>
          <Link href="/wishlist" className="nav-type hover:text-gilt hidden md:inline">Saved</Link>
          <Link href="/cart" className="nav-type hover:text-gilt" aria-label={`Bag, ${cartCount} item${cartCount === 1 ? "" : "s"}`}>Bag{cartCount ? ` (${cartCount})` : ""}</Link>
        </div>
      </div>

      {open && (
        <div id="mobile-menu" role="dialog" aria-modal="true" aria-label="Menu" className="fixed inset-0 z-50 bg-paper flex flex-col">
          <div className="wrap flex justify-between items-center h-[var(--header-h)] border-b border-sand/60">
            <span className="nav-type">Menu</span>
            <button className="nav-type py-3 pl-3" onClick={() => setOpen(false)}>Close</button>
          </div>
          <nav aria-label="Mobile" className="wrap flex-1 overflow-y-auto py-8 flex flex-col gap-1">
            {menu.map((m) => (
              <div key={m.href}>
                <Link href={m.href} className="font-display text-[40px] leading-[1.15] py-1 block">{m.label}</Link>
                {m.children.map((c) => <Link key={c.href} href={c.href} className="block pl-5 py-1 text-[16px] text-stone">{c.label}</Link>)}
              </div>
            ))}
            <div className="mt-10 flex flex-col gap-4">
              <Link href={signedIn ? "/account" : "/account/login"} className="nav-type">Account</Link>
              <Link href="/wishlist" className="nav-type">Saved items</Link>
              <Link href="/track" className="nav-type">Track an order</Link>
              <Link href="/contact" className="nav-type">Contact</Link>
            </div>
          </nav>
        </div>
      )}
      {search && <SearchOverlay onClose={() => setSearch(false)} />}
    </header>
  );
}

function SearchOverlay({ onClose }: { onClose: () => void }) {
  const [q, setQ] = useState("");
  const [items, setItems] = useState<Suggestion[]>([]);
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const input = useRef<HTMLInputElement>(null);
  useEffect(() => { input.current?.focus(); }, []);
  useEffect(() => {
    if (q.trim().length < 2) { setItems([]); return; }
    const ctrl = new AbortController();
    setLoading(true);
    const t = setTimeout(() => {
      fetch(`/api/search?q=${encodeURIComponent(q.trim())}`, { signal: ctrl.signal })
        .then((r) => r.json()).then((d) => setItems(d.items ?? [])).catch(() => {}).finally(() => setLoading(false));
    }, 180);
    return () => { clearTimeout(t); ctrl.abort(); };
  }, [q]);
  return (
    <div role="dialog" aria-modal="true" aria-label="Search" className="fixed inset-0 z-50 bg-paper/98 overflow-y-auto">
      <div className="wrap pt-6 pb-16">
        <div className="flex justify-end"><button className="nav-type py-3" onClick={onClose}>Close</button></div>
        <form role="search" onSubmit={(e) => { e.preventDefault(); if (q.trim()) router.push(`/search?q=${encodeURIComponent(q.trim())}`); }} className="mt-8 max-w-3xl">
          <label htmlFor="site-search" className="sr-only">Search products</label>
          <input id="site-search" ref={input} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search bags, dresses, earrings…" autoComplete="off"
            className="w-full bg-transparent border-b border-ink font-display text-[34px] md:text-[48px] py-3 focus:outline-none placeholder:text-stone/50" />
        </form>
        <div className="mt-8 max-w-3xl" aria-live="polite">
          {loading && <p className="text-stone text-sm">Searching…</p>}
          {!loading && q.trim().length >= 2 && !items.length && <p className="text-stone">Nothing matches “{q}”. Try a category such as bags or dresses.</p>}
          <ul className="divide-y divide-sand">
            {items.map((s) => (
              <li key={s.slug}>
                <Link href={`/products/${s.slug}`} className="flex items-center gap-4 py-3 hover:text-gilt">
                  {s.image && <Image src={s.image} alt="" width={56} height={67} className="w-14 h-[67px] object-cover bg-linen" />}
                  <span className="flex-1"><span className="block">{s.name}</span><span className="text-stone text-sm">{s.category}</span></span>
                  <span className="text-sm">{s.price}</span>
                </Link>
              </li>
            ))}
          </ul>
          {items.length > 0 && <Link href={`/search?q=${encodeURIComponent(q.trim())}`} className="link-line mt-6 inline-block">See all results</Link>}
        </div>
      </div>
    </div>
  );
}
