/* eslint-disable */
/* Header — refined nav with mega-menu, search bar, and AI Stylist trigger.
   Sub-tabs map to Shopify collection handles. Falls back to parent collection
   if the nested handle isn't published. */
const slug = s => s.toLowerCase().replace(/&/g, "and").replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
// Maps friendly NAV labels to actual published Shopify collection handles.
// What's not in here falls through to slug() and (if missing on the store)
// renders mock-fallback in CollectionPage.
const HANDLE_ALIAS = {
  "women":               "womens",       // routes through CollectionPage's "womens" alias to shop-all data + "Womens" title
  "womens":              "womens",
  "men":                 "mens",
  "mens":                "mens",
  "kids":                "kids-apparel",
  "apparel":             "hats",
  "bestsellers":         "shop-all",
  "the-edit":            "new-arrivals",
  // Composed aliases (per "Quick links" in the mega menu) — without these,
  // colHref("women","new") resolves to the dead handle `women-new` and the
  // PLP falls back to mock data even on a configured Shopify storefront.
  "women-new":           "new-arrivals",
  "women-bestsellers":   "shop-all",
  "women-under-75":      "shop-all",      // no price-banded collection on store; PLP filter rail will narrow further
  "men-new":             "mens",
  "men-bestsellers":     "mens",
  "men-under-100":       "mens",
  "men-silver":          "mens",
  "kids-new":            "kids-apparel",
  "kids-gift-sets":      "bundles",
  "kids-under-50":       "kids-apparel",
  "kids-mom-and-mini":   "bundles",
  "gift-sets":           "bundles",
};
const resolveHandle = h => HANDLE_ALIAS[h] || h;
const colHref = (...parts) => {
  const raw = parts.filter(Boolean).map(slug).join("-");
  return "collection.html?handle=" + resolveHandle(raw);
};
// Smart mega-menu resolver. Real top-level Shopify collections we know exist:
const REAL_COLLECTIONS = new Set([
  "shop-all","sale","new-arrivals","bundles","necklaces","bracelets","rings",
  "earrings","mens","kids-apparel","hats","travel-case",
]);
// Sub-category chips that don't have backing collections become tag filters
// against the parent collection — preserves the navigation depth the design
// calls for without faking a catalog that doesn't exist.
const navHref = (parent, head, item) => {
  // Women → category : route directly to the flat collection (necklaces,
  // rings, etc.) since DROP's catalog isn't gender-segmented at that level.
  if (parent === "women" && head && REAL_COLLECTIONS.has(slug(head))) {
    const url = "collection.html?handle=" + slug(head);
    return item ? url + "&filter=" + encodeURIComponent(item) : url;
  }
  // Men / Kids → category : tag-filter the parent collection.
  const parentHandle = resolveHandle(slug(parent));
  if (head && item)  return "collection.html?handle=" + parentHandle + "&filter=" + encodeURIComponent(head + " " + item);
  if (head)          return "collection.html?handle=" + parentHandle + "&filter=" + encodeURIComponent(head);
  return "collection.html?handle=" + parentHandle;
};

const NAV = {
  women: {
    label: "Womens",
    href: colHref("women"),
    cols: [
      { head: "Necklaces",  items: ["Chain", "Pendant", "Cuban", "Snake", "Charm"] },
      { head: "Earrings",   items: ["Hoops", "Studs", "Huggies", "Drops"] },
      { head: "Bracelets",  items: ["Charm", "Chain", "Cuban", "Pearl", "Watch"] },
      { head: "Rings",      items: ["Band", "Stacking", "Statement"] },
    ],
    feat: [
      { img: "assets/hero-main.jpg",       title: "Spring '26",  sub: "The new edit", href: colHref("women","new") },
      { img: "assets/hero-necklaces.jpg",  title: "Bestsellers", sub: "Top 25",       href: colHref("women","bestsellers") },
    ],
    quick: [
      ["New arrivals", colHref("women","new")],
      ["Bestsellers",  colHref("women","bestsellers")],
      ["Under $75",    colHref("women","under-75")],
      ["Gift sets",    colHref("gift-sets")],
      ["Sale",         colHref("sale")],
    ],
  },
  men: {
    label: "Mens",
    href: colHref("men"),
    cols: [
      { head: "Chains",     items: ["Cuban", "Rope", "Chain"] },
      { head: "Bracelets",  items: ["Cuban", "Rope", "Chain"] },
      { head: "Rings",      items: ["Band"] },
      { head: "Apparel",    items: ["Tees", "Hoodies", "Caps"] },
    ],
    feat: [
      { img: "assets/hero-mens.jpg", title: "The silver edit", sub: "Heavy weights", href: colHref("men","silver") },
    ],
    quick: [
      ["New arrivals", colHref("men","new")],
      ["Bestsellers",  colHref("men","bestsellers")],
      ["Under $100",   colHref("men","under-100")],
      ["Sale",         colHref("sale")],
    ],
  },
  kids: {
    label: "Kids",
    href: colHref("kids"),
    cols: [
      { head: "Necklaces",  items: ["Initial", "Heart", "Star", "Birthstone"] },
      { head: "Bracelets",  items: ["Cuff", "Charm", "Friendship"] },
      { head: "Sets",       items: ["Mom + Mini", "Sibling sets", "Gift box"] },
    ],
    feat: [
      { img: "assets/banner-bundles.jpg", title: "Mom + Mini", sub: "Matching sets", href: colHref("kids","mom-and-mini") },
    ],
    quick: [
      ["New arrivals", colHref("kids","new")],
      ["Gift sets",    colHref("kids","gift-sets")],
      ["Under $50",    colHref("kids","under-50")],
    ],
  },
};

