/* ProTGen site — variations panel + app shell */

const TWEAK_DEFS = [
  { key: "hero", title: "Homepage hero", hint: "How the hero leads with “restore immune competence.”", opts: [
    ["constellation", "Repertoire constellation", "Sparse → ordered nodes beside the claim"],
    ["restoration", "Restoration gradient", "Centered claim over a depleted→activated field"],
    ["gate", "Signal gate", "The Notch aperture leads the eye"],
  ]},
  { key: "belief", title: "Belief‑sequence module", hint: "How the seven beliefs are presented.", opts: [
    ["ladder", "Proof ladder", "Numbered rows, full claim + proof tag"],
    ["spine", "Horizontal spine", "Compact connected sequence"],
    ["cards", "Stepped cards", "Grid of belief cards, one highlighted"],
  ]},
  { key: "mech", title: "Platform mechanism", hint: "How targeted Notch activation is shown.", opts: [
    ["gate", "Signal gate", "Depleted → gate opens → ordered"],
    ["thymic", "Thymic architecture", "Nested restorative curves"],
    ["beforeafter", "Before / after", "Depleted vs restored repertoire"],
  ]},
  { key: "order", title: "Homepage narrative order", hint: "Which belief leads the homepage flow.", opts: [
    ["problem", "Problem‑first", "Lead with the human + clinical gap"],
    ["category", "Category‑first", "Lead with the white‑space reframe"],
    ["program", "Program‑first", "Lead with ProT‑096 as the proof point"],
  ]},
];

const DEFAULT_TWEAKS = { hero: "constellation", belief: "ladder", mech: "gate", order: "problem" };
const TWEAK_KEYS = TWEAK_DEFS.map((g) => g.key);

/* Variation state lives in the URL (?hero=&belief=&mech=&order=) so a specific
   combination is shareable/bookmarkable on the live deployment, then falls back
   to this browser's last choice, then to defaults. */
function validVal(key, val) {
  const g = TWEAK_DEFS.find((d) => d.key === key);
  return g && val && g.opts.some((o) => o[0] === val);
}
function loadTweaks() {
  let stored = {};
  try { stored = JSON.parse(localStorage.getItem("protgen_tweaks") || "{}"); } catch (e) {}
  let url = {};
  try {
    const q = new URLSearchParams(window.location.search);
    TWEAK_KEYS.forEach((k) => { const v = q.get(k); if (validVal(k, v)) url[k] = v; });
  } catch (e) {}
  return { ...DEFAULT_TWEAKS, ...stored, ...url };
}
function writeTweakUrl(tweaks) {
  try {
    const q = new URLSearchParams(window.location.search);
    TWEAK_KEYS.forEach((k) => {
      if (tweaks[k] && tweaks[k] !== DEFAULT_TWEAKS[k]) q.set(k, tweaks[k]); else q.delete(k);
    });
    const qs = q.toString();
    const url = window.location.pathname + (qs ? "?" + qs : "") + (window.location.hash || "");
    window.history.replaceState(null, "", url);
  } catch (e) {}
}

