// ── Veritee · app shell (nav · tabs · footer · tweaks) ─────────────────────
const { useState: useStateApp, useEffect: useEffectApp, useReducer: useReducerApp } = React;

// The Explorer is the landing tab (Docker-Hub-style: land on the registry).
// "What is Veritee" is the merged Overview + TEE Guarantees page. Status is
// not in the tab group — it is a button beside GitHub — but it is still a
// tab as far as state and the #status hash are concerned.
const TABS = [
  { k: "explorer", label: "Explorer" },
  { k: "about", label: "What is Veritee" },
  { k: "team", label: "Team" },
];
const ALL_TABS = [...TABS.map((t) => t.k), "status"];

// Old deep links keep working: the retired tabs map onto their new homes.
const LEGACY_TABS = { overview: "about", guarantees: "about", developers: "about", stats: "status", transparency: "status" };

const REPO_URL = "https://github.com/input-output-hk/veritee-vm";

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#10A0A8",
  "dither": true,
  "density": "comfortable"
}/*EDITMODE-END*/;

function Nav({ tab, go }) {
  const statusOn = tab === "status";
  const navBtn = {
    display: "inline-flex", alignItems: "center", gap: 8, fontWeight: 600, cursor: "pointer", textDecoration: "none",
    border: "var(--v-border)", padding: "8px 14px", fontSize: 13, fontFamily: "var(--font-sans)", whiteSpace: "nowrap",
    background: "var(--v-surface)", color: "var(--v-ink)", boxShadow: "var(--v-shadow-btn)",
  };
  return (
    <nav style={{ position: "sticky", top: 0, zIndex: 60, background: "var(--v-canvas)", borderBottom: "var(--v-border)" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "12px 56px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px 24px" }} className="tem-nav-inner">
        <VeriteeLogo onClick={(e) => { e.preventDefault(); go("explorer"); }} />
        <div style={{ display: "flex", alignItems: "stretch", border: "var(--v-border)", background: "var(--v-surface)", boxShadow: "var(--v-shadow-btn)" }} className="tem-tabs">
          {TABS.map((t, i) => {
            const on = tab === t.k;
            return (
              <button key={t.k} onClick={() => go(t.k)} className={on ? undefined : "v-wash"} style={{
                border: "none", borderRight: i < TABS.length - 1 ? "var(--v-border)" : "none", cursor: "pointer",
                padding: "9px 18px", fontSize: 14, fontFamily: "var(--font-sans)", fontWeight: 600, whiteSpace: "nowrap",
                background: on ? "var(--v-ink)" : "var(--v-surface)", color: on ? "var(--v-canvas)" : "var(--v-ink)",
              }}>{t.label}</button>
            );
          })}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <button onClick={() => go("status")} className="v-press v-tint" style={{ ...navBtn, background: statusOn ? "var(--v-ink)" : "var(--v-surface)", color: statusOn ? "var(--v-canvas)" : "var(--v-ink)" }}>
            <PixelSquare size={7} />Status
          </button>
          <a href={REPO_URL} className="v-press v-tint" style={navBtn}>GitHub <Icon.ArrowUpRight /></a>
        </div>
      </div>
    </nav>
  );
}

