/* Down The Cove homepage — chrome: promo, header, quick-nav, tab bar, toast */
const Icon = window.DtcIcon;

function PromoBar({ promo, onClose, onShop }) {
  if (!promo) return null;
  return (
    <div className="hp-promo" role="region" aria-label="Promotion">
      <span className="hp-promo__dot" />
      <span onClick={onShop} style={{ cursor: "pointer" }}>
        <strong>Father's Day</strong> · gifts dads actually use — order by Thu 18 June
      </span>
      <button className="hp-promo__close" aria-label="Dismiss" onClick={onClose}>
        <Icon name="x" size={13} />
      </button>
    </div>
  );
}

function Header({ stuck, cartCount, wishCount, onSearch, onCart, onTab }) {
  return (
    <header className="hp-header" data-stuck={stuck}>
      <div className="hp-header__row">
        <a href="#" className="hp-logo" aria-label="Down The Cove — home"
           onClick={(e) => { e.preventDefault(); onTab("home"); }}>
          <img src="assets/logo/logo.png" alt="Down The Cove" />
        </a>
        <div className="hp-header__search" onClick={onSearch} role="button" tabIndex={0}
             onKeyDown={(e) => { if (e.key === "Enter") onSearch(); }}>
          <Icon name="search" size={17} />
          <span>Search the cove — gifts, gear, guides…</span>
          <kbd className="hp-header__kbd">/</kbd>
        </div>
        <div className="hp-header__actions">
          <button className="hp-iconbtn" aria-label="Search" onClick={onSearch}>
            <Icon name="search" size={20} />
          </button>
          <button className="hp-iconbtn" aria-label="Account" onClick={() => onTab("account")}>
            <Icon name="user" size={20} />
          </button>
          <button className="hp-iconbtn" aria-label={`Wishlist, ${wishCount} items`} onClick={() => onTab("account")}>
            <Icon name="heart" size={20} />
            {wishCount > 0 ? <span className="hp-iconbtn__badge">{wishCount}</span> : null}
          </button>
          <button className="hp-iconbtn" aria-label={`Basket, ${cartCount} items`} onClick={onCart}>
            <Icon name="shopping-bag" size={20} />
            {cartCount > 0 ? <span className="hp-iconbtn__badge">{cartCount}</span> : null}
          </button>
        </div>
      </div>
      <div className="hp-searchbar" onClick={onSearch} role="button" tabIndex={0}
           onKeyDown={(e) => { if (e.key === "Enter") onSearch(); }}>
        <Icon name="search" size={17} />
        <span>What are you after today?</span>
      </div>
    </header>
  );
}

function QuickNav({ items, active, onPick }) {
  return (
    <nav className="hp-quicknav" aria-label="Shop categories">
      <button className="hp-chip hp-chip--accent" onClick={() => onPick("Gifts")} data-active={active === "Gifts"}>
        <Icon name="gift" size={14} /> Father's Day
      </button>
      {items.map((c) => (
        <button key={c} className="hp-chip" data-active={active === c} onClick={() => onPick(c)}>{c}</button>
      ))}
      <button className="hp-chip" onClick={() => onPick("Knowledge")} data-active={active === "Knowledge"}>Guides</button>
    </nav>
  );
}

function BottomTabBar({ active, cartCount, onTab, onCart }) {
  const tabs = [
    { id: "home", label: "Home", icon: "waves" },
    { id: "shop", label: "Shop", icon: "shopping-bag" },
    { id: "guides", label: "Guides", icon: "anchor" },
    { id: "account", label: "Account", icon: "user" },
  ];
  return (
    <nav className="hp-tabbar" aria-label="Primary">
      {tabs.map((t) => (
        <button key={t.id} className="hp-tab" data-active={active === t.id} onClick={() => onTab(t.id)}>
          <span className="hp-tab__ico"><Icon name={t.icon} size={21} /></span>
          {t.label}
        </button>
      ))}
      <button className="hp-tab" onClick={onCart} aria-label={`Basket, ${cartCount} items`}>
        <span className="hp-tab__ico">
          <Icon name="shopping-cart" size={21} />
          {cartCount > 0 ? <span className="hp-tab__badge">{cartCount}</span> : null}
        </span>
        Basket
      </button>
    </nav>
  );
}

function Toast({ show, text }) {
  return (
    <div className="hp-toast" data-show={show}>
      <Icon name="check" size={16} /> {text}
    </div>
  );
}

