/* App shell: routes between Landing → Profile → Thesis Lab → Ranked → Deep dive → Public.
   Owns the Tweaks panel and the active-profile / active-thesis / active-ticker state. */

const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "density": "comfortable",
  "cardStyle": "rich",
  "profileStyle": "hybrid",
  "deepDiveLayout": "tabs",
  "showSparkFill": true,
  "showCitationsInline": true
}/*EDITMODE-END*/;

function App() {
  // /t/<profile-slug>-<thesis-slug> is its own surface — render PublicThesisRoute
  // and short-circuit the SPA shell so cold visitors arriving from a shared link
  // see the thesis, not the in-app chrome.
  if (parsePublicSlug(window.location.pathname)) {
    return <PublicThesisRoute />;
  }

  // ?theme=<slug> wins over the default first-profile selection on boot, so
  // demo links can deep-link straight to a specific theme.
  const themeSlug = new URLSearchParams(window.location.search).get("theme");
  const requestedProfile = themeSlug ? dbq.profileBySlug(themeSlug) : null;
  const firstProfile = requestedProfile || dbq.allProfiles()[0];
  const initialThesis = dbq.thesesForProfile(firstProfile.id)[0];
  const initialCandidate = dbq.candidatesForThesis(initialThesis.id)[0];

  const [route, setRoute] = useStateApp("landing");
  const [activeProfileId, setActiveProfileId] = useStateApp(firstProfile.id);
  const [activeThesisId, setActiveThesisId] = useStateApp(initialThesis.id);
  const [activeTicker, setActiveTicker] = useStateApp(initialCandidate.ticker);
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffectApp(() => {
    document.documentElement.setAttribute("data-theme", tw.theme);
    document.documentElement.setAttribute("data-density", tw.density);
  }, [tw.theme, tw.density]);

  // Keep child selections valid when active profile changes; also keep the
  // URL ?theme= param in sync so the current state stays shareable.
  function switchProfile(profileId) {
    setActiveProfileId(profileId);
    const profile = dbq.profileById(profileId);
    if (profile) {
      const url = new URL(window.location.href);
      url.searchParams.set("theme", profile.slug);
      window.history.replaceState({}, "", url);
    }
    const t = dbq.thesesForProfile(profileId)[0];
    if (t) {
      setActiveThesisId(t.id);
      const c = dbq.candidatesForThesis(t.id)[0];
      if (c) setActiveTicker(c.ticker);
    }
  }

  const goRanked = (thesisId) => { setActiveThesisId(thesisId); setRoute("ranked"); };
  const goDeep = (ticker) => { setActiveTicker(ticker); setRoute("deep"); };

  return (
    <>
      <WipBanner />
      {route !== "landing" && route !== "deep" && (
        <TopBar
          crumbs={[
            route === "profile" && "01 profile",
            route === "lab" && "02 thesis lab",
            route === "ranked" && "03 ranked candidates",
            route === "data" && "data inspector",
          ].filter(Boolean)}
          onBack={
            route === "profile" ? () => setRoute("landing") :
            route === "lab" ? () => setRoute("profile") :
            route === "ranked" ? () => setRoute("lab") :
            route === "data" ? () => setRoute("landing") : null
          }
          center={
            <ProfileSwitcher
              profileId={activeProfileId}
              onChange={switchProfile}
            />
          }
          right={
            <button className="btn btn-sm" onClick={() => setRoute("landing")}>Restart</button>
          }
        />
      )}

      {route === "landing" && <Landing onLaunch={() => setRoute("profile")} profileId={activeProfileId} thesisId={activeThesisId} />}
      {route === "profile" && <ProfileScreen profileId={activeProfileId} onContinue={() => setRoute("lab")} profileStyle={tw.profileStyle} />}
      {route === "lab" && <ThesisLabScreen profileId={activeProfileId} onActivate={goRanked} onBack={() => setRoute("profile")} />}
      {route === "ranked" && <RankedScreen profileId={activeProfileId} thesisId={activeThesisId} onOpen={goDeep} cardStyle={tw.cardStyle} />}
      {route === "deep" && <DeepDiveScreen profileId={activeProfileId} thesisId={activeThesisId} ticker={activeTicker} onBack={() => setRoute("ranked")} layout={tw.deepDiveLayout} />}
      {route === "data" && <DataInspectorScreen />}

      <RouteBar route={route} setRoute={setRoute} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Appearance" />
        <TweakRadio label="Theme" value={tw.theme} options={["light", "dark"]} onChange={(v) => setTweak("theme", v)} />
        <TweakRadio label="Density" value={tw.density} options={["compact", "comfortable"]} onChange={(v) => setTweak("density", v)} />

        <TweakSection label="Profile screen" />
        <TweakRadio label="Layout" value={tw.profileStyle} options={["form", "hybrid", "chat"]} onChange={(v) => setTweak("profileStyle", v)} />

        <TweakSection label="Ranked candidates" />
        <TweakRadio label="Card style" value={tw.cardStyle} options={["rich", "editorial", "table"]} onChange={(v) => setTweak("cardStyle", v === "table" ? "compact" : v)} />

        <TweakSection label="Deep dive" />
        <TweakRadio label="Layout" value={tw.deepDiveLayout} options={["tabs", "scroll"]} onChange={(v) => setTweak("deepDiveLayout", v)} />

        <TweakSection label="Surprises" />
        <TweakToggle label="Inline citation pills" value={tw.showCitationsInline} onChange={(v) => setTweak("showCitationsInline", v)} />
        <TweakToggle label="Sparkline fill" value={tw.showSparkFill} onChange={(v) => setTweak("showSparkFill", v)} />
      </TweaksPanel>
    </>
  );
}

