/* ============================================================
   screens-home.jsx — HOME / TODAY: the tiered glance.
   Surfaces acute → sub-acute first; falls back to the wellness
   layer. Two layouts (stack / board) for the variation study.
   ============================================================ */
(function () {
  const fmtDur = (m) => m == null ? "—" : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;

  // recovery uncertainty viz, switchable (variation study)
  function RecoveryViz({ rec, kind = "dist", status }) {
    if (kind === "band") return <RecoveryBand value={rec.value} band={rec.band} status={status} />;
    if (kind === "arc") return <div style={{ display: "flex", justifyContent: "center" }}><RecoveryArc value={rec.value} band={rec.band} status={status} /></div>;
    return <RecoveryDist value={rec.value} band={rec.band} status={status} />;
  }
  window.RecoveryViz = RecoveryViz;

  const recStatus = (v) => v >= 67 ? "good" : v >= 45 ? "within" : "attn";

  // ---- ACUTE alert ----------------------------------------
  function AcuteAlert({ a, onOpen }) {
    return (
      <div style={{ background: "var(--acute-soft)", border: "1px solid var(--acute-line)", borderRadius: "var(--r)", padding: 16 }}>
        <Row justify="space-between" style={{ marginBottom: 10 }}>
          <Row gap={8}><StatusMark status="acute" size={15} /><Label style={{ color: "var(--acute-ink)" }}>Acute · worth checking</Label></Row>
          <Chip tone="acute">{a.time ? a.time.split("·")[1]?.trim() || "Now" : "Now"}</Chip>
        </Row>
        <div style={{ fontSize: 16.5, fontWeight: 700, lineHeight: 1.25, marginBottom: 6, color: "var(--ink)", textWrap: "balance" }}>{a.title}</div>
        <div style={{ fontSize: 13, lineHeight: 1.5, color: "var(--ink-2)", textWrap: "pretty" }}>{a.summary}</div>
        {a.metric && (
          <Row justify="space-between" style={{ marginTop: 12, padding: "10px 12px", background: "var(--surface)", borderRadius: "var(--r-sm)", border: "1px solid var(--acute-line)" }}>
            <div><Label>{a.metric.label}</Label><div className="num" style={{ fontSize: 22, fontWeight: 600, color: "var(--acute)", marginTop: 2 }}>{a.metric.value}</div></div>
            <div style={{ textAlign: "right" }}><Label>{a.time?.split("·")[0]?.trim()}</Label><div className="num" style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>{a.metric.threshold}</div></div>
          </Row>
        )}
        <Caveat tone="acute" action={a.action}>{a.caveat}</Caveat>
        <button onClick={onOpen} style={{ marginTop: 10, width: "100%", background: "transparent", border: "none", color: "var(--acute-ink)", fontSize: 12.5, fontWeight: 600, padding: 2, textAlign: "left", fontFamily: "var(--font-mono)", letterSpacing: "0.03em" }}>OPEN AF SCREEN →</button>
      </div>
    );
  }

  // ---- SUB-ACUTE card -------------------------------------
  function SubacuteCard({ s, onOpen }) {
    return (
      <Card style={{ borderColor: "var(--attn-line)" }}>
        <Row justify="space-between" style={{ marginBottom: 10 }}>
          <Row gap={8}><StatusMark status="attn" size={14} /><Label style={{ color: "var(--attn-ink)" }}>Investigate · {s.window}</Label></Row>
          <Chip tone="attn">multi-night</Chip>
        </Row>
        <div style={{ fontSize: 15.5, fontWeight: 700, lineHeight: 1.25, marginBottom: 6, textWrap: "balance" }}>{s.title}</div>
        <div style={{ fontSize: 12.5, lineHeight: 1.5, color: "var(--ink-2)", textWrap: "pretty", marginBottom: 12 }}>{s.summary}</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--line)", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", overflow: "hidden" }}>
          {s.signals.map((sig) => {
            const bad = (sig.dir === "up") !== sig.higherBetter;
            return (
              <div key={sig.label} style={{ background: "var(--surface)", padding: "9px 11px" }}>
                <Row justify="space-between" style={{ marginBottom: 5 }}>
                  <Label style={{ fontSize: 9.5, whiteSpace: "nowrap" }}>{sig.label}</Label>
                  <span className="num" style={{ fontSize: 12, fontWeight: 600, whiteSpace: "nowrap", color: bad ? "var(--attn-ink)" : "var(--good-ink)" }}>{sig.value}</span>
                </Row>
                <SignalSpark data={sig.series} dir={sig.dir} higherBetter={sig.higherBetter} w={120} h={22} />
              </div>
            );
          })}
        </div>
        <Caveat tone="attn" action={s.action}>{s.caveat}</Caveat>
        <button onClick={onOpen} style={{ marginTop: 10, width: "100%", background: "transparent", border: "none", color: "var(--attn-ink)", fontSize: 12.5, fontWeight: 600, padding: 2, textAlign: "left", fontFamily: "var(--font-mono)", letterSpacing: "0.03em" }}>OPEN ILLNESS SCREEN →</button>
      </Card>
    );
  }

  // ---- ALL CLEAR (reassuring, not blank) ------------------
  function AllClear({ data }) {
    return (
      <Card pad={18} style={{ borderColor: "var(--good-line)" }}>
        <Row gap={12} align="flex-start">
          <div style={{ flexShrink: 0, width: 34, height: 34, borderRadius: 999, background: "var(--good-soft)", display: "grid", placeItems: "center" }}>
            <svg width="18" height="18" viewBox="0 0 18 18"><path d="M4 9.5 L7.5 13 L14 5.5" fill="none" stroke="var(--good-ink)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 3 }}>{data.greeting}</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5, textWrap: "pretty" }}>No acute or sub-acute signals overnight. Your wellness layer is below.</div>
          </div>
        </Row>
        <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
          {[["Acute", "AF · desaturation"], ["Sub-acute", "apnea · illness · RHR"]].map(([t, sub]) => (
            <div key={t} style={{ flex: 1, minWidth: 0, padding: "9px 11px", background: "var(--bg-sunken)", borderRadius: "var(--r-sm)", border: "1px solid var(--line)" }}>
              <Row gap={5} style={{ marginBottom: 4 }}><StatusMark status="good" size={11} /><Label style={{ fontSize: 9.5, color: "var(--good-ink)", whiteSpace: "nowrap" }}>{t} clear</Label></Row>
              <div style={{ fontSize: 10, color: "var(--ink-4)", fontFamily: "var(--font-mono)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{sub}</div>
            </div>
          ))}
        </div>
      </Card>
    );
  }

  // ---- night confidence strip -----------------------------
  function NightStrip({ data }) {
    const c = data.confidence;
    return (
      <Card tone="sunken" pad={13} style={{ borderStyle: c.level === "low" ? "dashed" : "solid", borderColor: c.level === "low" ? "var(--line-strong)" : "var(--line)" }}>
        <Row justify="space-between">
          <div>
            <Label>Last night · data confidence</Label>
            <Row gap={8} style={{ marginTop: 6 }}>
              <ConfidenceMeter level={c.level} pct={c.pct} />
            </Row>
          </div>
          {c.gapHrs > 0 && (
            <div style={{ textAlign: "right" }}>
              <Row gap={5} justify="flex-end"><Icon name="gap" size={14} color="var(--ink-3)" /><Label style={{ color: "var(--ink-3)" }}>wear gap</Label></Row>
              <div className="num" style={{ fontSize: 16, fontWeight: 600, marginTop: 3, color: "var(--ink-2)" }}>{c.gapHrs}h</div>
            </div>
          )}
        </Row>
        {c.note && <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 12, lineHeight: 1.45, textWrap: "pretty" }}>{c.note}</div>}
      </Card>
    );
  }

  // ---- wellness cards -------------------------------------
  function RecoveryCard({ data, viz, onOpen }) {
    const rec = data.recovery, st = recStatus(rec.value);
    return (
      <Card onClick={onOpen} style={{ cursor: "pointer" }} className="occ-tap">
        <Row justify="space-between" style={{ marginBottom: 12 }}>
          <Label>Recovery</Label>
          <ConfidenceMeter level={rec.confidence} showText={true} />
        </Row>
        <Row justify="space-between" align="flex-end" style={{ marginBottom: 14 }}>
          <Readout value={rec.value} unit="%" band={rec.band} size={54} status={st} />
          <div style={{ textAlign: "right", maxWidth: 130 }}>
            <Chip tone={st === "good" ? "good" : st === "attn" ? "attn" : "neutral"}>
              <StatusMark status={st} size={11} />{st === "good" ? "recovered" : st === "attn" ? "low" : "moderate"}
            </Chip>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 6, lineHeight: 1.4, textWrap: "pretty" }}>{rec.headline}</div>
          </div>
        </Row>
        <RecoveryViz rec={rec} kind={viz} status={st} />
        <Row justify="space-between" style={{ marginTop: 12, paddingTop: 11, borderTop: "1px solid var(--line)" }}>
          <Label style={{ color: "var(--ink-4)", textTransform: "none", letterSpacing: 0 }}>{rec.context.length ? rec.context[0].text.slice(0, 38) + "…" : "4 inputs vs personal baseline"}</Label>
          <Label style={{ color: "var(--ink-3)" }}>why →</Label>
        </Row>
      </Card>
    );
  }

  function StrainSleepRow({ data, onSleep }) {
    const st = data.strain, sl = data.sleep;
    return (
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <Card>
          <Label>Strain</Label>
          {st.value != null ? (
            <>
              <div style={{ marginTop: 8, marginBottom: 10 }}><Readout value={st.value} band={st.band} size={30} /></div>
              <StrainBar value={st.value} target={st.target} />
              <Label style={{ marginTop: 8, display: "block", color: "var(--ink-4)", textTransform: "none", letterSpacing: 0 }}>{st.label} · target {st.target[0]}–{st.target[1]}</Label>
            </>
          ) : (
            <div style={{ marginTop: 10, fontSize: 12, color: "var(--ink-4)", fontFamily: "var(--font-mono)" }}>unavailable<br /><span style={{ fontSize: 10.5 }}>wear gap</span></div>
          )}
        </Card>
        <Card onClick={onSleep} style={{ cursor: "pointer" }} className="occ-tap">
          <Row justify="space-between"><Label>Sleep</Label><ConfidenceMeter level={sl.confidence} showText={false} /></Row>
          <div style={{ marginTop: 8, marginBottom: 6 }}><span className="readout" style={{ fontSize: 30 }}>{fmtDur(sl.duration)}</span></div>
          {sl.gapHrs ? (
            <div style={{ height: 8, borderRadius: 4, marginBottom: 8, background: "repeating-linear-gradient(135deg, var(--hatch) 0 4px, transparent 4px 8px)", border: "1px solid var(--line)" }} />
          ) : (
            <div style={{ marginBottom: 8 }}><StageBar stages={sl.stages} w={150} h={8} /></div>
          )}
          <Label style={{ color: "var(--ink-4)", textTransform: "none", letterSpacing: 0 }}>regularity {sl.regularity} · eff {sl.efficiency ?? "—"}%</Label>
        </Card>
      </div>
    );
  }

  // ---- HOME: STACK layout (default / variation A) ---------
  function HomeStack({ data, go, viz }) {
    const hasAcute = data.acute.length, hasSub = data.subacute.length;
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <NightStrip data={data} />
        {hasAcute > 0 && (<div><TierHeader tier="acute" title="Acute" count="1" /><div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{data.acute.map((a) => <AcuteAlert key={a.key} a={a} onOpen={() => go("clinical", "af")} />)}</div></div>)}
        {hasSub > 0 && (<div><TierHeader tier="subacute" title="Sub-acute" count="1" /><div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{data.subacute.map((s) => <SubacuteCard key={s.key} s={s} onOpen={() => go("clinical", "illness")} />)}</div></div>)}
        {!hasAcute && !hasSub && <AllClear data={data} />}
        <div>
          <TierHeader tier="wellness" title="Today · wellness" note="non-clinical" />
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <RecoveryCard data={data} viz={viz} onOpen={() => go("recovery")} />
            <StrainSleepRow data={data} onSleep={() => go("sleep")} />
          </div>
        </div>
        <button onClick={() => go("trends")} style={{ width: "100%", background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--r)", padding: "13px 16px", display: "flex", justifyContent: "space-between", alignItems: "center", color: "var(--ink-2)" }}>
          <Row gap={9}><span style={{ width: 3, height: 12, borderRadius: 2, background: "var(--ink-3)" }} /><Label style={{ color: "var(--ink-2)" }}>Chronic trends</Label></Row>
          <Label style={{ color: "var(--ink-4)", textTransform: "none", letterSpacing: 0 }}>RHR · HRV · fitness →</Label>
        </button>
      </div>
    );
  }

  // ---- HOME: BOARD layout (variation B) -------------------
  function StatusRow({ mark, status, label, value, onClick }) {
    return (
      <button onClick={onClick} style={{ width: "100%", background: "transparent", border: "none", borderBottom: "1px solid var(--line)", padding: "12px 2px", display: "flex", alignItems: "center", justifyContent: "space-between", textAlign: "left" }}>
        <Row gap={10}><StatusMark status={status} size={14} /><span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{label}</span></Row>
        <Row gap={8}><span className="num" style={{ fontSize: 12.5, color: status === "good" ? "var(--good-ink)" : status === "attn" ? "var(--attn-ink)" : status === "acute" ? "var(--acute-ink)" : "var(--ink-3)" }}>{value}</span><svg width="13" height="13" viewBox="0 0 13 13"><path d="M4.5 3 L8.5 6.5 L4.5 10" fill="none" stroke="var(--ink-4)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg></Row>
      </button>
    );
  }

  function HomeBoard({ data, go, viz }) {
    const hasAcute = data.acute.length, hasSub = data.subacute.length;
    const rec = data.recovery, st = recStatus(rec.value);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Card pad={16}>
          <Row justify="space-between" style={{ marginBottom: 4 }}><Label>Status board</Label><ConfidenceMeter level={data.confidence.level} pct={data.confidence.pct} /></Row>
          <StatusRow status={hasAcute ? "acute" : "good"} label="Acute alerts" value={hasAcute ? "AF flag" : "all clear"} onClick={() => hasAcute && go("clinical", "af")} />
          <StatusRow status={hasSub ? "attn" : "good"} label="Sub-acute screens" value={hasSub ? "illness · 3 nights" : "all clear"} onClick={() => hasSub && go("clinical", "illness")} />
          <StatusRow status="within" label="Chronic trends" value="stable" onClick={() => go("trends")} />
          <StatusRow status={st} label="Recovery" value={`${rec.value}% ± ${rec.band}`} onClick={() => go("recovery")} />
          <div style={{ height: 0 }} />
        </Card>
        {hasAcute > 0 && data.acute.map((a) => <AcuteAlert key={a.key} a={a} onOpen={() => go("clinical", "af")} />)}
        {hasSub > 0 && data.subacute.map((s) => <SubacuteCard key={s.key} s={s} onOpen={() => go("clinical", "illness")} />)}
        <div>
          <TierHeader tier="wellness" title="Today · wellness" note="non-clinical" />
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <RecoveryCard data={data} viz={viz} onOpen={() => go("recovery")} />
            <StrainSleepRow data={data} onSleep={() => go("sleep")} />
          </div>
        </div>
      </div>
    );
  }

  function Home({ data, go, viz = "dist", layout = "stack" }) {
    return layout === "board" ? <HomeBoard data={data} go={go} viz={viz} /> : <HomeStack data={data} go={go} viz={viz} />;
  }

  Object.assign(window, { Home, HomeStack, HomeBoard, RecoveryCard, AcuteAlert, SubacuteCard, AllClear, recStatus, fmtDur: fmtDur });
})();
