// SAT Results Report - page assembly
// Ported from the design bundle (report-app.jsx) and wired to live data.
// Reads globals REPORT, TESTS, EXAM, TARGET_SCORE, set by data-report.jsx.
// Two edits from the mock version:
//   1. TopicBreakdown reads sub.note (server-selected) instead of TOPIC_NOTES[sub.name].
//   2. RecommendedPlan reads sec.nextSteps (server-built) instead of a hardcoded list.
const { useState: useStateApp } = React;

const TAG_META = {
  weak:     { label: "Weak Area",     color: "var(--error)", tint: "#FBD9D6", desc: "Wrong even on easy items, so fundamentals need rebuilding" },
  depth:    { label: "Lack of Depth", color: "#C98A1E",      tint: "#FBEFCF", desc: "Easy items fine, but missing on the harder questions" },
  solid:    { label: "Solid",         color: "#5C7E3F",      tint: "#E4EFD6", desc: "Tested with no misses" },
  untested: { label: "Not tested",    color: "#7CA158",      tint: "#EDF1DD", desc: "Not assessed on this test" },
};
const WP_META = { label: "Word Problems", color: "#2E6B8A", tint: "#DCE9F1", desc: "Misses cluster on the word-problem versions of this skill" };

function Card({ children, pad = 24, style, className }) {
  return <div className={className} style={{ background: "var(--white)", border: "1px solid var(--sage-l)", borderRadius: 18, padding: pad, ...style }}>{children}</div>;
}
function SecHead({ eyebrow, title, sub, right }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginBottom: 16, flexWrap: "wrap" }}>
      <div>
        {eyebrow && <div style={{ fontFamily: "var(--fp)", fontSize: "0.7rem", letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--sage)", marginBottom: 5 }}>{eyebrow}</div>}
        <h2 style={{ fontFamily: "var(--fh)", color: "var(--forest)", fontSize: "1.5rem", margin: 0, lineHeight: 1.1 }}>{title}</h2>
        {sub && <div style={{ fontFamily: "var(--fp)", fontSize: "0.84rem", color: "var(--muted)", marginTop: 5 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// ─── 1 · Snapshot hero (V1 warm story style) ───
function SnapshotHero() {
  // All live, from the /exam/report payload. No mock values.
  const rw = REPORT.rw, math = REPORT.math;
  const comp = REPORT.composite || { score: rw.scoreMid + math.scoreMid, percentile: null };
  const tests = (typeof TESTS !== "undefined" && TESTS) || [];
  const prev = tests.length >= 2 ? tests[tests.length - 2] : null;
  const growth = prev ? comp.score - prev.med : null;
  const target = (typeof TARGET_SCORE !== "undefined" && TARGET_SCORE) || null;
  const vsTarget = target != null ? comp.score - target : null;
  const totalLow = (rw.low != null && math.low != null) ? rw.low + math.low : null;
  const totalHigh = (rw.high != null && math.high != null) ? rw.high + math.high : null;
  const name = REPORT.studentName || null;
  const signed = (n) => (n > 0 ? "+" + n : n < 0 ? "−" + Math.abs(n) : "0");
  return (
    <Card pad={32} style={{ position: "relative", overflow: "hidden", borderRadius: 22 }}>
      <div style={{ position: "absolute", top: -50, right: -40, width: 300, height: 300, borderRadius: "50%", background: "var(--sage-m)", opacity: 0.45 }} />
      <div style={{ position: "absolute", bottom: -70, right: 120, width: 180, height: 180, borderRadius: "50%", background: "var(--sage-l)", opacity: 0.3 }} />
      <div style={{ position: "relative" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", flexWrap: "wrap", gap: 16 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              <span style={{ fontFamily: "var(--fp)", fontSize: "0.66rem", fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "#fff", background: "var(--forest)", padding: "4px 11px", borderRadius: 99 }}>{EXAM.typeLabel}</span>
              <span style={{ fontFamily: "var(--fp)", fontSize: "0.78rem", color: "var(--slate)" }}>{EXAM.sessionLabel} · completed</span>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 8, flexWrap: "wrap" }}>
              <span style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--fp)", fontSize: "0.74rem", color: "var(--muted)" }}>
                <span style={{ letterSpacing: "0.06em", textTransform: "uppercase", fontSize: "0.62rem" }}>Date taken</span>
                <b style={{ color: "var(--forest)", fontWeight: 600 }}>{EXAM.dateTaken}</b>
              </span>
              <span style={{ width: 1, height: 12, background: "var(--sage-l)" }} />
              <span style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--fp)", fontSize: "0.74rem", color: "var(--muted)" }}>
                <span style={{ letterSpacing: "0.06em", textTransform: "uppercase", fontSize: "0.62rem" }}>Exam ID</span>
                <b style={{ fontFamily: "var(--fb)", color: "var(--forest)", fontWeight: 600, letterSpacing: "0.04em", fontVariantNumeric: "tabular-nums" }}>{EXAM.id}</b>
              </span>
            </div>
            <div style={{ fontFamily: "var(--fh)", color: "var(--forest)", fontSize: "2rem", marginTop: 14, lineHeight: 1.12, maxWidth: 460 }}>
              {growth != null && growth > 0
                ? <span>Nice work{name ? ", " + name : ""}. You grew <span style={{ borderBottom: "3px solid var(--sage)" }}>~{growth} points</span> since your last test.</span>
                : <span>Here is your score report{name ? ", " + name : ""}.</span>}
            </div>
          </div>
          <div className="rep-actions" style={{ display: "flex", gap: 10 }}>
            <button className="rep-btn rep-btn-primary" disabled title="Emailed reports are coming soon" style={{ opacity: 0.55, cursor: "default" }}>Email me my results (soon)</button>
            <button className="rep-btn rep-btn-ghost" onClick={() => window.print()}>Export as PDF</button>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "auto 1px 1fr", alignItems: "center", gap: 36, marginTop: 26 }}>
          <div>
            <div style={{ fontFamily: "var(--fh)", color: "var(--forest)", fontSize: "4.4rem", lineHeight: 0.85, letterSpacing: "-0.03em", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>{totalLow != null ? totalLow : comp.score}<span style={{ color: "var(--sage)", fontSize: "2.8rem", margin: "0 6px" }}>–</span>{totalHigh != null ? totalHigh : comp.score}</div>
            <div style={{ fontFamily: "var(--fp)", fontSize: "0.82rem", color: "var(--muted)", marginTop: 8 }}>Total score range · median <b style={{ color: "var(--forest)" }}>{comp.score}</b> / 1600</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0, marginTop: 16, borderTop: "1px dashed var(--sage-l)", paddingTop: 14 }}>
              <HeroRange name="Reading & Writing" range={rw.scoreRange} mid={rw.scoreMid} />
              <HeroRange name="Math" range={math.scoreRange} mid={math.scoreMid} border />
            </div>
          </div>
          <div style={{ width: 1, height: 150, background: "var(--sage-l)" }} />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }}>
            {growth != null && <HeroStat label="vs last test" value={signed(growth)} tone={growth >= 0 ? "up" : undefined} />}
            {vsTarget != null && <HeroStat label={"vs Target (" + target + ")"} value={signed(vsTarget)} tone={vsTarget >= 0 ? "up" : undefined} />}
            {comp.percentile != null && <HeroStat label="Percentile" value={Math.round(comp.percentile) + "th"} />}
          </div>
        </div>
      </div>
    </Card>
  );
}
function HeroRange({ name, range, mid, border }) {
  return (
    <div style={{ paddingLeft: border ? 18 : 0, marginLeft: border ? 18 : 0, borderLeft: border ? "1px dashed var(--sage-l)" : "none" }}>
      <div style={{ fontFamily: "var(--fp)", fontSize: "0.64rem", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)" }}>{name}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 5, marginTop: 4 }}>
        <span style={{ fontFamily: "var(--fh)", color: "var(--forest)", fontSize: "1.45rem", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{range}</span>
        <span style={{ fontFamily: "var(--fb)", color: "var(--muted)", fontSize: "0.7rem" }}>/ 800</span>
      </div>
      <div style={{ fontFamily: "var(--fp)", fontSize: "0.7rem", color: "var(--muted)", marginTop: 3 }}>median <b style={{ color: "var(--forest)" }}>{mid}</b></div>
    </div>
  );
}
function HeroStat({ label, value, tone }) {
  return (
    <div>
      <div style={{ fontFamily: "var(--fp)", fontSize: "0.68rem", color: "var(--muted)", letterSpacing: "0.05em", textTransform: "uppercase" }}>{label}</div>
      <div style={{ fontFamily: "var(--fh)", color: tone === "up" ? "var(--success)" : "var(--forest)", fontSize: "1.5rem", marginTop: 3, fontVariantNumeric: "tabular-nums" }}>{value}</div>
    </div>
  );
}

// ─── Panel frame inside the 2×2 grid ───
function GridPanel({ title, sub, children, style }) {
  return (
    <div style={{ padding: 20, ...style }}>
      <div style={{ marginBottom: 14 }}>
        <h4 style={{ fontFamily: "var(--fh)", color: "var(--forest)", fontSize: "1rem", margin: 0 }}>{title}</h4>
        {sub && <div style={{ fontFamily: "var(--fp)", fontSize: "0.74rem", color: "var(--muted)", marginTop: 2 }}>{sub}</div>}
      </div>
      {children}
    </div>
  );
}

// ─── In-depth topic breakdown (respects active section) ───
function TopicBreakdown({ sec }) {
  const [open, setOpen] = useStateApp(() => new Set(sec.topics.filter(t => t.tag === "weak" || t.tag === "depth").map(t => t.name)));
  const toggle = (n) => { const s = new Set(open); s.has(n) ? s.delete(n) : s.add(n); setOpen(s); };
  // sort: weak → depth → solid → untested
  const rank = { weak: 0, depth: 1, solid: 2, untested: 3 };
  const doms = [...sec.topics].sort((a, b) => rank[a.tag] - rank[b.tag]);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "6px 18px", marginBottom: 4, padding: "12px 14px", background: "var(--white)", border: "1px solid var(--sage-l)", borderRadius: 10 }}>
        {["weak", "depth"].map(k => <LegendRow key={k} m={TAG_META[k]} />)}
        <LegendRow m={WP_META} />
        {["solid", "untested"].map(k => <LegendRow key={k} m={TAG_META[k]} />)}
      </div>
      {doms.map((dom, i) => {
        const isOpen = open.has(dom.name);
        const m = TAG_META[dom.tag];
        return (
          <div key={i} style={{ border: "1px solid var(--sage-l)", borderRadius: 12, overflow: "hidden", background: "#FBFCF6" }}>
            <button onClick={() => toggle(dom.name)} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 14, alignItems: "center", width: "100%", padding: "14px 16px", background: "transparent", border: "none", borderLeft: `4px solid ${m.color}`, textAlign: "left", cursor: "pointer" }}>
              <span style={{ color: "var(--slate)", transform: isOpen ? "rotate(90deg)" : "none", transition: "transform .15s", fontFamily: "var(--fb)", fontSize: "1rem" }}>›</span>
              <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <span style={{ fontFamily: "var(--fh)", color: "var(--forest)", fontSize: "1.05rem" }}>{dom.name}</span>
                {dom.tag !== "solid" && dom.tag !== "untested" && <Tag tag={dom.tag} />}
                {dom.wp && <Tag wp />}
                <span style={{ fontFamily: "var(--fp)", fontSize: "0.72rem", color: "var(--muted)" }}>{dom.cor} / {dom.tot} correct</span>
              </div>
              {dom.pct != null ? <AccMini v={dom.pct} tag={dom.tag} /> : <span style={{ fontFamily: "var(--fp)", fontSize: "0.72rem", color: "var(--muted)" }}>—</span>}
              <span style={{ fontFamily: "var(--fp)", fontSize: "0.72rem", color: "var(--sage)" }}>{dom.subs.length} topics</span>
            </button>
            {isOpen && (
              <div style={{ padding: "4px 16px 16px 34px", background: "var(--white)", borderTop: "1px dashed var(--sage-l)" }}>
                {dom.subs.map((sub, j) => {
                  const note = sub.tot > 0 ? sub.note : null;
                  const untested = sub.tag === "untested";
                  return (
                    <div key={j} style={{ padding: "11px 0", borderBottom: j < dom.subs.length - 1 ? "1px dashed var(--sage-l)" : "none", opacity: untested ? 0.6 : 1 }}>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 12, alignItems: "center" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap" }}>
                          <span style={{ width: 6, height: 6, borderRadius: "50%", background: TAG_META[sub.tag].color }} />
                          <span style={{ fontFamily: "var(--fb)", fontSize: "0.88rem", color: "var(--forest)" }}>{sub.name}</span>
                          {sub.tag !== "solid" && sub.tag !== "untested" && <Tag tag={sub.tag} small />}
                          {sub.wp && sub.tag !== "solid" && sub.tag !== "untested" && <Tag wp small />}
                          {untested
                            ? <span style={{ fontFamily: "var(--fp)", fontSize: "0.66rem", color: "var(--muted)", fontStyle: "italic" }}>not on this test</span>
                            : <span style={{ fontFamily: "var(--fp)", fontSize: "0.68rem", color: "var(--muted)" }}>{sub.cor} / {sub.tot}</span>}
                          {!untested && (
                            <span style={{ display: "flex", gap: 4, marginLeft: 2 }}>
                              {sub.byDiff.filter(d => d.n > 0).map(d => (
                                <span key={d.d} title={`${d.label}: ${d.n - d.wrong}/${d.n}`} style={{ fontFamily: "var(--fp)", fontSize: "0.58rem", fontWeight: 700, color: d.wrong > 0 ? "#fff" : "var(--slate)", background: d.wrong > 0 ? (d.d === "E" ? "var(--error)" : d.d === "M" ? "#E0A82E" : "#E07A2E") : "var(--sage-l)", padding: "1px 5px", borderRadius: 4 }}>{d.d}{d.wrong > 0 ? `−${d.wrong}` : ""}</span>
                              ))}
                            </span>
                          )}
                        </div>
                        {sub.pct != null ? <AccMini v={sub.pct} tag={sub.tag} w={44} /> : <span style={{ fontFamily: "var(--fp)", fontSize: "0.7rem", color: "var(--muted)" }}>—</span>}
                      </div>
                      {note && (
                        <div style={{ display: "flex", gap: 8, marginTop: 7 }}>
                          <span style={{ width: 3, background: sub.wp ? WP_META.color : "var(--sage)", borderRadius: 2, flexShrink: 0 }} />
                          <p style={{ fontFamily: "var(--fb)", fontSize: "0.78rem", lineHeight: 1.5, color: "var(--slate)", margin: 0 }}><span style={{ fontFamily: "var(--fp)", fontWeight: 700, color: "var(--forest)", fontSize: "0.66rem", letterSpacing: "0.04em", marginRight: 6 }}>SRUTHI</span>{note}</p>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}
function Tag({ tag, wp, small }) {
  const m = wp ? WP_META : TAG_META[tag];
  return <span style={{ fontFamily: "var(--fp)", fontSize: small ? "0.58rem" : "0.62rem", fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: m.color, background: m.tint, padding: small ? "1px 7px" : "2px 9px", borderRadius: 99, whiteSpace: "nowrap" }}>{m.label}</span>;
}
function LegendRow({ m }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <span style={{ flexShrink: 0, fontFamily: "var(--fp)", fontSize: "0.6rem", fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: m.color, background: m.tint, padding: "2px 8px", borderRadius: 99 }}>{m.label}</span>
      <span style={{ fontFamily: "var(--fp)", fontSize: "0.72rem", color: "var(--muted)" }}>{m.desc}</span>
    </div>
  );
}
function AccMini({ v, tag, w = 64 }) {
  const c = TAG_META[tag].color;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div style={{ width: w, height: 5, background: "var(--sage-l)", borderRadius: 99, overflow: "hidden" }}><div style={{ width: `${v}%`, height: "100%", background: c }} /></div>
      <span style={{ fontFamily: "var(--fb)", fontSize: "0.82rem", color: c, minWidth: 34, textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{v}%</span>
    </div>
  );
}

// Next Steps - top priority items from the server
function RecommendedPlan({ sec }) {
  const tintFor = (c) => c === "var(--error)" ? "#FBD9D6" : c === "#C98A1E" ? "#FBEFCF" : "#DCE9F1";
  // The server sends { t, tag, why }; the accent color is derived from the tag here
  // (presentation), so the payload stays free of styling.
  const colorFor = (tag) => tag === "Weak Area" ? "var(--error)" : tag === "Lack of Depth" ? "#C98A1E" : tag === "Word Problems" ? WP_META.color : "#6FA5DE";
  const items = (sec.nextSteps || []).map((a) => Object.assign({ c: colorFor(a.tag) }, a));
  return (
    <Card pad={26} style={{ background: "#FAFBF1" }}>
      <SecHead title="Next Steps" sub="Top priority items to maximize your score" />
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map((a, i) => (
          <div key={i} style={{ display: "flex", gap: 14, alignItems: "flex-start", padding: "15px 18px", background: "var(--white)", border: "1px solid var(--sage-l)", borderLeft: `3px solid ${a.c}`, borderRadius: 12 }}>
            <span style={{ flexShrink: 0, width: 26, height: 26, borderRadius: 8, background: "var(--sage-m)", color: "var(--forest)", fontFamily: "var(--fh)", fontSize: "0.9rem", display: "grid", placeItems: "center" }}>{i + 1}</span>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <span style={{ fontFamily: "var(--fh)", fontSize: "1.02rem", color: "var(--forest)", lineHeight: 1.2 }}>{a.t}</span>
                <span style={{ fontFamily: "var(--fp)", fontSize: "0.58rem", fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: a.c, background: tintFor(a.c), padding: "2px 8px", borderRadius: 99, whiteSpace: "nowrap" }}>{a.tag}</span>
              </div>
              <p style={{ fontFamily: "var(--fb)", fontSize: "0.82rem", lineHeight: 1.5, color: "var(--slate)", margin: "6px 0 0" }}>{a.why}</p>
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

// ─── Services / packages ───
function Services() {
  const pkgs = [
    { name: "1-on-1 Targeted Sessions", price: "from $40/hr", best: false, desc: "Live work on your exact weak areas, covering trig setup, quadratic graphing and pacing.", points: ["Personalized to this report", "Flexible weekly scheduling", "Homework + review built in"] },
    { name: "Test-Prep Sprint", price: "Coming soon", best: true, desc: "A structured plan focused on the exact weak areas in this report, in the weeks before your next official test.", points: ["2 sessions / week", "Full practice test every 2 weeks", "A report like this one each time", "Parent progress updates"] },
    { name: "Self-Study + Drill Library", price: "Coming soon", best: false, desc: "Targeted question sets for every topic flagged here, with worked solutions.", points: ["Weak-area drill sets", "Pacing trainer", "Cancel anytime"] },
  ];
  return (
    <Card className="rep-offerings" pad={28} style={{ background: "linear-gradient(135deg, #F4F7EC, #EAF0DC)" }}>
      <SecHead eyebrow="How LearningWithSruthi can help" title="Recommended for you" sub="Recommended offerings based on your score and progress." />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
        {pkgs.map((p, i) => (
          <div key={i} style={{ position: "relative", background: "var(--white)", border: `1.5px solid ${p.best ? "var(--sage)" : "var(--sage-l)"}`, borderRadius: 14, padding: 20, display: "flex", flexDirection: "column", boxShadow: p.best ? "0 8px 24px rgba(123,161,88,.18)" : "none" }}>
            {p.best && <span style={{ position: "absolute", top: -11, left: 20, background: "var(--forest)", color: "#fff", fontFamily: "var(--fp)", fontSize: "0.62rem", fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", padding: "3px 10px", borderRadius: 99 }}>Best match</span>}
            <div style={{ fontFamily: "var(--fh)", color: "var(--forest)", fontSize: "1.1rem" }}>{p.name}</div>
            <div style={{ fontFamily: "var(--fp)", fontSize: "0.84rem", color: "var(--sage)", fontWeight: 600, marginTop: 3 }}>{p.price}</div>
            <p style={{ fontFamily: "var(--fb)", fontSize: "0.8rem", lineHeight: 1.5, color: "var(--slate)", margin: "10px 0 12px" }}>{p.desc}</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 16 }}>
              {p.points.map((pt, j) => (
                <div key={j} style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
                  <span style={{ color: "var(--sage)", fontSize: "0.8rem", marginTop: 1 }}>✓</span>
                  <span style={{ fontFamily: "var(--fp)", fontSize: "0.78rem", color: "var(--ink)" }}>{pt}</span>
                </div>
              ))}
            </div>
            <button className={`rep-btn ${p.best ? "rep-btn-primary" : "rep-btn-ghost"}`} style={{ marginTop: "auto", width: "100%", justifyContent: "center" }}>{p.best ? "Start the sprint" : "Learn more"}</button>
          </div>
        ))}
      </div>
    </Card>
  );
}

// ─── Root ───
function ReportApp() {
  const [tab, setTab] = useStateApp("math");
  const sec = REPORT[tab];
  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: "32px 24px 64px", display: "flex", flexDirection: "column", gap: 22 }}>
      <SnapshotHero />

      {/* Cohort compare near top. Only shown once there is a real cohort: the
          distribution and percentile are computed from cohortMid/cohortSd, which are
          null until enough students have taken this test. We never fabricate a peer
          group, so below the threshold this renders an honest placeholder. */}
      <Card>
        <SecHead title="Where you Stand" sub={REPORT.cohortReady ? `Your score vs. other students aiming for ${TARGET_SCORE}` : "Comparison to other students"} />
        {REPORT.cohortReady && REPORT.rw.cohortMid != null && REPORT.math.cohortMid != null ? (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
            <CohortDistribution sec={REPORT.rw} />
            <CohortDistribution sec={REPORT.math} />
          </div>
        ) : (
          <p style={{ fontFamily: "var(--fb)", fontSize: "0.88rem", lineHeight: 1.5, color: "var(--slate)", margin: 0 }}>
            Not enough students have taken this exam yet to show a reliable comparison. Your percentile against other test-takers will appear here once the group is large enough.
          </p>
        )}
      </Card>

      {/* Trajectory */}
      <Card>
        <SecHead title="Score Trajectory" sub="Your score progression on your SAT journey." right={<TrajLegend />} />
        <Trajectory tests={TESTS} target={TARGET_SCORE} />
      </Card>

      {/* Tabbed deep-dive */}
      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ padding: "22px 24px 0" }}>
          <SecHead title="Section Deep-Dive" sub="Break down by time, difficulty and confidence to fully understand your score" right={
            <div className="rep-tabs">
              {["rw", "math"].map(k => (
                <button key={k} onClick={() => setTab(k)} className={`rep-tab ${tab === k ? "active" : ""}`}>{REPORT[k].name}</button>
              ))}
            </div>
          } />
        </div>
        {/* stat strip */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, padding: "4px 24px 20px" }}>
          <MiniStat label="Score range" value={sec.scoreRange} />
          <MiniStat label="Accuracy" value={`${sec.accuracy}%`} />
          <MiniStat label="Items" value={sec.items} />
          {sec.cohortMid != null
            ? <MiniStat label="vs cohort median" value={`${sec.scoreMid - sec.cohortMid > 0 ? "+" : ""}${sec.scoreMid - sec.cohortMid} pts`} tone={sec.scoreMid - sec.cohortMid > 0 ? "up" : "down"} />
            : <MiniStat label="Percentile" value={sec.percentile != null ? _ordinal(Math.round(sec.percentile)) : "—"} />}
        </div>
        {/* 2×2 grid */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", borderTop: "1px solid var(--sage-l)" }}>
          <GridPanel title="Result per Question" sub="Module 1 over Module 2" style={{ borderRight: "1px solid var(--sage-l)" }}><PerQuestionPanel sec={sec} /></GridPanel>
          <GridPanel title="Performance by Difficulty" sub="Score, time & answer changes by difficulty"><DifficultyPanel sec={sec} /></GridPanel>
          <GridPanel title="Confidence vs. Accuracy" sub="Both modules · how sure were you, really?" style={{ borderRight: "1px solid var(--sage-l)", borderTop: "1px solid var(--sage-l)" }}><ConfidenceMatrix sec={sec} /></GridPanel>
          <GridPanel title="Performance by Time" sub="Pace per question vs the recommended pace" style={{ borderTop: "1px solid var(--sage-l)" }}><TimePanel sec={sec} /></GridPanel>
        </div>
        {/* topic breakdown */}
        <div style={{ padding: "22px 24px 24px", borderTop: "1px solid var(--sage-l)", background: "#FCFDF6" }}>
          <SecHead title="Topic Deep-Dive" sub="Click each domain to expand" />
          <TopicBreakdown sec={sec} key={tab} />
        </div>
      </Card>

      <RecommendedPlan sec={sec} />
      <Services />

      <div style={{ textAlign: "center", fontFamily: "var(--fp)", fontSize: "0.74rem", color: "var(--muted)", marginTop: 4 }}>
        LearningWithSruthi · SAT Results Report · generated June 15, 2026 · questions? reply to your results email
      </div>
    </div>
  );
}
function MiniStat({ label, value, tone }) {
  return (
    <div>
      <div style={{ fontFamily: "var(--fp)", fontSize: "0.66rem", color: "var(--muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{label}</div>
      <div style={{ fontFamily: "var(--fh)", color: tone === "up" ? "var(--success)" : tone === "down" ? "var(--error)" : "var(--forest)", fontSize: "1.15rem", marginTop: 3, fontVariantNumeric: "tabular-nums" }}>{value}</div>
    </div>
  );
}
function TrajLegend() {
  return (
    <div style={{ display: "flex", gap: 14, alignItems: "center", fontFamily: "var(--fp)", fontSize: "0.7rem", color: "var(--slate)" }}>
      <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
        <svg width="26" height="14" viewBox="0 0 26 14"><line x1="13" y1="2" x2="13" y2="12" stroke="var(--sage)" strokeWidth="1.2" /><rect x="5" y="5" width="16" height="4" fill="#C5D9A8" stroke="var(--sage)" strokeWidth="1" /><line x1="5" y1="7" x2="21" y2="7" stroke="var(--forest)" strokeWidth="1.4" /></svg>
        low · median · high
      </span>
      <span style={{ display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 14, height: 3, background: "var(--forest)" }} /> Target</span>
    </div>
  );
}

Object.assign(window, { ReportApp });
