// Navigation — Vendoo Design System
// Three surfaces that move people through Vendoo: a bottom Navigation bar (mobile),
// a side Navigation rail (web), and a Navigation drawer (full destination list).
// One selection language — a tonal pill behind the active item. Requires tokens.css
// + assets/icons.js. React is global.
//
// ── This file ───────────────────────────────────────────────────────────────
// Updated component (rail brought up to the documented rail, plus a responsive
// "auto" surface). Authored to be loaded straight in the browser as a Babel
// script: it registers `Navigation` on window.VendooDesignSystem_a81b7b instead
// of using a top-level `export` (the in-browser Babel transform rejects ESM
// `export`). When compiled into the design-system bundle this same body is
// wrapped with `export function Navigation(…)`.
// ─────────────────────────────────────────────────────────────────────────────

(function () {
  const React = window.React;

  // CSS is appended under a fresh id (…-v2) so this updated rail always wins,
  // even if an older `vds-nav-css` block from the bundle is already present.
  const VDS_NAV_CSS = `
.vds-nav{ font-family:"Lexend",system-ui,sans-serif; }
.vds-nav-sl{ position:relative; isolation:isolate; }
.vds-nav-sl > *{ position:relative; z-index:1; }
.vds-nav-sl::before{ content:""; position:absolute; inset:0; border-radius:inherit; background:transparent;
  pointer-events:none; z-index:0; transition:background var(--dur-medium,150ms) var(--ease-standard,cubic-bezier(0.2,0,0,1)); }
.vds-nav-sl:hover::before{ background:var(--state-layers-onSurfaceVariant-opacity-0_08); }
.vds-nav-sl:active::before{ background:var(--state-layers-onSurfaceVariant-opacity-0_10); }

/* Bar — unchanged */
.vds-navbar{ width:412px; height:72px; background:var(--sys-surface-container); display:flex; flex-direction:row;
  align-items:center; padding:8px 0; box-sizing:border-box; }
.vds-bar-item{ flex:1; display:flex; flex-direction:column; align-items:center; gap:4px; padding:6px 0; cursor:pointer; }
.vds-bar-item__icon{ width:56px; height:32px; border-radius:var(--radius-xs); display:flex; align-items:center; justify-content:center; }
.vds-bar-item__icon v-icon{ width:24px; height:24px; color:var(--sys-on-surface-variant); display:block; }
.vds-bar-item__label{ font:var(--type-label-medium); color:var(--sys-on-surface-variant); }
.vds-bar-item--sel .vds-bar-item__icon{ background:var(--sys-secondary-container); }
.vds-bar-item--sel .vds-bar-item__icon v-icon{ color:var(--sys-on-secondary-container); }
.vds-bar-item--sel .vds-bar-item__label{ color:var(--sys-secondary); }
.vds-bar-fab{ flex:none; width:56px; height:56px; margin:0 6px; border-radius:var(--radius-sm);
  background:var(--sys-primary); color:var(--sys-on-primary); display:flex; align-items:center; justify-content:center; box-shadow:var(--elev-3); }
.vds-bar-fab v-icon{ width:24px; height:24px; display:block; }

/* Rail — matches the documented rail: brand · menu + extended FAB · segments · settings.
   min-height 800px and GROWS with content (no fixed height, no overflow clip);
   Settings stays pinned to the bottom via margin-top:auto. */
.vds-rail{ width:220px; box-sizing:border-box; background:var(--sys-surface-container); border-radius:var(--radius-lg);
  padding:40px 24px; display:flex; flex-direction:column; min-height:800px; }
.vds-rail__brand{ min-height:35px; margin-bottom:44px; display:flex; align-items:center; }
.vds-rail__brand img{ display:block; width:148px; height:auto; }
.vds-rail__brand--text{ font:var(--type-title-large); color:var(--sys-primary); font-weight:700; }
.vds-rail__top{ display:flex; flex-direction:column; gap:16px; margin-bottom:28px; }
.vds-rail__segments{ display:flex; flex-direction:column; gap:0; }
.vds-rail__settings{ margin-top:auto; padding-top:8px; }

.vds-rail-iconbtn{ width:48px; height:48px; border:0; background:transparent; -webkit-appearance:none; appearance:none;
  border-radius:var(--radius-xs); display:flex; align-items:center; justify-content:center;
  color:var(--sys-on-surface-variant); cursor:pointer; padding:0; font-family:inherit; }
.vds-rail-iconbtn v-icon{ width:24px; height:24px; display:block; }

.vds-rail-fab{ align-self:flex-start; height:48px; border:0; border-radius:var(--radius-xs);
  background:var(--sys-primary); color:var(--sys-on-primary); display:inline-flex; align-items:center; gap:8px;
  padding:0 24px; cursor:pointer; box-shadow:var(--elev-3); font-family:inherit; }
.vds-rail-fab .vds-nav__lbl{ font:var(--type-label-large); color:var(--sys-on-primary); white-space:nowrap; }
.vds-rail-fab v-icon{ width:24px; height:24px; color:var(--sys-on-primary); display:block; }

.vds-rail-item{ align-self:flex-start; max-width:100%; min-height:56px; border-radius:var(--radius-md);
  display:inline-flex; align-items:center; gap:8px; padding:16px; cursor:pointer; box-sizing:border-box; }
.vds-rail-item v-icon{ width:24px; height:24px; color:var(--sys-on-surface-variant); flex:none; display:block; }
.vds-rail-item .vds-nav__lbl{ font:var(--type-label-large); color:var(--sys-on-surface-variant); white-space:nowrap; }
.vds-rail-item--sel{ background:var(--sys-secondary-container); }

/* Drawer — unchanged */
.vds-drawer{ width:360px; box-sizing:border-box; background:var(--sys-surface-container-low); border-radius:var(--radius-lg);
  padding:12px; display:flex; flex-direction:column; }
.vds-drawer-item{ width:100%; min-height:52px; border-radius:var(--radius-md); display:flex; align-items:center; gap:8px;
  padding:16px; cursor:pointer; margin:1px 0; box-sizing:border-box; }
.vds-drawer-item .vds-nav__lbl{ font:var(--type-label-large); color:var(--sys-on-surface-variant); }
.vds-drawer-item--sel{ background:var(--sys-primary-fixed); }
`;

  function vdsInjectCss(id, css) {
    if (typeof document === "undefined" || document.getElementById(id)) return;
    const s = document.createElement("style"); s.id = id; s.textContent = css; document.head.appendChild(s);
  }

  const VDS_BAR_DEFAULT = [
    { label: "Inventory", icon: "package" },
    { label: "Markets", icon: "store" },
    { label: "Analytics", icon: "analytics" },
    { label: "Automations", icon: "zap" },
  ];
  const VDS_RAIL_DEFAULT = [
    { label: "Inventory", icon: "package" },
    { label: "Markets", icon: "store" },
    { label: "Analytics", icon: "analytics" },
    { label: "Automations", icon: "zap" },
  ];
  const VDS_DRAWER_DEFAULT = [
    { label: "Inventory" }, { label: "Drafts" }, { label: "Active listings" }, { label: "Sold" },
  ];

  // Default breakpoint for surface="auto": the BAR renders below it, the RAIL
  // at/above it. OPEN DECISION — proposed 840px, confirm with design.
  const VDS_AUTO_BREAKPOINT = 840;

  function Navigation({
    surface = "bar",          // "auto" | "bar" | "rail" | "drawer"
    items,
    selected = 0,
    fabIcon = "plus_circle",  // bar — centre FAB glyph
    brand = "Vendoo",         // rail — fallback when no logo image is set
    breakpoint = VDS_AUTO_BREAKPOINT, // auto — bar below / rail at-or-above (px)
    // ── rail logo slot ──
    showLogo = true,          // reserve the slot even when false (layout stays stable)
    logo = "assets/logos/vendoo-lockup.svg", // brand image; "" falls back to the text wordmark
    logoAlt = "Vendoo",
    // ── rail extended FAB (always rendered) ──
    railFabLabel = "New listing",
    railFabIcon = "plus_circle",
    // ── rail menu icon button ──
    menuIcon = "menu_open",
    // ── rail Settings (always pinned to the bottom) ──
    settingsLabel = "Settings",
    settingsIcon = "settings",
    onSelect,
  }) {
    vdsInjectCss("vds-nav-css-v2", VDS_NAV_CSS);

    // ── Responsive surface switch (auto) ───────────────────────────────────
    // Measure the CONTAINER the nav is dropped into (not the window) so the
    // switch tracks the live-preview viewport / any resized parent.
    if (surface === "auto") {
      const wrapRef = React.useRef(null);
      const [eff, setEff] = React.useState("rail");
      React.useLayoutEffect(function () {
        const el = wrapRef.current;
        if (!el) return;
        let last = null;
        const measure = function () {
          const w = el.getBoundingClientRect().width;
          if (!w) return;
          const next = w >= breakpoint ? "rail" : "bar";
          if (next !== last) { last = next; setEff(next); }
        };
        measure();
        let ro = null;
        if (typeof ResizeObserver !== "undefined") {
          ro = new ResizeObserver(measure);
          ro.observe(el);
        }
        window.addEventListener("resize", measure);
        // Safety net: some embedded/headless contexts don't tick ResizeObserver,
        // so poll the container width as well (cheap; only re-renders on a flip).
        const poll = window.setInterval(measure, 250);
        return function () {
          if (ro) ro.disconnect();
          window.removeEventListener("resize", measure);
          window.clearInterval(poll);
        };
      }, [breakpoint]);
      return (
        <div ref={wrapRef} data-nav-auto={eff}
          style={{ width: "100%", display: "flex", justifyContent: eff === "rail" ? "flex-start" : "center" }}>
          <Navigation
            surface={eff} items={items} selected={selected}
            fabIcon={fabIcon} brand={brand}
            showLogo={showLogo} logo={logo} logoAlt={logoAlt}
            railFabLabel={railFabLabel} railFabIcon={railFabIcon}
            menuIcon={menuIcon} settingsLabel={settingsLabel} settingsIcon={settingsIcon}
            onSelect={onSelect} />
        </div>
      );
    }

    if (surface === "rail") {
      const data = items || VDS_RAIL_DEFAULT;
      const settingsIdx = data.length; // Settings sits after the last destination
      return (
        <nav className="vds-nav vds-rail" aria-label="Navigation rail">
          {/* logo slot — always reserves space; hidden = empty slot, layout unchanged */}
          <div className="vds-rail__brand" aria-hidden={!showLogo}>
            {showLogo
              ? (logo
                  ? <img src={logo} alt={logoAlt} />
                  : <span className="vds-rail__brand--text">{brand}</span>)
              : null}
          </div>

          {/* menu icon button + extended FAB — always rendered */}
          <div className="vds-rail__top">
            <button type="button" className="vds-rail-iconbtn vds-nav-sl" aria-label="Open menu">
              <v-icon name={menuIcon}></v-icon>
            </button>
            <button type="button" className="vds-rail-fab">
              <span className="vds-nav__lbl">{railFabLabel}</span>
              <v-icon name={railFabIcon}></v-icon>
            </button>
          </div>

          {/* primary destinations */}
          <div className="vds-rail__segments">
            {data.map((it, i) => (
              <div key={i} className={"vds-rail-item vds-nav-sl" + (i === selected ? " vds-rail-item--sel" : "")}
                onClick={() => onSelect && onSelect(it, i)}>
                <v-icon name={it.icon}></v-icon><span className="vds-nav__lbl">{it.label}</span>
              </div>
            ))}
          </div>

          {/* Settings — always pinned to the bottom */}
          <div className="vds-rail__settings">
            <div className={"vds-rail-item vds-nav-sl" + (selected === settingsIdx ? " vds-rail-item--sel" : "")}
              onClick={() => onSelect && onSelect({ label: settingsLabel, icon: settingsIcon }, settingsIdx)}>
              <v-icon name={settingsIcon}></v-icon><span className="vds-nav__lbl">{settingsLabel}</span>
            </div>
          </div>
        </nav>
      );
    }

    if (surface === "drawer") {
      const data = items || VDS_DRAWER_DEFAULT;
      return (
        <nav className="vds-nav vds-drawer" aria-label="Navigation drawer">
          {data.map((it, i) => (
            <div key={i} className={"vds-drawer-item vds-nav-sl" + (i === selected ? " vds-drawer-item--sel" : "")}
              onClick={() => onSelect && onSelect(it, i)}>
              <span className="vds-nav__lbl">{it.label}</span>
            </div>
          ))}
        </nav>
      );
    }

    // bar (default) — split items around the centered FAB
    const data = items || VDS_BAR_DEFAULT;
    const mid = Math.ceil(data.length / 2);
    const renderItem = (it, i) => (
      <div key={i} className={"vds-bar-item" + (i === selected ? " vds-bar-item--sel" : "")}
        onClick={() => onSelect && onSelect(it, i)}>
        <div className="vds-bar-item__icon vds-nav-sl"><v-icon name={it.icon}></v-icon></div>
        <span className="vds-bar-item__label">{it.label}</span>
      </div>
    );
    return (
      <nav className="vds-nav vds-navbar" aria-label="Navigation bar">
        {data.slice(0, mid).map(renderItem)}
        <div className="vds-bar-fab"><v-icon name={fabIcon}></v-icon></div>
        {data.slice(mid).map((it, i) => renderItem(it, i + mid))}
      </nav>
    );
  }

  // Register on the design-system namespace, overriding the bundle's Navigation
  // so the playground previews this updated component.
  const ns = (window.VendooDesignSystem_a81b7b = window.VendooDesignSystem_a81b7b || {});
  ns.Navigation = Navigation;
  Navigation.VDS_AUTO_BREAKPOINT = VDS_AUTO_BREAKPOINT;
})();