function Footer({ go, dither }) {
  const link = { fontSize: 14, color: "var(--v-canvas)", textDecoration: "none" };
  const head = { fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--v-teal-tint)", marginBottom: 4 };
  const tabLink = (k, label) => (
    <a key={k} href={"#" + k} className="v-footlink" onClick={(e) => { e.preventDefault(); go(k); }} style={link}>{label}</a>
  );
  return (
    <footer style={{ background: "var(--v-ink)", color: "var(--v-canvas)", position: "relative", overflow: "hidden" }}>
      {dither && <div style={{ position: "absolute", inset: "0 0 auto 0", height: 28, background: "var(--v-dither)", opacity: 0.35 }} />}
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "68px 56px 44px", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 40, position: "relative" }}>
        <div style={{ maxWidth: 360, display: "flex", gap: 18, alignItems: "flex-start" }}>
          <img src="assets/manatee-bust.png" alt="" className="v-pixel" style={{ width: 76, height: "auto", flexShrink: 0, marginTop: -4 }} />
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 32, lineHeight: 1 }}>Veri<span style={{ color: "var(--v-teal-tint)" }}>tee</span></div>
            <p style={{ fontSize: 13.5, lineHeight: 1.6, margin: "12px 0 0", opacity: 0.86 }}>
              Hardware-rooted attestation, translated on-chain. An Input | Output protocol for the Midnight blockchain.
            </p>
          </div>
        </div>
        <div style={{ display: "flex", gap: 64, flexWrap: "wrap" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <span style={head}>Protocol</span>
            {tabLink("explorer", "Explorer")}
            {tabLink("status", "Status")}
            {tabLink("about", "What is Veritee")}
            {tabLink("team", "Team")}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <span style={head}>Resources</span>
            <a href={REPO_URL} className="v-footlink" style={link}>Repository</a>
            <a href="https://midnight.network" className="v-footlink" style={link}>Midnight</a>
            <a href="https://iog.io" className="v-footlink" style={link}>Input | Output</a>
          </div>
        </div>
      </div>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "18px 56px 36px", borderTop: "1px solid rgba(248,248,240,0.25)", position: "relative" }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, opacity: 0.6 }}>© 2026 Input Output · Veritee v0.2</span>
      </div>
    </footer>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  // Read the tab from the hash up front: the Explorer (a child, so its effects
  // run first) mirrors its own state into the hash on mount, which would wipe
  // a #status / #about deep link before an App-level effect could read it.
  const [tab, setTab] = useStateApp(() => {
    const raw = (window.location.hash || "").replace("#", "").split("/")[0];
    const h = LEGACY_TABS[raw] || raw;
    return ALL_TABS.includes(h) ? h : "explorer";
  });
  const go = (k) => { setTab(k); window.scrollTo(0, 0); };

  // Re-render when live data lands (data.jsx fetches the contract async).
  const [, bump] = useReducerApp((n) => n + 1, 0);
  useEffectApp(() => {
    window.addEventListener("veritee:data", bump);
    return () => window.removeEventListener("veritee:data", bump);
  }, []);

  // apply accent to CSS vars
  useEffectApp(() => {
    document.documentElement.style.setProperty("--tem-accent", t.accent);
    document.documentElement.style.setProperty("--v-teal", t.accent);
  }, [t.accent]);

  // Deep-link via hash. The first segment is the tab; the Explorer owns any
  // sub-path after it (#explorer/reg/<id>, #explorer/app/<key>) — so only
  // rewrite the hash when the tab itself actually changed, or a shared link's
  // sub-path would be wiped before the Explorer reads it.
  useEffectApp(() => {
    const cur = (window.location.hash || "").replace("#", "");
    if (cur === tab || cur.startsWith(tab + "/")) return;
    window.history.replaceState(null, "", "#" + tab);
  }, [tab]);

  return (
    <div style={{ minHeight: "100vh", background: "var(--v-canvas)" }} data-density={t.density}>
      {/* private-beta notice band */}
      <div style={{
        background: "var(--v-ink)", color: "var(--v-canvas)", padding: "7px 24px",
        fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.02em", lineHeight: 1.5,
        display: "flex", alignItems: "center", justifyContent: "center", gap: 10, textAlign: "center",
      }}>
        <PixelSquare size={8} color="var(--v-teal-tint)" />
        Veritee is live on-chain in private beta, with access limited to select customers.
      </div>
      <Nav tab={tab} go={go} />
      <main>
        {tab === "about" && (
          <>
            <Overview goExplorer={() => go("explorer")} docsUrl={REPO_URL} />
            <Guarantees goExplorer={() => go("explorer")} />
          </>
        )}
        {tab === "explorer" && <Explorer goStats={() => go("status")} />}
        {tab === "status" && <ProductionStats />}
        {tab === "team" && <Team repoUrl={REPO_URL} />}
      </main>
      <Footer go={go} dither={t.dither} />

      <TweaksPanel>
        <TweakSection label="Accent" />
        <TweakColor label="Veritee accent" value={t.accent}
          options={["#10A0A8", "#003058", "#C8383F", "#7C5CFF"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakSection label="Pixel accents" />
        <TweakToggle label="Footer dither" value={t.dither} onChange={(v) => setTweak("dither", v)} />
        <TweakSection label="Explorer" />
        <TweakRadio label="Density" value={t.density} options={["compact", "comfortable"]} onChange={(v) => setTweak("density", v)} />
      </TweaksPanel>
    </div>
  );
}

const temRoot = ReactDOM.createRoot(document.getElementById("root"));
setTimeout(() => temRoot.render(<App />), 60);