/* WipBanner is defined in ui.jsx so the public route can use it too. */

function ProfileSwitcher({ profileId, onChange }) {
  const profiles = dbq.allProfiles();
  if (profiles.length <= 1) return null;
  const idx = profiles.findIndex((p) => p.id === profileId);
  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 10,
        padding: "6px 6px 6px 14px",
        background: "var(--surface)",
        border: "1.5px solid var(--accent, var(--ink-2))",
        borderRadius: 999,
        boxShadow: "0 2px 10px rgba(0,0,0,0.06)",
      }}
    >
      <span
        className="mono"
        style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.12em" }}
      >
        Demo theme
      </span>
      <span
        className="mono"
        style={{ fontSize: 10, color: "var(--ink-4)" }}
      >
        {idx + 1}/{profiles.length}
      </span>
      <div style={{ position: "relative", display: "inline-flex", alignItems: "center" }}>
        <select
          value={profileId}
          onChange={(e) => onChange(e.target.value)}
          style={{
            appearance: "none",
            WebkitAppearance: "none",
            fontSize: 13,
            fontWeight: 600,
            padding: "8px 32px 8px 14px",
            border: "none",
            borderRadius: 999,
            background: "var(--accent, var(--ink))",
            color: "var(--bg)",
            cursor: "pointer",
            fontFamily: "var(--font-sans)",
            minWidth: 220,
          }}
        >
          {profiles.map((p) => (
            <option key={p.id} value={p.id}>{p.theme}</option>
          ))}
        </select>
        <span
          aria-hidden="true"
          style={{
            position: "absolute",
            right: 12,
            pointerEvents: "none",
            color: "var(--bg)",
            display: "flex",
          }}
        >
          <Icon name="caret" size={14} />
        </span>
      </div>
    </div>
  );
}

function RouteBar({ route, setRoute }) {
  const items = [
    ["landing", "Landing"],
    ["profile", "Profile"],
    ["lab", "Lab"],
    ["ranked", "Ranked"],
    ["deep", "Deep"],
    ["data", "Data"],
  ];
  return (
    <div style={{
      position: "fixed",
      bottom: 16, left: "50%", transform: "translateX(-50%)",
      display: "flex", gap: 4, padding: 4,
      background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 999,
      boxShadow: "0 6px 24px rgba(0,0,0,0.06)",
      zIndex: 50,
    }}>
      {items.map(([id, label]) => (
        <button
          key={id}
          onClick={() => setRoute(id)}
          className={"btn btn-sm " + (route === id ? "btn-primary" : "btn-ghost")}
          style={{ borderRadius: 999, padding: "5px 12px", border: "none" }}
        >
          {label}
        </button>
      ))}
    </div>
  );
}

function Boot() {
  const [ready, setReady] = useStateApp(false);
  const [error, setError] = useStateApp(null);
  useEffectApp(() => {
    window.DATA_READY.then(() => setReady(true)).catch((e) => setError(e));
  }, []);
  if (error) {
    return (
      <div style={{ padding: 40, fontFamily: "var(--font-sans)", color: "var(--neg, #c33)" }}>
        Failed to load data: {String(error.message || error)}
      </div>
    );
  }
  if (!ready) {
    return (
      <div style={{ padding: 40, fontFamily: "var(--font-sans)", color: "var(--ink-2, #888)" }}>
        Loading…
      </div>
    );
  }
  return <App />;
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Boot />);
