/* ============================================================
   screens-detail.jsx — RECOVERY · SLEEP · TRENDS · CLINICAL
   ============================================================ */
(function () {
  const fmtDur = window.fmtDur || ((m) => m == null ? "—" : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`);

  function ScreenHead({ title, sub }) {
    return (
      <div style={{ marginBottom: 16 }}>
        <Label>{sub}</Label>
        <h1 style={{ margin: "5px 0 0", fontSize: 23, fontWeight: 700, letterSpacing: "-0.01em" }}>{title}</h1>
      </div>
    );
  }
  window.ScreenHead = ScreenHead;

  // input status → tone for delta
  function inputTone(inp) {
    if (inp.status === "good") return "good";
    if (inp.status === "attn") return "attn";
    return "neutral";
  }

  // ---- RECOVERY DETAIL ------------------------------------
  function InputRow({ inp }) {
    const within = inp.status === "within";
    const low = inp.status === "lowconf";
    const deltaTone = inputTone(inp);
    return (
      <div style={{ padding: "14px 0", borderBottom: "1px solid var(--line)" }}>
        <Row justify="space-between" align="center" style={{ marginBottom: 9 }}>
          <Row gap={7} style={{ minWidth: 0 }}>
            <StatusMark status={inp.status} size={12} />
            <span style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap" }}>{inp.label}</span>
          </Row>
          <Label style={{ color: "var(--ink-4)", whiteSpace: "nowrap" }}>{inp.weight}% wt</Label>
        </Row>
        <Row justify="space-between" align="flex-end">
          <div style={{ minWidth: 0 }}>
            <Row gap={6} align="baseline">
              <span className="num" style={{ fontSize: 21, fontWeight: 600 }}>{inp.value}</span>
              <span className="mono-label" style={{ fontSize: 10 }}>{inp.unit}</span>
            </Row>
            {inp.note && <div style={{ marginTop: 4 }}><Delta tone={deltaTone}>{inp.note}</Delta></div>}
          </div>
          <div style={{ flexShrink: 0, textAlign: "right" }}>
            <Spark data={inp.series} baseline={inp.baseline} swc={inp.swc} status={inp.status} lowconf={low} w={116} h={38} />
            <Label style={{ fontSize: 9, color: "var(--ink-4)", marginTop: 3, display: "block" }}>{within ? "within band" : low ? "low confidence" : "outside band"}</Label>
          </div>
        </Row>
      </div>
    );
  }

  function Recovery({ data, viz = "dist" }) {
    const rec = data.recovery, st = window.recStatus(rec.value);
    return (
      <div>
        <ScreenHead sub={data.date + " · why this score"} title="Recovery" />
        <Card pad={18}>
          <Row justify="space-between" align="flex-start" style={{ marginBottom: 16 }}>
            <div>
              <Readout value={rec.value} unit="%" band={rec.band} size={56} status={st} />
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 8, textWrap: "pretty" }}>{rec.headline}</div>
            </div>
            <ConfidenceMeter level={rec.confidence} pct={rec.confidence === "high" ? 96 : rec.confidence === "medium" ? 68 : 41} />
          </Row>
          <window.RecoveryViz rec={rec} kind={viz} status={st} />
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 8, fontFamily: "var(--font-mono)", textAlign: "center" }}>
            point estimate {rec.value}% · 68% interval {Math.max(0, rec.value - rec.band)}–{Math.min(100, rec.value + rec.band)} · dashed = your typical
          </div>
        </Card>

        {rec.context.length > 0 && (
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            {rec.context.map((c, i) => (
              <Row key={i} gap={9} align="flex-start" style={{ padding: "11px 13px", background: c.type === "gap" ? "var(--bg-sunken)" : "var(--surface)", border: "1px solid " + (c.type === "flag" ? "var(--attn-line)" : "var(--line)"), borderRadius: "var(--r-sm)" }}>
                {c.type === "gap" ? <Icon name="gap" size={15} color="var(--ink-3)" /> : <StatusMark status={c.type === "flag" ? "attn" : "within"} size={13} />}
                <span style={{ fontSize: 12.5, lineHeight: 1.45, color: "var(--ink-2)", textWrap: "pretty" }}>{c.text}</span>
              </Row>
            ))}
          </div>
        )}

        <div style={{ marginTop: 18 }}>
          <SubLabel right="vs personal baseline · SWC band">Contributing inputs</SubLabel>
          <Card pad={16} style={{ paddingTop: 2, paddingBottom: 2 }}>
            {rec.inputs.map((inp) => <InputRow key={inp.key} inp={inp} />)}
            <div style={{ height: 2 }} />
          </Card>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 9, lineHeight: 1.5, fontFamily: "var(--font-mono)", padding: "0 2px" }}>
            Bayesian model · weights shown per input · shaded band = smallest worthwhile change (noise). A value inside the band is not meaningfully different from your norm.
          </div>
        </div>
      </div>
    );
  }

  // ---- SLEEP DETAIL ---------------------------------------
  function Sleep({ data }) {
    const sl = data.sleep, low = sl.confidence === "low";
    const stageRows = sl.stages ? [["Deep", sl.stages.deep], ["REM", sl.stages.rem], ["Light", sl.stages.light], ["Awake", sl.stages.awake]] : null;
    return (
      <div>
        <ScreenHead sub={data.date + " · last night"} title="Sleep" />
        <Card pad={18}>
          <Row justify="space-between" align="flex-end">
            <div>
              <Label>Duration</Label>
              <div style={{ marginTop: 6 }}><span className="readout" style={{ fontSize: 44, whiteSpace: "nowrap" }}>{fmtDur(sl.duration)}</span></div>
            </div>
            <ConfidenceMeter level={sl.confidence} />
          </Row>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginTop: 18 }}>
            {[["Regularity", sl.regularity, "/100"], ["Efficiency", sl.efficiency ?? "—", "%"], ["Fragments", sl.fragmentation ?? "—", `· base ${sl.fragBaseline}`]].map(([k, v, u]) => (
              <div key={k}><Label style={{ fontSize: 9.5 }}>{k}</Label><div className="num" style={{ fontSize: 20, fontWeight: 600, marginTop: 4 }}>{v}<span style={{ fontSize: 10, color: "var(--ink-4)", marginLeft: 3 }}>{u}</span></div></div>
            ))}
          </div>
        </Card>

        {/* onset signal */}
        <Card style={{ marginTop: 12 }}>
          <SubLabel right={sl.onsetSignal}>Sleep-onset signal</SubLabel>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5, textWrap: "pretty" }}>{sl.onsetNote}</div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 8, fontFamily: "var(--font-mono)" }}>derived from evening temp-rise + HR-fall</div>
        </Card>

        {/* duration trend */}
        <Card style={{ marginTop: 12 }}>
          <SubLabel right="14 nights">Duration trend</SubLabel>
          <Spark data={sl.series.map((m) => m / 60)} baseline={7.4} swc={0.6} status={low ? "lowconf" : "within"} lowconf={low} w={300} h={56} dot />
        </Card>

        {/* stages — visibly de-emphasized */}
        <div style={{ marginTop: 12 }}>
          <SubLabel right="lower confidence">Sleep stages</SubLabel>
          <Card style={{ opacity: stageRows ? 0.82 : 1 }}>
            {stageRows ? (
              <>
                <StageBar stages={sl.stages} w={300} h={22} />
                <div style={{ display: "flex", gap: 14, marginTop: 12, flexWrap: "wrap" }}>
                  {stageRows.map(([k, v]) => (
                    <Row key={k} gap={6}><span style={{ width: 9, height: 9, borderRadius: 2, background: { Deep: "var(--ink-2)", REM: "var(--ink-3)", Light: "var(--ink-4)", Awake: "var(--line-strong)" }[k], opacity: 0.7 }} /><Label style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-3)", whiteSpace: "nowrap" }}>{k} {fmtDur(v)}</Label></Row>
                  ))}
                </div>
                <Caveat>Stage classification from a wrist optical sensor is approximate — treat the split as indicative, not exact. Duration and regularity are the higher-confidence numbers above.</Caveat>
              </>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 2px" }}>
                <Icon name="gap" size={18} color="var(--ink-3)" />
                <div style={{ fontSize: 12.5, color: "var(--ink-3)", lineHeight: 1.4 }}>Stages unavailable — {sl.gapHrs}h wear-time gap during the early night.</div>
              </div>
            )}
          </Card>
        </div>
      </div>
    );
  }

  // ---- TRENDS ----------------------------------------------
  function rolling(arr, w) { return arr.map((_, i) => { const a = arr.slice(Math.max(0, i - w + 1), i + 1); return a.reduce((x, y) => x + y, 0) / a.length; }); }

  function Trends({ data }) {
    const T = window.OCC.trends;
    const [range, setRange] = React.useState("90d");
    const rhrAvg = rolling(T.rhr90 || [], 7), hrvAvg = rolling(T.hrv90 || [], 7);
    const last = (a) => a.length ? a[a.length - 1].toFixed(0) : "—";
    return (
      <div>
        <ScreenHead sub="chronic context · trajectory over snapshot" title="Trends" />
        <Row gap={6} style={{ marginBottom: 14 }}>
          {["30d", "90d", "6mo"].map((r) => (
            <button key={r} onClick={() => setRange(r)} style={{ flex: 1, padding: "8px 0", borderRadius: "var(--r-sm)", border: "1px solid " + (range === r ? "var(--ink)" : "var(--line)"), background: range === r ? "var(--ink)" : "var(--surface)", color: range === r ? "var(--surface)" : "var(--ink-3)", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500, letterSpacing: "0.03em" }}>{r.toUpperCase()}</button>
          ))}
        </Row>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <Card>
            <Row justify="space-between" style={{ marginBottom: 4 }}><SubLabel>Resting HR · 7-day avg</SubLabel><span className="num" style={{ fontSize: 13, color: "var(--ink-2)", fontWeight: 600 }}>{last(rhrAvg)} bpm</span></Row>
            <TrendChart raw={T.rhr90} avg={rhrAvg} baseline={54} swc={1.5} status="within" />
          </Card>
          <Card>
            <Row justify="space-between" style={{ marginBottom: 4 }}><SubLabel>HRV (rMSSD) · 7-day avg</SubLabel><span className="num" style={{ fontSize: 13, color: "var(--good-ink)", fontWeight: 600 }}>{last(hrvAvg)} ms</span></Row>
            <TrendChart raw={T.hrv90} avg={hrvAvg} baseline={61} swc={4} status="good" />
            <div style={{ fontSize: 10.5, color: "var(--ink-4)", marginTop: 6, fontFamily: "var(--font-mono)" }}>faint = nightly · solid = rolling avg · shaded = SWC band</div>
          </Card>
          <Card>
            <SubLabel right="CTL · ATL · form">Fitness / fatigue / form</SubLabel>
            <FFF ctl={T.ctl} atl={T.atl} form={T.form} />
            <div style={{ display: "flex", gap: 14, marginTop: 8, flexWrap: "wrap" }}>
              <Row gap={6}><span style={{ width: 14, height: 2, background: "var(--c-line)" }} /><Label style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-3)" }}>Fitness</Label></Row>
              <Row gap={6}><span style={{ width: 14, height: 0, borderTop: "2px dashed var(--attn)" }} /><Label style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-3)" }}>Fatigue</Label></Row>
              <Row gap={6}><span style={{ width: 14, height: 2, background: "var(--good)" }} /><Label style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-3)" }}>Form</Label></Row>
            </div>
          </Card>
          <Card>
            <SubLabel right="M10 / L5 windows">Circadian regularity</SubLabel>
            <Circadian data={T.circadian} />
            <Row gap={14} style={{ marginTop: 6 }}>
              <Row gap={6}><span style={{ width: 10, height: 10, borderRadius: 2, background: "var(--good-soft)", border: "1px solid var(--good-line)" }} /><Label style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-3)" }}>M10 active</Label></Row>
              <Row gap={6}><span style={{ width: 10, height: 10, borderRadius: 2, background: "var(--c-band)", border: "1px solid var(--line)" }} /><Label style={{ textTransform: "none", letterSpacing: 0, color: "var(--ink-3)" }}>L5 rest</Label></Row>
              <span style={{ marginLeft: "auto" }} className="num"><span style={{ fontSize: 12, color: "var(--ink-2)", fontWeight: 600 }}>IS 0.74</span></span>
            </Row>
          </Card>
        </div>
      </div>
    );
  }

  // ---- CLINICAL SCREENS -----------------------------------
  function ClinicalTabs({ active, set, clin }) {
    const items = [["af", clin.af], ["osa", clin.osa], ["illness", clin.illness]];
    return (
      <Row gap={6} style={{ marginBottom: 16 }}>
        {items.map(([k, c]) => {
          const on = active === k;
          const tone = c.status === "flag" ? "acute" : c.status === "watch" ? "attn" : "good";
          return (
            <button key={k} onClick={() => set(k)} style={{ flex: 1, padding: "9px 4px", borderRadius: "var(--r-sm)", border: "1px solid " + (on ? "var(--ink)" : "var(--line)"), background: on ? "var(--ink)" : "var(--surface)", color: on ? "var(--surface)" : "var(--ink-2)", display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, letterSpacing: "0.04em" }}>{c.short}</span>
              <span style={{ width: 5, height: 5, borderRadius: 999, background: on ? "var(--surface)" : tone === "acute" ? "var(--acute)" : tone === "attn" ? "var(--attn)" : "var(--good)" }} />
            </button>
          );
        })}
      </Row>
    );
  }

  function ClinicalDetail({ c }) {
    const tone = c.status === "flag" ? "acute" : c.status === "watch" ? "attn" : "good";
    const statusMark = c.status === "flag" ? "acute" : c.status === "watch" ? "attn" : "good";
    return (
      <div>
        <Card pad={18} style={{ borderColor: tone === "acute" ? "var(--acute-line)" : tone === "attn" ? "var(--attn-line)" : "var(--good-line)", background: tone === "good" ? "var(--surface)" : tone === "acute" ? "var(--acute-soft)" : "var(--surface)" }}>
          <Row justify="space-between" style={{ marginBottom: 12 }}>
            <Row gap={8}><StatusMark status={statusMark} size={15} /><Label style={{ color: tone === "acute" ? "var(--acute-ink)" : tone === "attn" ? "var(--attn-ink)" : "var(--good-ink)" }}>{c.status === "flag" ? "Flag · worth checking" : c.status === "watch" ? "Watch" : "Clear"}</Label></Row>
            <Chip tone={tone === "good" ? "good" : tone}>screen</Chip>
          </Row>
          <div style={{ fontSize: 19, fontWeight: 700, lineHeight: 1.2, marginBottom: 8, textWrap: "balance" }}>{c.result}</div>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5, textWrap: "pretty" }}>{c.detail}</div>
        </Card>

        <Card style={{ marginTop: 12 }}>
          <SubLabel>Threshold crossed</SubLabel>
          <div style={{ fontSize: 13, fontFamily: "var(--font-mono)", color: "var(--ink)", lineHeight: 1.5 }}>{c.threshold}</div>
        </Card>

        <Card style={{ marginTop: 12 }}>
          <SubLabel>What this test can and can't tell you</SubLabel>
          <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55, textWrap: "pretty" }}>{c.plain}</div>
          <Caveat tone={tone === "good" ? "neutral" : tone} action={c.action}>{c.caveat}</Caveat>
        </Card>
      </div>
    );
  }

  function Clinical({ data, initial = "af" }) {
    const clin = window.OCC.clinicalFor(data);
    const [active, setActive] = React.useState(initial);
    React.useEffect(() => { setActive(initial); }, [initial]);
    return (
      <div>
        <ScreenHead sub="screening · confirm with a professional" title="Clinical" />
        <ClinicalTabs active={active} set={setActive} clin={clin} />
        <ClinicalDetail c={clin[active]} />
      </div>
    );
  }

  Object.assign(window, { Recovery, Sleep, Trends, Clinical });
})();