/* ── Desktop nav row — two-pane mega-menus with hover intent ── */
const WORLD_BLURBS = {
  "Fishing Gear": "Rods, reels & tackle for UK shores",
  "Cook Shop": "Seafood tools & proper kitchen kit",
  "Food Smoking": "Ovens, wood chips & smoking kits",
  "Home Decor": "Coastal living, art & gifts",
  "Coastal": "Crabbing, safety & days by the sea",
};
const KNOWLEDGE_BLURBS = {
  Fishing: "How-tos, marks and methods for UK sea fishing.",
  Fish: "Species guides — what it is, where it lives, how to catch it.",
  Recipes: "Cook the catch — simple, honest coastal recipes.",
  Seafood: "Buying, prepping and cooking fish & shellfish.",
  Foraging: "Safe, seasonal foraging along the shoreline.",
  Smoking: "Hot & cold smoking at home, from first kit to pro.",
  Places: "Cornish harbours, beaches and coastal spots worth the trip.",
  Stories: "Cornwall's history, sea songs and salty tales.",
};

function DesktopNav() {
  const M = window.DTC.MENU;
  const K = window.DTC.KNOWLEDGE_MENU;
  const L = window.DTC.NAV_LINKS;
  const [open, setOpen] = React.useState(null);   // 'collections' | 'knowledge' | 'offers'
  const [wi, setWi] = React.useState(0);          // active world in Collections
  const [ki, setKi] = React.useState(0);          // active category in Knowledge
  const closeT = React.useRef(null);

  const enter = (k) => { clearTimeout(closeT.current); if (open !== k) { setOpen(k); setWi(0); setKi(0); } };
  const hold = () => clearTimeout(closeT.current);
  const leave = () => { clearTimeout(closeT.current); closeT.current = setTimeout(() => setOpen(null), 160); };

  const w = M[wi];
  const k = K[ki];

  return (
    <nav className="hp-dnav" aria-label="Primary" onMouseLeave={leave}>
      <div className="hp-dnav__row" onMouseEnter={hold}>
        <a className="hp-dnav__link" href="./" onMouseEnter={() => setOpen(null)}>Home</a>

        <div className="hp-dnav__item" data-open={open === "collections"} onMouseEnter={() => enter("collections")}>
          <a className="hp-dnav__link" href={L.shopAll} aria-haspopup="true" aria-expanded={open === "collections"}
             onFocus={() => enter("collections")}>
            Collections <Icon name="chevron-down" size={14} />
          </a>
        </div>

        <div className="hp-dnav__item" data-open={open === "knowledge"} onMouseEnter={() => enter("knowledge")}>
          <a className="hp-dnav__link" href={L.knowledge} aria-haspopup="true" aria-expanded={open === "knowledge"}
             onFocus={() => enter("knowledge")}>
            Knowledge <Icon name="chevron-down" size={14} />
          </a>
        </div>

        <div className="hp-dnav__item" data-open={open === "offers"} onMouseEnter={() => enter("offers")}>
          <a className="hp-dnav__link" href={L.offers} aria-haspopup="true" aria-expanded={open === "offers"}
             onFocus={() => enter("offers")}>
            Offers <Icon name="chevron-down" size={14} />
          </a>
          {open === "offers" ? (
            <div className="hp-mm-offers" onMouseEnter={hold}>
              <a className="hp-mm-offers__row" href={L.offers}>
                <span className="hp-mm-offers__ico hp-mm-offers__ico--sale"><Icon name="star" size={17} /></span>
                <span className="hp-mm-offers__txt"><b>Sale</b><em>Seasonal price drops across the cove</em></span>
                <Icon name="chevron-right" size={16} />
              </a>
              <a className="hp-mm-offers__row" href={L.offers}>
                <span className="hp-mm-offers__ico hp-mm-offers__ico--time"><Icon name="rotate-ccw" size={17} /></span>
                <span className="hp-mm-offers__txt"><b>Limited-Time Deals</b><em>Here for a tide, then gone</em></span>
                <Icon name="chevron-right" size={16} />
              </a>
              <a className="hp-mm-offers__row" href={L.offers}>
                <span className="hp-mm-offers__ico hp-mm-offers__ico--clear"><Icon name="shopping-bag" size={17} /></span>
                <span className="hp-mm-offers__txt"><b>Clearance</b><em>End-of-line kit at its lowest</em></span>
                <Icon name="chevron-right" size={16} />
              </a>
              <a className="hp-mm-offers__promo" href={L.offers}>
                <Icon name="gift" size={16} />
                <span><b>Father's Day picks</b> — order by Thu 18 June</span>
                <Icon name="arrow-right" size={14} />
              </a>
            </div>
          ) : null}
        </div>

        <a className="hp-dnav__link" href={L.coveClub} onMouseEnter={() => setOpen(null)}>Cove Club</a>
        <a className="hp-dnav__link" href={L.coastlines} onMouseEnter={() => setOpen(null)}>Coastlines</a>
        <a className="hp-dnav__link" href={L.affiliate} onMouseEnter={() => setOpen(null)}>Affiliate</a>
        <a className="hp-dnav__link" href={L.about} onMouseEnter={() => setOpen(null)}>About</a>
      </div>

      {/* ── Collections mega: worlds rail | groups | feature card ── */}
      {open === "collections" ? (
        <div className="hp-mm" onMouseEnter={hold}>
          <div className="hp-mm__inner hp-mm__inner--shop">
            <div className="hp-mm__rail" role="list">
              {M.map((m, i) => (
                <a className="hp-mm__world" data-active={i === wi} href={m.href} key={m.title}
                   onMouseEnter={() => setWi(i)} onFocus={() => setWi(i)}>
                  <img src={"assets/" + m.img} alt="" loading="lazy" />
                  <span className="hp-mm__wname">{m.title}<em>{m.groups[0].links.length + m.groups[1].links.length}+ ranges</em></span>
                  <Icon name="chevron-right" size={16} />
                </a>
              ))}
              <a className="hp-mm__allshop" href={L.shopAll}>Shop all collections <Icon name="arrow-right" size={14} /></a>
            </div>
            <div className="hp-mm__pane" key={w.title}>
              <div className="hp-mm__phead">
                <h4>{w.title}</h4>
                <p>{WORLD_BLURBS[w.title] || ""}</p>
              </div>
              <div className="hp-mm__groups">
                {w.groups.filter((g) => g.title !== "Featured").map((g) => (
                  <div className="hp-mm__group" key={g.title}>
                    <p className="hp-mm__gt">{g.title}</p>
                    <ul>
                      {g.links.map((l) => <li key={l.label}><a href={l.href}>{l.label}</a></li>)}
                    </ul>
                  </div>
                ))}
              </div>
              {(w.groups.find((g) => g.title === "Featured") || { links: [] }).links.length ? (
                <div className="hp-mm__chips">
                  {(w.groups.find((g) => g.title === "Featured")).links.map((l, idx, arr) => (
                    <a className={"hp-mm__chip" + (idx === arr.length - 1 ? " hp-mm__chip--solid" : "")} href={l.href} key={l.label}>
                      {idx === 0 ? <Icon name="star" size={13} /> : null}{l.label}
                      {idx === arr.length - 1 ? <Icon name="arrow-right" size={13} /> : null}
                    </a>
                  ))}
                </div>
              ) : null}
            </div>
            <a className="hp-mm__feature" href={w.href} key={"f" + w.title}>
              <img src={"assets/" + w.img} alt="" loading="lazy" />
              <span className="hp-mm__fscrim" />
              <span className="hp-mm__fbody">
                <span className="hp-mm__ftitle">{w.title}</span>
                <span className="hp-mm__fcta">Shop all {w.title} <Icon name="arrow-right" size={14} /></span>
              </span>
            </a>
          </div>
        </div>
      ) : null}

      {/* ── Knowledge mega: categories rail | guides pane ── */}
      {open === "knowledge" ? (
        <div className="hp-mm" onMouseEnter={hold}>
          <div className="hp-mm__inner hp-mm__inner--know">
            <div className="hp-mm__rail" role="list">
              {K.map((c, i) => (
                <a className="hp-mm__world hp-mm__world--text" data-active={i === ki} href={c.href} key={c.title}
                   onMouseEnter={() => setKi(i)} onFocus={() => setKi(i)}>
                  <span className="hp-mm__wname">{c.title}</span>
                  <Icon name="chevron-right" size={16} />
                </a>
              ))}
              <a className="hp-mm__allshop" href={L.knowledge}>Browse the Knowledge hub <Icon name="arrow-right" size={14} /></a>
            </div>
            <div className="hp-mm__kpane" key={k.title}>
              <p className="hp-mm__keyebrow">Knowledge · {k.title}</p>
              <p className="hp-mm__kblurb">{KNOWLEDGE_BLURBS[k.title] || ""}</p>
              {k.examples.length ? (
                <div className="hp-mm__klinks">
                  {k.examples.map((e) => (
                    <a href={e.href} key={e.label}><Icon name="chevron-right" size={14} />{e.label}</a>
                  ))}
                </div>
              ) : null}
              <a className="hp-mm__kbrowse" href={k.href}>{k.browse} <Icon name="arrow-right" size={14} /></a>
              <p className="hp-mm__knote">Advice is part of the parcel — hundreds of free guides, written by the family.</p>
            </div>
          </div>
        </div>
      ) : null}
    </nav>
  );
}

