// d4not — Top bar, safety strip, hero, filter rail

function SafetyStrip({ onLearn, onClose, shown }) {
  if (!shown) return null;
  return (
    <div className="safestrip">
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 16px" }}>
        <span className="bang">HEADS UP</span>
        <span className="mark">
          d4not library doesn't host code. Every link sends you to an external repo. Audit before you run — we scan, but we can miss things.
        </span>
        <span className="learn" onClick={onLearn}>How we review →</span>
        <span className="close" onClick={onClose}>✕</span>
      </div>
      <div style={{
        display: "flex", alignItems: "center", gap: 10, padding: "6px 16px",
        background: "var(--yellow)", color: "#111",
        borderTop: "1px solid rgba(0,0,0,0.15)",
      }}>
        <span className="bang" style={{ background: "#111", color: "var(--yellow)" }}>TEST SITE</span>
        <span className="mark" style={{ color: "#111" }}>
          d4not library is in public beta. Accounts, submissions and forum posts may be reset without notice. Report bugs:&nbsp;
          <a href="mailto:contact@d4notlibrary.com" style={{ color: "inherit", textDecoration: "underline" }}>contact@d4notlibrary.com</a>
        </span>
      </div>
    </div>
  );
}

function TopBar({ onUploadClick, theme, onTheme }) {
  const [profile, setProfile] = React.useState(null);

  React.useEffect(() => {
    let ignore = false;
    (async () => {
      if (!window.D4API) return;
      const p = await window.D4API.currentProfile().catch(() => null);
      if (!ignore) setProfile(p);
      window.D4API.client.auth.onAuthStateChange(async () => {
        const p2 = await window.D4API.currentProfile().catch(() => null);
        if (!ignore) setProfile(p2);
      });
    })();
    return () => { ignore = true; };
  }, []);

  async function doLogout() {
    if (window.D4API) await window.D4API.signOut();
    location.reload();
  }

  return (
    <header className="topbar">
      <div className="brand" onClick={() => location.href = "index.html"} style={{ cursor: "pointer" }}>
        <Wordmark />
        <span className="bar" />
      </div>

      <nav>
        <a href="index.html">Home</a>
        <a href="library.html" className="active">For builders</a>
        <a href="everyone.html">For everyone</a>
        <a href="manifesto.html">Manifesto</a>
        <a href="safety.html">Safety</a>
        <a href="donate.html">Donate</a>
      </nav>

      <div className="actions">
        <button className="btn ghost tiny" onClick={() => onTheme(theme === "bone" ? "dark" : "bone")}>
          {theme === "bone" ? "☾ Dark" : "☼ Bone"}
        </button>
        {profile
          ? <><span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-3)", padding: "0 8px" }}>@{profile.handle}</span>
              <button className="btn ghost tiny" onClick={doLogout}>Log out</button></>
          : <><a className="btn ghost tiny" href="auth.html">Sign in</a>
              <a className="btn ghost tiny" href="auth.html?mode=signup">Sign up</a></>
        }
        <button className="btn primary" onClick={onUploadClick}>
          ＋ Publish
        </button>
      </div>
    </header>
  );
}

function Hero({ query, onQuery, totalProjects, totalTokens, totalAuthors }) {
  const inputRef = useRef(null);
  useEffect(() => {
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); inputRef.current?.focus(); }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <section className="hero">
      <div className="hero-inner">
        <div>
          <div className="by">
            <span className="signet">BY d4not</span>
            <span>vol. III — № 04 · cataloged apr 19, 2026</span>
          </div>
          <h1 className="megat">
            DON'T <br />
            <span className="slash">REGENERATE</span><br />
            WHAT <span className="strike">EXISTS</span>.
          </h1>
          <p className="dek">
            d4not library is an <b style={{ color: "var(--yellow)", fontWeight: 400 }}>open index</b> of work
            already done — apps, templates, agents, CLIs and more. Not just for programmers.
            Search before you build. Contribute when you ship.
          </p>

          <div className="hero-search">
            <span className="prompt">&gt;</span>
            <input
              ref={inputRef} value={query} onChange={e => onQuery(e.target.value)}
              placeholder='find "tauri firewall" · "kanban with subtasks" · "go log tailer"'
            />
            <span className="kbd">
              <span className="kbd-key">⌘</span><span className="kbd-key">K</span>
            </span>
          </div>
        </div>

        <aside className="hero-aside">
          <h3>We index. We don't host.</h3>
          <p>
            Every entry is a redirect to the author's GitHub, GitLab, Codeberg or personal URL. We review
            what we can and flag the rest — but the code runs on your machine, so <b style={{color: "var(--red)"}}>read before you run</b>.
          </p>
          <div className="row" style={{ marginTop: 6 }}>
            <div><b>{fmt(totalProjects)}</b><br />indexed</div>
            <div><b>{fmt(totalAuthors)}</b><br />authors</div>
            <div><b>{fmtTokens(totalTokens)}</b><br />tokens spared</div>
          </div>
        </aside>
      </div>
    </section>
  );
}

