/* global React, DemixViz */
const { Eyebrow, GradientText, Button, Chip, Card, ClaimCeiling } = window.OregonCoastAIDesignSystem_e04d97;

const HERO_COPY = {
  problem: {
    eyebrow: "Cohort de-mixing · fibromyalgia molecular phenotyping",
    head: ["See the subgroups your trial is ", "averaging away", "."],
    lede: "A clinically labeled fibromyalgia cohort is rarely one biology. When distinct molecular states are pooled, a real treatment effect is diluted toward the mean — and a working drug can read as a near-miss. We sort the cohort first.",
  },
  method: {
    eyebrow: "Cohort de-mixing · spectral-entropy phenotyping",
    head: ["De-mix the cohort. ", "Recover the signal", "."],
    lede: "Trace-normalized local-covariance spectral entropy resolves a pooled blood-derived cohort into coarse molecular-state classes — with explicit abstention where the data won't support a call. The structure was always there; we make it legible.",
  },
  provocation: {
    eyebrow: "Cohort de-mixing · fibromyalgia molecular phenotyping",
    head: ["Fibromyalgia isn't one disease. Stop ", "analyzing it like one", "."],
    lede: "Pooling biologically distinct patients inflates trial noise and blurs the very subgroup your therapy serves best. We resolve the molecular states inside an already-diagnosed cohort — methods-only, evidence-bound, hypothesis-generating.",
  },
};

function ReadoutStrip({ r }) {
  const Metric = window.OCAMetric;
  if (!r) return null;
  return (
    <div className="readout-strip" style={{ display: "flex", gap: "26px", flexWrap: "wrap", padding: "16px 0 0", borderTop: "1px solid var(--border-line)", marginTop: "16px" }}>
      <Metric label="Apparent classes" value={r.classes} sub={r.demixed ? "resolved" : "resolving…"} color={r.demixed ? "var(--text-accent)" : "var(--text-strong)"} />
      <Metric label="Mean H_S" value={r.entropy.toFixed(3)} unit="nats" sub="local-cov spectral entropy" />
      <Metric label="Responder Δ" value={r.effect.toFixed(2)} unit="d" sub={r.demixed ? "de-mixed subgroup" : "pooled / ITT"} color={r.effect > 0.6 ? "var(--success)" : "var(--text-strong)"} />
      <Metric label="Abstained" value={r.abstain} sub="routed to review" color="var(--warning)" />
    </div>
  );
}