function VariationsPanel({ tweaks, setTweak, reset, page }) {
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(false);
  const homeOnly = page !== "home";
  const copyLink = () => {
    try {
      navigator.clipboard.writeText(window.location.href);
      setCopied(true); setTimeout(() => setCopied(false), 1800);
    } catch (e) {}
  };
  return (
    <div className="vpanel">
      {open && (
        <div className="vbody">
          <div className="vpanel-head">
            <div>
              <div className="vtitle">Design variations</div>
              <div className="vsub">Mix &amp; match — saved as you go</div>
            </div>
            <button className="x" onClick={() => setOpen(false)} aria-label="Close">×</button>
          </div>
          {homeOnly && (
            <p className="vhint" style={{ background: "var(--bone-100)", border: "1px solid var(--bone-200)", borderRadius: 8, padding: "10px 12px", color: "var(--fg-2)" }}>
              These variations apply to the <b>homepage</b>. <button className="btn-link" style={{ fontSize: 12.5 }} onClick={() => go("home")}>Go to homepage →</button>
            </p>
          )}
          {TWEAK_DEFS.map((g) => (
            <div className="vgroup" key={g.key}>
              <h5>{g.title}</h5>
              <p className="vhint">{g.hint}</p>
              <div className="vseg">
                {g.opts.map(([val, name, desc]) => (
                  <button key={val} className={"vopt" + (tweaks[g.key] === val ? " active" : "")} onClick={() => setTweak(g.key, val)}>
                    <span className="vo-name">{name}</span>
                    <span className="vo-desc">{desc}</span>
                  </button>
                ))}
              </div>
            </div>
          ))}
          <button className="btn btn-primary btn-sm" style={{ width: "100%", justifyContent: "center", marginTop: 6 }} onClick={copyLink}>
            <Icon name={copied ? "check" : "arrow"} size={15} /> {copied ? "Link copied" : "Copy share link"}
          </button>
          <button className="btn btn-ghost btn-sm" style={{ width: "100%", justifyContent: "center", marginTop: 8 }} onClick={reset}>Reset to default</button>
          <p className="vhint" style={{ marginTop: 12, marginBottom: 0 }}>The link captures this exact combination — share it to show a specific direction.</p>
        </div>
      )}
      <button className="vtoggle" onClick={() => setOpen(!open)}>
        <Icon name="sliders" size={16} /> {open ? "Close" : "Variations"}
      </button>
    </div>
  );
}

function App() {
  const route = useRoute();
  const [modal, setModal] = React.useState(false);
  const [preset, setPreset] = React.useState(null);
  const [tweaks, setTweaks] = React.useState(loadTweaks);

  const setTweak = (k, v) => setTweaks((t) => {
    const n = { ...t, [k]: v };
    try { localStorage.setItem("protgen_tweaks", JSON.stringify(n)); } catch (e) {}
    writeTweakUrl(n);
    return n;
  });
  const reset = () => { setTweaks({ ...DEFAULT_TWEAKS }); try { localStorage.setItem("protgen_tweaks", JSON.stringify(DEFAULT_TWEAKS)); } catch (e) {} writeTweakUrl(DEFAULT_TWEAKS); };

  React.useEffect(() => { writeTweakUrl(tweaks); }, []);

  const openReq = (p) => { setPreset(p || null); setModal(true); };
  const segPreset = { Champion: "Internal champion", Clinical: "Investor", Category: "Investor", Partner: "Strategic partner" };
  const onDoorway = (k) => openReq(segPreset[k] || null);

  let pageEl;
  switch (route.page) {
    case "platform":  pageEl = <PlatformPage onRequest={() => openReq()} />; break;
    case "program":   pageEl = <ProgramPage onRequest={() => openReq("Investor")} />; break;
    case "investors": pageEl = <InvestorsPage onRequest={() => openReq("Investor")} onDoorway={onDoorway} />; break;
    case "about":     pageEl = <AboutPage onRequest={() => openReq()} />; break;
    case "resources": pageEl = <ResourcesPage onRequest={() => openReq()} />; break;
    case "article":   pageEl = <ArticlePage onRequest={() => openReq()} />; break;
    case "contact":   pageEl = <ContactPage />; break;
    default:          pageEl = <HomePage onRequest={() => openReq()} onDoorway={onDoorway} tweaks={tweaks} />;
  }

  return (
    <React.Fragment>
      <Header page={route.page} onRequest={() => openReq()} />
      <main>{pageEl}</main>
      <Footer onRequest={() => openReq()} />
      <RequestModal open={modal} onClose={() => setModal(false)} preset={preset} />
      <VariationsPanel tweaks={tweaks} setTweak={setTweak} reset={reset} page={route.page} />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