function Header({ cartCount, onCart, onSearch, onAI }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [hover, setHover] = React.useState(null);
  const [searchOpen, setSearchOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <React.Fragment>
      <div className="announce">
        <span>JOIN VIP — TEXT <strong>DROP</strong> TO 33433 FOR 20% OFF</span>
        <span className="dot">·</span>
        <span>FREE SHIPPING $75+</span>
        <span className="dot">·</span>
        <span>30-DAY RETURNS</span>
      </div>
      <header
        className={"site-nav " + (scrolled ? "scrolled" : "") + (hover ? " menu-open" : "")}
        onMouseLeave={() => setHover(null)}
      >
        <div className="nav-row">
          <nav className="nav-left">
            {Object.entries(NAV).map(([key, n]) => (
              <a key={key}
                href={n.href}
                className={"nav-tab " + (hover === key ? "active" : "")}
                onMouseEnter={() => setHover(key)}>
                {n.label}
              </a>
            ))}
            <span className="nav-div"></span>
            <a className="nav-tab" href={colHref("bundles")} onMouseEnter={() => setHover(null)}>Bundles</a>
            <a className="nav-tab" href={colHref("new-arrivals")} onMouseEnter={() => setHover(null)}>New</a>
            <a className="nav-tab sale-link" href={colHref("sale")} onMouseEnter={() => setHover(null)}>Sale</a>
          </nav>

          <a className="brand" href="index.html" onMouseEnter={() => setHover(null)}>
            <DropLogo size={scrolled ? 28 : 34} />
          </a>

          <div className="nav-right" onMouseEnter={() => setHover(null)}>
            <button className="ai-trigger" onClick={onAI}>
              <span className="ai-dot"></span>
              <span>Style with AI</span>
            </button>
            <button className="icon-btn" onClick={() => setSearchOpen(true)} aria-label="Search">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
            </button>
            <a className="icon-btn" href="account.html" aria-label="Account">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
            </a>
            <button className="icon-btn bag" onClick={onCart} aria-label="Bag">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"/><path d="M3 6h18"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>
              {cartCount > 0 && <span className="badge-count">{cartCount}</span>}
            </button>
          </div>
        </div>

        {hover && (
          <div className="mega" onMouseEnter={() => setHover(hover)}>
            <div className="mega-inner">
              <div className="mega-quick">
                <div className="mega-quick-head">Quick links</div>
                {NAV[hover].quick.map(([label, href]) =>
                  <a key={label} className="mega-quick-a" href={href}>{label}</a>
                )}
              </div>
              <div className="mega-cols">
                {NAV[hover].cols.map(col => (
                  <div key={col.head} className="mega-col">
                    <a className="mega-head" href={navHref(hover, col.head)}>{col.head}</a>
                    {col.items.map(i =>
                      <a key={i} className="mega-item" href={navHref(hover, col.head, i)}>{i}</a>
                    )}
                    <a className="mega-shop-all" href={navHref(hover, col.head)}>Shop all {col.head.toLowerCase()} →</a>
                  </div>
                ))}
              </div>
              <div className="mega-feats">
                {NAV[hover].feat.map((f, i) => (
                  <a key={i} className="mega-feat" href={f.href}>
                    <div className="mega-feat-img" style={{backgroundImage:`url(${f.img})`}}></div>
                    <div className="mega-feat-meta">
                      <div className="mega-feat-sub">{f.sub}</div>
                      <div className="mega-feat-title">{f.title} →</div>
                    </div>
                  </a>
                ))}
              </div>
            </div>
          </div>
        )}
      </header>
      {searchOpen && <SearchOverlay onClose={() => setSearchOpen(false)} />}
    </React.Fragment>
  );
}

function SearchOverlay({ onClose }) {
  const [q, setQ] = React.useState("");
  const submit = (term) => {
    if (!term) return;
    window.location.href = "search.html?q=" + encodeURIComponent(term);
  };
  const onKey = e => { if (e.key === "Enter") submit(q.trim()); if (e.key === "Escape") onClose(); };
  return (
    <div className="search-overlay" onClick={onClose}>
      <div className="search-panel" onClick={e => e.stopPropagation()}>
        <div className="search-bar">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
          <input autoFocus placeholder="Search for chains, rings, gifts…" value={q} onChange={e => setQ(e.target.value)} onKeyDown={onKey} />
          <button className="search-close" onClick={onClose}>Esc</button>
        </div>
        <div className="search-body">
          <div className="search-col">
            <div className="search-head">Popular categories</div>
            <a className="search-suggest" href={colHref("necklaces")}>Necklaces</a>
            <a className="search-suggest" href={colHref("bracelets")}>Bracelets</a>
            <a className="search-suggest" href={colHref("rings")}>Rings</a>
            <a className="search-suggest" href={colHref("earrings")}>Earrings</a>
            <a className="search-suggest" href={colHref("bundles")}>Bundles</a>
          </div>
        </div>
      </div>
    </div>
  );
}
window.Header = Header;
window.NAV = NAV;
window.colHref = colHref;
