// TopBar — the single site header used on every page. Logo sits top-left always.
// Three modes by page:
//   • home               → simple nav (projects · about · contact) at the RIGHT corner
//   • projects / detail   → filter group CENTER + (about · contact) RIGHT, caret on active
//   • about / contact     → simple nav CENTER with the active item highlighted + caret
// The header is absolutely positioned over the top band so each page's content can
// begin at a fixed offset (250px / 220px) below it.
function TopBar({ page, filter, setFilter, go, projects, filterOrder }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [projOpen, setProjOpen] = React.useState(false);
  // Add a subtle border when page is scrolled
  // Toggle a hairline/pin state once the page is scrolled. Re-run on every page
  // change so a stale `.scrolled` from a previous page is cleared the moment a
  // fresh page loads at scrollTop 0 (e.g. about/contact open with the logo at
  // its landing position, then pin as you actually scroll).
  React.useEffect(() => {
    const el = document.querySelector(".topbar");
    const onScroll = () => el && el.classList.toggle("scrolled", window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [page]);
  // Derive filter list dynamically from all project tags. "selected" is always
  // first; the rest follow the author-controlled order in `filterOrder` (set
  // from the Tweaks panel). Any tag a project uses that ISN'T in filterOrder
  // auto-appears after the ordered ones (alphabetically) — so the top bar stays
  // in sync when projects gain new disciplines.
  const filters = React.useMemo(() => {
    const orderMap = {};
    (filterOrder || []).forEach((name, i) => {
      const n = String(name || "").toLowerCase().trim();
      if (n && !(n in orderMap)) orderMap[n] = i;
    });
    const seen = new Set();
    (projects || []).forEach((p) => {
      const source = p.disciplines || p.tags || "";
      if (!source) return;
      source.split(",").forEach((t) => {
        const tag = t.trim().toLowerCase();
        if (tag && tag !== "production") seen.add(tag);
      });
    });
    const sorted = [...seen].sort((a, b) => {
      const ai = a in orderMap ? orderMap[a] : Infinity;
      const bi = b in orderMap ? orderMap[b] : Infinity;
      if (ai === bi) return a.localeCompare(b);
      return ai - bi;
    });
    return [["all", "selected"], ...sorted.map((t) => [t, t])];
  }, [projects, filterOrder]);
  const simple = [["projects", "works"], ["about", "about"], ["contact", "contact"]];

  const mode = page === "home" ? "home"
    : (page === "about" || page === "contact") ? "info"
    : "filter"; // projects + detail

  const pick = (k) => { setFilter(k); go("projects"); };
  // Navigating to projects from the plain nav (home/about/contact) always
  // resets the filter to "selected" (all) so you land on the full list.
  const goProjects = () => { setFilter("all"); go("projects"); };

  // Mobile menu helpers — close the panel, then navigate / pick a filter.
  const goM = (p, id) => { setMenuOpen(false); setProjOpen(false); go(p, id); };
  const pickM = (k) => { setMenuOpen(false); setProjOpen(false); pick(k); };
  // Mobile: a slim cream bar holds only the logo + hamburger. The menu itself
  // is a full-width cream panel that slides DOWN from under the bar (below).
  const mobileNav = (
    <div className="topbar-mobile">
      <button className="hamburger" aria-label="menu" aria-expanded={menuOpen}
              onClick={() => setMenuOpen((o) => !o)}>{menuOpen ? "\u00D7" : "\u2630"}</button>
    </div>
  );
  // Full-width slide-down panel. Always rendered (so the slide can animate);
  // visibility + slide are driven by the `open` class. works · about · contact,
  // with the category list tucked under works (tap the caret to reveal).
  const mobileMenu = (
    <div className={"mobile-menu" + (menuOpen ? " open" : "")}>
      <button className="mm-item" onClick={() => { setMenuOpen(false); setProjOpen(false); if (setFilter) setFilter("all"); go("projects"); }}>
        <span>works</span>
        <span className={"mm-caret" + (projOpen ? " open" : "")}
              onClick={(e) => { e.stopPropagation(); setProjOpen((o) => !o); }}>{"\u2304"}</span>
      </button>
      {projOpen && (
        <div className="mm-sub">
          {filters.map(([k, label]) => (
            <button key={k} className={"mm-subitem" + (filter === k ? " active" : "")}
                    onClick={() => pickM(k)}>{label}</button>
          ))}
        </div>
      )}
      <button className="mm-item" onClick={() => goM("about")}>about</button>
      <button className="mm-item" onClick={() => goM("contact")}>contact</button>
    </div>
  );

  // label whose width is reserved at bold, so the active state never shifts neighbors
  const Label = ({ text }) => (
    <span className="tlabel" data-t={text}><span>{text}</span></span>
  );

  const logo = (
    <button className="topbar-logo" onClick={() => go("home")} aria-label="home">
      <image-slot id="home-logo" shape="rect" data-store="home" style={{ pointerEvents: "none" }}></image-slot>
    </button>
  );

  // filter group (center) — used on projects / detail
  const filterNav = (
    <nav className="topbar-center">
      {filters.map(([k, label]) => (
        <button key={k} className={"tf" + (filter === k && page !== "detail" ? " active" : "")} onClick={() => pick(k)}>
          <Label text={label} />
          {filter === k && <span className={"caret" + (page === "detail" ? " caret-up" : "")}>{"\u2304"}</span>}
        </button>
      ))}
    </nav>
  );

  // simple nav — used on home (right) and about/contact (right, active highlighted)
  const simpleNav = (cls) => (
    <nav className={cls}>
      {simple.map(([k, label]) => {
        const active = mode === "info" && page === k;
        return (
          <button key={k} className="tf" onClick={() => k === "projects" ? goProjects() : go(k)}>
            <Label text={label} />
            {active && <span className="caret">{"\u2304"}</span>}
          </button>
        );
      })}
    </nav>
  );

  let center, right;
  if (mode === "filter") {
    center = filterNav;
    right = (
      <nav className="topbar-right">
        <a className="tf" onClick={() => go("about")}><Label text="about" /></a>
        <a className="tf" onClick={() => go("contact")}><Label text="contact" /></a>
      </nav>
    );
  } else if (mode === "info") {
    center = <nav className="topbar-center"></nav>;
    right = simpleNav("topbar-right");
  } else { // home
    center = <nav className="topbar-center"></nav>;
    right = simpleNav("topbar-right");
  }

  return (
    <React.Fragment>
      <header className="topbar fade">
        {logo}
        {center}
        {right}
        {mobileNav}
      </header>
      {mobileMenu}
    </React.Fragment>
  );
}
window.TopBar = TopBar;