function RailSection({ title, count, defaultOpen = true, children }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ marginBottom: 4 }}>
      <button
        onClick={() => setOpen(!open)}
        style={{
          width: "100%", display: "flex", justifyContent: "space-between",
          alignItems: "baseline", padding: "8px 0 6px",
          fontFamily: "var(--display)", fontSize: 11,
          letterSpacing: "0.18em", textTransform: "uppercase",
          color: "var(--ink-3)", borderBottom: "1px solid var(--rule)",
          marginBottom: open ? 6 : 0,
        }}
      >
        <span>{title} {count != null && <span style={{ fontFamily: "var(--mono)", color: "var(--ink-4)", letterSpacing: 0, fontWeight: 400 }}>{count}</span>}</span>
        <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-4)" }}>{open ? "▲" : "▼"}</span>
      </button>
      {open && children}
    </div>
  );
}

function FilterRail({
  surfaces, origins, trust,
  selectedSurfaces, setSelectedSurfaces,
  selectedLangs, setSelectedLangs,
  selectedFrameworks, setSelectedFrameworks,
  selectedTopics, setSelectedTopics,
  selectedPlatforms, setSelectedPlatforms,
  selectedOrigins, setSelectedOrigins,
  selectedTrust, setSelectedTrust,
  selectedHosts, setSelectedHosts,
  selectedSizes, setSelectedSizes,
  counts,
}) {
  function toggle(set, setSet, id) {
    const next = new Set(set);
    if (next.has(id)) next.delete(id); else next.add(id);
    setSet(next);
  }

  const totalActive =
    selectedSurfaces.size + selectedLangs.size + selectedFrameworks.size +
    selectedTopics.size + selectedPlatforms.size + selectedOrigins.size +
    selectedTrust.size + selectedHosts.size + selectedSizes.size;

  return (
    <aside className="rail">
      {/* active count */}
      {totalActive > 0 && (
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "8px 10px", marginBottom: 10,
          background: "var(--bg-2)", border: "1px solid var(--rule-2)",
          fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-2)",
          letterSpacing: "0.08em", textTransform: "uppercase",
        }}>
          <span>{totalActive} filter{totalActive !== 1 ? "s" : ""} active</span>
          <button style={{ color: "var(--red)", fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: "0.1em", textTransform: "uppercase" }}
            onClick={() => {
              setSelectedSurfaces(new Set()); setSelectedLangs(new Set());
              setSelectedFrameworks(new Set()); setSelectedTopics(new Set());
              setSelectedPlatforms(new Set()); setSelectedOrigins(new Set());
              setSelectedTrust(new Set()); setSelectedHosts(new Set());
              setSelectedSizes(new Set());
            }}>Clear all</button>
        </div>
      )}

      <RailSection title="Type" count={surfaces.length}>
        {surfaces.map(s => (
          <button key={s.id} className={"facet" + (selectedSurfaces.has(s.id) ? " on" : "")}
            onClick={() => toggle(selectedSurfaces, setSelectedSurfaces, s.id)}>
            <span className="glyph" style={{ fontFamily: "var(--mono)", fontSize: 11 }}>{s.glyph}</span>
            <span className="lbl">{s.label}</span>
            <span className="count">{counts.surface[s.id] || 0}</span>
          </button>
        ))}
      </RailSection>

      <RailSection title="Language">
        <div className="chip-row">
          {window.LANGUAGES.map(l => (
            <button key={l} className={"chip" + (selectedLangs.has(l) ? " on" : "")}
              onClick={() => toggle(selectedLangs, setSelectedLangs, l)}>{l}</button>
          ))}
        </div>
      </RailSection>

      <RailSection title="Framework / Library" defaultOpen={false}>
        <div className="chip-row">
          {window.FRAMEWORKS.map(f => (
            <button key={f} className={"chip" + (selectedFrameworks.has(f) ? " on" : "")}
              onClick={() => toggle(selectedFrameworks, setSelectedFrameworks, f)}>{f}</button>
          ))}
        </div>
      </RailSection>

      <RailSection title="Topic" defaultOpen={false}>
        {window.TOPICS.map(t => (
          <button key={t.id} className={"facet" + (selectedTopics.has(t.id) ? " on" : "")}
            onClick={() => toggle(selectedTopics, setSelectedTopics, t.id)}>
            <span className="glyph">◈</span>
            <span className="lbl">{t.label}</span>
          </button>
        ))}
      </RailSection>

      <RailSection title="Platform" defaultOpen={false}>
        <div className="chip-row">
          {window.PLATFORMS.map(p => (
            <button key={p.id} className={"chip" + (selectedPlatforms.has(p.id) ? " on" : "")}
              onClick={() => toggle(selectedPlatforms, setSelectedPlatforms, p.id)}>{p.label}</button>
          ))}
        </div>
      </RailSection>

      <RailSection title="Origin">
        {origins.map(o => (
          <button key={o.id} className={"facet" + (selectedOrigins.has(o.id) ? " on" : "")}
            onClick={() => toggle(selectedOrigins, setSelectedOrigins, o.id)}>
            <span className="glyph">◆</span>
            <span className="lbl">{o.label}</span>
            <span className="count">{counts.origin[o.id] || 0}</span>
          </button>
        ))}
      </RailSection>

      <RailSection title="Safety">
        {trust.map(t => (
          <button key={t.id} className={"facet" + (selectedTrust.has(t.id) ? " on" : "")}
            onClick={() => toggle(selectedTrust, setSelectedTrust, t.id)}>
            <span className="glyph" style={{ color:
              t.id === "reviewed" ? "var(--lime)" :
              t.id === "automated" ? "var(--yellow)" : "var(--red)" }}>■</span>
            <span className="lbl">{t.label}</span>
            <span className="count">{counts.trust[t.id] || 0}</span>
          </button>
        ))}
      </RailSection>

      <RailSection title="Host" defaultOpen={false}>
        {window.HOSTS.map(h => (
          <button key={h.id} className={"facet" + (selectedHosts.has(h.id) ? " on" : "")}
            onClick={() => toggle(selectedHosts, setSelectedHosts, h.id)}>
            <span className="glyph">⛬</span>
            <span className="lbl">{h.label}</span>
            <span className="count">{counts.host[h.id] || 0}</span>
          </button>
        ))}
      </RailSection>

      <RailSection title="Project size" defaultOpen={false}>
        {window.SIZES.map(s => (
          <button key={s.id} className={"facet" + (selectedSizes.has(s.id) ? " on" : "")}
            onClick={() => toggle(selectedSizes, setSelectedSizes, s.id)}>
            <span className="glyph">▭</span>
            <span className="lbl">{s.label}</span>
            <span className="count">{counts.size[s.id] || 0}</span>
          </button>
        ))}
      </RailSection>

      <div style={{ marginTop: 20, padding: "12px 0", borderTop: "1px dashed var(--rule)" }}>
        <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: "var(--ink-4)", lineHeight: 1.7, letterSpacing: "0.04em" }}>
          Curated by <span style={{ background: "var(--ink)", color: "var(--bg)", padding: "1px 5px" }}>@d4not</span>
          <br />Ad-free · nothing hosted
        </div>
      </div>
    </aside>
  );
}

Object.assign(window, { SafetyStrip, TopBar, Hero, FilterRail, RailSection });