function HomeScreen({ onNav, heroVariant = "problem", vizStyle = "ellipsoid", onRequestDemo }) {
  const Section = window.OCASection, Wrap = window.OCAWrap, Kicker = window.OCAKicker, SH = window.OCASH, Sub = window.OCASub, Pipeline = window.OCAPipeline, VizLegend = window.OCAVizLegend;
  const [r, setR] = React.useState(null);
  const copy = HERO_COPY[heroVariant] || HERO_COPY.problem;

  const problems = [
    ["Diluted effect sizes", "Mixing responders with non-responders pulls the group mean toward placebo. A genuine effect in one subgroup looks marginal across the whole arm."],
    ["False-negative risk", "Heterogeneity is a leading cause of underpowered, ambiguous readouts — the inadvertent shelving of a compound that in fact works in a definable subset."],
    ["Unstable interpretation", "Without a molecular lens, post-hoc subgroups look like fishing. Pre-registered, structure-aware classes are defensible to reviewers and regulators."],
  ];
  const method = [
    ["Structured spectral state", "Each blood-derived record becomes a per-sample local covariance operator in the n≪p regime — geometry, not a single score."],
    ["Verification gate", "Symmetry, positive-semidefiniteness, and positive-trace are checked before any readout. Records that fail the gate abstain rather than guess."],
    ["Registry-routed reporting", "A cohort-type-conditional layer compares against a platform-matched healthy-control reference and emits a class — or a low-confidence / abstain flag."],
  ];

  return (
    <div>
      {/* ---------------- HERO ---------------- */}
      <header style={{ padding: "44px 0 8px" }}>
        <Wrap wide>
          <div className="hero-grid">
            <div>
              <Eyebrow>{copy.eyebrow}</Eyebrow>
              <h1 style={{ fontSize: "clamp(30px,4.4vw,50px)", lineHeight: 1.1, margin: "16px 0 18px", fontWeight: 700, maxWidth: "16ch", color: "var(--text-strong)", textWrap: "balance" }}>
                {copy.head[0]}<GradientText>{copy.head[1]}</GradientText>{copy.head[2]}
              </h1>
              <p style={{ fontSize: "clamp(16px,1.6vw,19px)", color: "var(--text-body)", maxWidth: "52ch", margin: 0, lineHeight: 1.62 }}>{copy.lede}</p>
              <div style={{ display: "flex", gap: "12px", marginTop: "26px", flexWrap: "wrap" }}>
                <Button size="lg" onClick={onRequestDemo}>Request demo access</Button>
                <Button size="lg" variant="secondary" onClick={() => onNav("service")}>How it works</Button>
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: "8px", marginTop: "24px" }}>
                {["Methods-only", "Evidence-bound", "Versioned artifacts", "Abstain discipline", "Grant-ready"].map((c) => <Chip key={c}>{c}</Chip>)}
              </div>
            </div>

            {/* viz panel */}
            <div style={{ background: "var(--bg-panel-gradient)", border: "1px solid var(--border-line)", borderRadius: "var(--radius-lg)", padding: "16px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "10px" }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", letterSpacing: "0.06em", color: "var(--text-muted)" }}>SPECTRAL-COVARIANCE STATE SPACE · 2-D PROJECTION</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: "10px", color: r && r.demixed ? "var(--success)" : "var(--text-accent)" }}>{r && r.demixed ? "● de-mixed" : "○ de-mixing"}</span>
              </div>
              <DemixViz vizStyle={vizStyle} auto height={330} onReadout={setR} seed={11} />
              <div style={{ marginTop: "12px" }}><VizLegend compact /></div>
              <ReadoutStrip r={r} />
              <div style={{ margin: "14px 0 0" }}><ClaimCeiling>Illustrative synthetic cohort · not trial data · figures animate to demonstrate method behavior, not a clinical result.</ClaimCeiling></div>
            </div>
          </div>
        </Wrap>
      </header>

      {/* ---------------- THE PROBLEM ---------------- */}
      <Section wide id="problem">
        <Kicker>The technical problem</Kicker>
        <SH>One label, several biologies</SH>
        <Sub>Fibromyalgia is often treated as a single condition with one dominant biology. In practice that simplification is expensive: a labeled cohort can carry biologically distinct states whose mixing increases trial noise and blurs the subgroups that matter.</Sub>
        <div className="cards-3">
          {problems.map(([t, d]) => (
            <Card key={t} title={t}>{d}</Card>
          ))}
        </div>
        <p style={{ marginTop: "26px", fontSize: "17px", color: "var(--text-body)", fontStyle: "italic", maxWidth: "62ch", lineHeight: 1.6 }}>
          The first practical need isn't a universal diagnostic — it's a more informative molecular lens that sorts an already-diagnosed cohort into more coherent groupings.
        </p>
      </Section>

      {/* ---------------- THE METHOD ---------------- */}
      <Section wide id="method">
        <Kicker>The method</Kicker>
        <SH>De-mixing, gated at every step</SH>
        <Sub>The engine is a registered composition — not a generic classifier. It reports only under verification, calibration, and abstention controls, so what it emits is defensible.</Sub>
        <div style={{ background: "var(--surface-inset)", border: "1px solid var(--border-line)", borderRadius: "var(--radius-lg)", padding: "20px 22px", marginBottom: "20px" }}>
          <Pipeline steps={["harmonize record", "local covariance Cⱼ", "trace-normalize ρⱼ", "verification gate", "spectral entropy H_S", "registry route", "class · low-confidence · abstain"]} />
        </div>
        <div className="cards-3">
          {method.map(([t, d]) => (
            <Card key={t} title={t}>{d}</Card>
          ))}
        </div>
        <div style={{ margin: "22px 0 0" }}><ClaimCeiling>Outputs support cohort de-mixing, stratification, transfer assessment, and study design — each carrying a hypothesis-generating-status flag. Not a diagnosis, severity, or therapy-selection claim.</ClaimCeiling></div>
      </Section>
    </div>
  );
}

window.HomeScreen = HomeScreen;
window.HERO_COPY = HERO_COPY;
