"use client";

import Link from "next/link";
import Image from "next/image";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { usePathname, useSearchParams } from "next/navigation";
import { useCart } from "@/lib/cart-context";
import { useWishlist } from "@/lib/wishlist-context";
import CartDrawer from "@/components/CartDrawer";
import { whatsappLink } from "@/lib/site";

type NavCategory = {
  id: string;
  name: string;
  slug: string;
  productCount: number;
  children: { id: string; name: string; slug: string }[];
};

// "Budget Return Gifts" gets a fixed dropdown of site-wide price tiers instead of
// real category children — these aren't Category rows, just /shop?maxPrice=N links.
const BUDGET_PRICE_TIERS = [49, 99, 199, 499, 999];

// Small label that fades in on hover of the icon button it's dropped into — the parent needs
// `group relative` for this to anchor and reveal correctly.
function IconTooltip({ children }: { children: React.ReactNode }) {
  return (
    <span className="pointer-events-none absolute left-1/2 top-full z-50 mt-2 -translate-x-1/2 whitespace-nowrap rounded-md bg-rose-900 px-2 py-1 text-xs font-medium text-white opacity-0 transition-opacity duration-150 group-hover:opacity-100">
      {children}
    </span>
  );
}

export default function Header({ categories, isLoggedIn }: { categories: NavCategory[]; isLoggedIn: boolean }) {
  const { count } = useCart();
  const { count: wishlistCount } = useWishlist();
  const [menuOpen, setMenuOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const activeCategory = searchParams.get("category");
  const activeMaxPrice = searchParams.get("maxPrice");

  // Any navigation, from any link (category dropdown, logo, browser back/forward — not just the menu's own
  // links), should close whatever's open. Layouts persist across routes in the App Router, so this state
  // otherwise survives a page change and shows up stuck open on the next page.
  useEffect(() => {
    setMenuOpen(false);
    setSearchOpen(false);
    setOpenDropdown(null);
  }, [pathname, searchParams]);

  const navLinkClass = (active: boolean) =>
    `text-sm font-medium ${active ? "font-semibold text-rose-700" : "text-stone-600 hover:text-rose-700"}`;

  const accountHref = isLoggedIn ? "/account" : "/account/login";
  const accountLabel = isLoggedIn ? "My Account" : "Login";

  const menuLinks = [
    { href: accountHref, label: accountLabel },
    { href: "/track-order", label: "Track Order" },
    { href: "/about", label: "About" },
    { href: "/contact", label: "Contact" },
  ];

  return (
    <>
      <header className="relative z-40 border-b border-rose-100 bg-white/90 backdrop-blur print:hidden sm:sticky sm:top-0">
        <div className="mx-auto flex max-w-7xl items-center gap-3 px-4 py-3 sm:px-6">
          <Link href="/" className="flex shrink-0 items-center gap-2">
            <Image src="/brand/logo.png" alt="Iniyaval Return Gifts" width={44} height={44} priority className="h-10 w-10 sm:h-11 sm:w-11" />
            <span className="font-[family-name:var(--font-heading)] uppercase leading-tight text-rose-800">
              <span className="text-lg font-bold tracking-wide sm:text-2xl">Iniyaval</span>{" "}
              <span className="text-[10px] font-semibold tracking-widest text-stone-500 sm:text-sm">Return Gifts</span>
            </span>
          </Link>

          <form action="/search" role="search" className="relative hidden flex-1 max-w-md md:block">
            <svg xmlns="http://www.w3.org/2000/svg" className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-stone-400" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
            </svg>
            <input
              type="search"
              name="q"
              placeholder="Search products..."
              className="w-full rounded-full border border-rose-200 bg-rose-50/50 py-2 pl-10 pr-4 text-sm focus:border-rose-400 focus:bg-white focus:outline-none"
            />
          </form>

          <div className="ml-auto flex items-center gap-2 sm:gap-3">
            <a
              href={whatsappLink()}
              target="_blank"
              rel="noopener noreferrer"
              className="hidden items-center gap-1.5 rounded-full bg-emerald-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-600 lg:flex"
            >
              WhatsApp us
            </a>
            <button
              onClick={() => setSearchOpen((v) => !v)}
              className="rounded-full border border-rose-200 p-2 text-rose-800 hover:bg-rose-50 md:hidden"
              aria-label="Toggle search"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
              </svg>
            </button>
            <Link
              href="/wishlist"
              className="group relative hidden rounded-full border border-rose-200 p-2 text-rose-800 hover:bg-rose-50 sm:block"
              aria-label="Open wishlist"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" />
              </svg>
              {wishlistCount > 0 && (
                <span className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-rose-600 text-[11px] font-semibold text-white">
                  {wishlistCount}
                </span>
              )}
              <IconTooltip>Wishlist</IconTooltip>
            </Link>
            <Link
              href="/track-order"
              className="group relative hidden rounded-full border border-rose-200 p-2 text-rose-800 hover:bg-rose-50 sm:block"
              aria-label="Track order"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75M3.75 4.5h16.5v15a1.5 1.5 0 01-1.5 1.5H5.25a1.5 1.5 0 01-1.5-1.5v-15zM3.75 4.5L5.25 3h13.5l1.5 1.5" />
              </svg>
              <IconTooltip>Track your order</IconTooltip>
            </Link>
            <Link
              href={accountHref}
              className="group relative hidden rounded-full border border-rose-200 p-2 text-rose-800 hover:bg-rose-50 sm:block"
              aria-label={accountLabel}
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
              </svg>
              <IconTooltip>{accountLabel}</IconTooltip>
            </Link>
            <button
              onClick={() => setCartOpen(true)}
              className="group relative rounded-full border border-rose-200 p-2 text-rose-800 hover:bg-rose-50"
              aria-label="Open cart"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 1.976-4.694 2.512-7.152.108-.494-.272-.958-.777-.958H4.826m2.674 8.11L6.052 5.272M7.5 14.25L5.106 5.272M7.5 14.25L5.106 5.272M12 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm7.5 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
              </svg>
              {count > 0 && (
                <span className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-rose-600 text-[11px] font-semibold text-white">
                  {count}
                </span>
              )}
              <IconTooltip>Cart</IconTooltip>
            </button>
            <div className="relative">
              <button
                className="group relative rounded-md border border-rose-200 p-2 text-rose-800"
                onClick={() => setMenuOpen((v) => !v)}
                aria-label="Toggle menu"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h16.5" />
                </svg>
                <IconTooltip>Menu</IconTooltip>
              </button>

              {/* sm and up: small dropdown anchored under the button, sized to content — not the
                  mobile full-height drawer (rendered separately below, sm:hidden). */}
              {menuOpen && (
                <div className="absolute right-0 top-full z-50 mt-2 hidden w-48 flex-col gap-1 rounded-md border border-rose-100 bg-white p-2 shadow-lg sm:flex">
                  {menuLinks.map((l) => (
                    <Link
                      key={l.href}
                      href={l.href}
                      className={`rounded-md px-2 py-2 hover:bg-rose-50 ${navLinkClass(pathname === l.href)}`}
                    >
                      {l.label}
                    </Link>
                  ))}
                  <Link href="/wishlist" className={`rounded-md px-2 py-2 hover:bg-rose-50 ${navLinkClass(pathname === "/wishlist")}`}>
                    Wishlist{wishlistCount > 0 ? ` (${wishlistCount})` : ""}
                  </Link>
                  <a
                    href={whatsappLink()}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="rounded-md px-2 py-2 text-sm font-medium text-emerald-700 hover:bg-emerald-50 lg:hidden"
                  >
                    WhatsApp us
                  </a>
                </div>
              )}
            </div>
          </div>
        </div>

        {searchOpen && (
          <form action="/search" role="search" className="border-t border-rose-100 bg-white px-4 py-3 md:hidden">
            <input
              type="search"
              name="q"
              autoFocus
              placeholder="Search products..."
              className="w-full rounded-full border border-rose-200 px-4 py-2 text-sm focus:border-rose-400 focus:outline-none"
            />
          </form>
        )}

        <div className="hidden border-t border-rose-100 bg-rose-50/60 sm:block">
          <nav className="relative mx-auto flex max-w-7xl flex-wrap gap-x-5 gap-y-1.5 px-4 py-2.5 sm:px-6">
            <Link href="/shop" className={`shrink-0 ${navLinkClass(pathname === "/shop" && !activeCategory)}`}>
              All Products
            </Link>
            {categories.map((c) => {
              // Dropdown visibility is driven entirely by `openDropdown` state — no CSS :hover/group-hover.
              // Two reasons: (1) hover alone doesn't work on touch devices, where a tap on a hover-styled
              // element gets consumed as a "simulate hover" gesture instead of opening anything; (2) mixing
              // a plain "invisible/visible" utility with a "group-hover:visible" variant in the same class
              // list is a real CSS specificity/ordering conflict — whichever rule Tailwind happens to emit
              // later in the stylesheet wins regardless of actual hover state, causing inconsistent partial
              // rendering. Mouse enter/leave here just sets the same state a tap/click would.
              //
              // The dropdown PANEL itself only renders here for sm: and up, anchored to this specific
              // trigger (verified to fit at both narrow and wide desktop widths). Below sm:, nav items can
              // sit anywhere depending on how the flex-wrap row reflows, so a panel anchored to one small
              // trigger reliably overflows the viewport on one side or the other — a single shared panel
              // anchored to the whole nav bar (rendered once, after this loop) is used for mobile instead.
              const dropdownVisibility = (id: string) =>
                `transition-opacity ${openDropdown === id ? "visible opacity-100" : "invisible opacity-0"}`;
              const caretButton = (id: string, active: boolean) => (
                <button
                  type="button"
                  onClick={() => setOpenDropdown((cur) => (cur === id ? null : id))}
                  aria-label={`Toggle ${id} submenu`}
                  aria-expanded={openDropdown === id}
                  className={`px-1 text-xs ${active ? "text-rose-700" : "text-stone-500"}`}
                >
                  ▾
                </button>
              );

              if (c.slug === "budget-return-gifts") {
                const active = activeCategory === c.slug || (!activeCategory && !!activeMaxPrice) || openDropdown === c.id;
                return (
                  <div
                    key={c.id}
                    className="relative flex shrink-0 items-center"
                    onMouseEnter={() => setOpenDropdown(c.id)}
                    onMouseLeave={() => setOpenDropdown((cur) => (cur === c.id ? null : cur))}
                  >
                    <Link href={`/shop?category=${c.slug}`} className={navLinkClass(active)}>
                      {c.name}
                    </Link>
                    {caretButton(c.id, active)}
                    <div
                      className={`absolute right-0 top-full z-50 hidden grid-cols-2 gap-x-6 gap-y-0.5 rounded-md border border-rose-100 bg-white p-2 shadow-lg sm:grid sm:w-[420px] ${dropdownVisibility(c.id)}`}
                    >
                      {BUDGET_PRICE_TIERS.map((price) => (
                        <Link
                          key={price}
                          href={`/shop?maxPrice=${price}`}
                          className={`block whitespace-nowrap rounded px-3 py-2 hover:bg-rose-50 ${navLinkClass(!activeCategory && activeMaxPrice === String(price))}`}
                        >
                          Return Gifts Under ₹{price}
                        </Link>
                      ))}
                    </div>
                  </div>
                );
              }
              const childActive = c.children.some((child) => child.slug === activeCategory);
              const isOpen = openDropdown === c.id;
              return c.children.length > 0 ? (
                <div
                  key={c.id}
                  className="relative flex shrink-0 items-center"
                  onMouseEnter={() => setOpenDropdown(c.id)}
                  onMouseLeave={() => setOpenDropdown((cur) => (cur === c.id ? null : cur))}
                >
                  {c.productCount > 0 ? (
                    <Link href={`/shop?category=${c.slug}`} className={navLinkClass(activeCategory === c.slug || childActive || isOpen)}>
                      {c.name}
                    </Link>
                  ) : (
                    <span className={`cursor-default ${navLinkClass(childActive || isOpen)}`}>{c.name}</span>
                  )}
                  {caretButton(c.id, activeCategory === c.slug || childActive || isOpen)}
                  <div
                    className={`absolute left-0 top-full z-50 hidden grid-cols-2 gap-x-6 gap-y-0.5 rounded-md border border-rose-100 bg-white p-2 shadow-lg sm:grid sm:w-[420px] ${dropdownVisibility(c.id)}`}
                  >
                    {c.children.map((child) => (
                      <Link
                        key={child.id}
                        href={`/shop?category=${child.slug}`}
                        className={`block whitespace-nowrap rounded px-3 py-2 hover:bg-rose-50 ${navLinkClass(activeCategory === child.slug)}`}
                      >
                        {child.name}
                      </Link>
                    ))}
                  </div>
                </div>
              ) : (
                <Link key={c.id} href={`/shop?category=${c.slug}`} className={`shrink-0 ${navLinkClass(activeCategory === c.slug)}`}>
                  {c.name}
                </Link>
              );
            })}
          </nav>
        </div>

        {menuOpen && (
          <>
            {/* Mobile: partial-width slide-out drawer (not full-screen), portaled to <body>, matching the
                usual "hamburger drawer" pattern — a dim backdrop over the page with a narrower panel
                anchored to the left. All shopping navigation lives here instead of a wrapping row of
                dropdowns (hidden on mobile above) — sections with sub-items expand in place with a
                chevron, flat categories are plain links.
                Rendered via a portal rather than inline: <header> has `backdrop-blur` (backdrop-filter),
                and per spec any filter/backdrop-filter on an ancestor creates a new containing block for
                `position: fixed` descendants — nested here, this overlay would be constrained to header's
                own ~64px height instead of the real viewport, no matter what inset/height it's given. */}
            {createPortal(
              <div className="fixed inset-0 z-50 sm:hidden">
              <div className="absolute inset-0 bg-black/40" onClick={() => setMenuOpen(false)} />
              <aside className="absolute left-0 top-0 flex h-full w-full max-w-[280px] flex-col bg-rose-50 shadow-xl">
              <div className="flex shrink-0 items-center justify-between border-b border-rose-100 bg-white px-4 py-4">
                <h2 className="font-[family-name:var(--font-heading)] text-lg font-bold text-rose-800">Menu</h2>
                <button type="button" onClick={() => setMenuOpen(false)} aria-label="Close menu" className="p-1 text-rose-800">
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <div className="flex-1 overflow-y-auto">
              <nav className="flex flex-col gap-1 px-4 py-3">
                <Link
                  href="/shop"
                  className={`rounded-md px-2 py-2.5 text-sm font-medium hover:bg-rose-100/60 ${navLinkClass(pathname === "/shop" && !activeCategory)}`}
                >
                  All Products
                </Link>
                {categories.map((c) => {
                  const isBudget = c.slug === "budget-return-gifts";
                  const items = isBudget
                    ? BUDGET_PRICE_TIERS.map((price) => ({ key: String(price), label: `Return Gifts Under ₹${price}`, href: `/shop?maxPrice=${price}` }))
                    : c.children.map((child) => ({ key: child.id, label: child.name, href: `/shop?category=${child.slug}` }));

                  if (items.length === 0) {
                    return (
                      <Link
                        key={c.id}
                        href={`/shop?category=${c.slug}`}
                        className="rounded-md px-2 py-2.5 text-sm font-medium text-stone-600 hover:bg-rose-100/60"
                      >
                        {c.name}
                      </Link>
                    );
                  }
                  const expanded = openDropdown === c.id;
                  return (
                    <div key={c.id}>
                      <button
                        type="button"
                        onClick={() => setOpenDropdown((cur) => (cur === c.id ? null : c.id))}
                        aria-expanded={expanded}
                        className="flex w-full items-center justify-between rounded-md px-2 py-2.5 text-left text-sm font-semibold text-rose-700 hover:bg-rose-100/60"
                      >
                        {c.name}
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          className={`h-4 w-4 shrink-0 text-rose-700 transition-transform ${expanded ? "rotate-90" : ""}`}
                          fill="none"
                          viewBox="0 0 24 24"
                          strokeWidth={2}
                          stroke="currentColor"
                        >
                          <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                        </svg>
                      </button>
                      {expanded && (
                        <div className="ml-2 flex flex-col gap-1 border-l border-rose-200 pl-3">
                          {items.map((item) => (
                            <Link key={item.key} href={item.href} className="rounded-md px-2 py-2 text-sm text-stone-600 hover:bg-rose-100/60">
                              {item.label}
                            </Link>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </nav>

              <nav className="flex flex-col gap-1 border-t border-rose-100 px-4 py-3">
                {menuLinks.map((l) => (
                  <Link
                    key={l.href}
                    href={l.href}
                    className={`rounded-md px-2 py-2 hover:bg-rose-100/60 ${navLinkClass(pathname === l.href)}`}
                  >
                    {l.label}
                  </Link>
                ))}
                <Link href="/wishlist" className={`rounded-md px-2 py-2 hover:bg-rose-100/60 ${navLinkClass(pathname === "/wishlist")}`}>
                  Wishlist{wishlistCount > 0 ? ` (${wishlistCount})` : ""}
                </Link>
                <a
                  href={whatsappLink()}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="rounded-md px-2 py-2 text-sm font-medium text-emerald-700 hover:bg-emerald-100/60"
                >
                  WhatsApp us
                </a>
              </nav>
              </div>
              </aside>
            </div>,
              document.body
            )}
          </>
        )}
      </header>
      <CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} />
    </>
  );
}