/* ── Mobile menu sheet — Shop = 5 worlds → sub-menus; Guides = knowledge ── */
function MenuSheet({ kind, onClose, onBrowsePreview }) {
  const [openAcc, setOpenAcc] = React.useState(null);
  React.useEffect(() => { setOpenAcc(null); }, [kind]);
  if (!kind) return null;
  const L = window.DTC.NAV_LINKS;
  const isShop = kind === "shop";
  const rows = isShop ? window.DTC.MENU : window.DTC.KNOWLEDGE_MENU;
  return (
    <div className="hp-overlay" data-open="true">
      <div className="hp-overlay__scrim" onClick={onClose} />
      <div className="hp-sheet hp-menusheet" role="dialog" aria-label={isShop ? "Shop menu" : "Guides menu"}>
        <div className="hp-sheet__grip" />
        <div className="hp-sheet__head">
          <h3>{isShop ? "Shop the cove" : "Knowledge & guides"}</h3>
          <button className="hp-iconbtn" onClick={onClose} aria-label="Close menu"><Icon name="x" size={20} /></button>
        </div>
        <div className="hp-menusheet__body">
          {isShop ? (
            <div className="hp-menusheet__top">
              <a className="hp-menusheet__pill" href={L.shopAll}>Shop All <Icon name="arrow-right" size={14} /></a>
              <a className="hp-menusheet__pill" href={L.bestSellers}>Best Sellers <Icon name="arrow-right" size={14} /></a>
              <a className="hp-menusheet__pill" href={L.offers}>Offers <Icon name="arrow-right" size={14} /></a>
            </div>
          ) : (
            <div className="hp-menusheet__top">
              <a className="hp-menusheet__pill" href={L.knowledge}>All guides <Icon name="arrow-right" size={14} /></a>
            </div>
          )}
          {rows.map((r) => {
            const open = openAcc === r.title;
            return (
              <div className="hp-menusheet__acc" data-open={open} key={r.title}>
                <button className="hp-menusheet__row" aria-expanded={open}
                        onClick={() => setOpenAcc(open ? null : r.title)}>
                  {isShop && r.img ? <img className="hp-menusheet__thumb" src={"assets/" + r.img} alt="" /> : null}
                  <span>{r.title}</span>
                  <Icon name="chevron-down" size={18} />
                </button>
                <div className="hp-menusheet__panel">
                  {isShop ? (
                    <React.Fragment>
                      <a className="hp-menusheet__all" href={r.href}>Shop all {r.title} <Icon name="arrow-right" size={13} /></a>
                      {r.groups.map((g) => (
                        <div className="hp-menusheet__group" key={g.title}>
                          <p className="hp-menusheet__gt">{g.title}</p>
                          {g.links.map((l) => <a className="hp-menusheet__leaf" href={l.href} key={l.label}>{l.label}</a>)}
                        </div>
                      ))}
                    </React.Fragment>
                  ) : (
                    <React.Fragment>
                      {r.examples.map((e) => <a className="hp-menusheet__leaf" href={e.href} key={e.label}>{e.label}</a>)}
                      <a className="hp-menusheet__all" href={r.href}>{r.browse} <Icon name="arrow-right" size={13} /></a>
                    </React.Fragment>
                  )}
                </div>
              </div>
            );
          })}
          <button className="hp-menusheet__preview" onClick={onBrowsePreview}>
            {isShop ? "Or browse the sample shop on this page" : "Or see the guide highlights on this page"} <Icon name="chevron-right" size={14} />
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PromoBar, Header, QuickNav, BottomTabBar, Toast, DesktopNav, MenuSheet });
