/* v2 Screen 4 — Baseline Comparison / Results
 * Refinements: hero "Today vs Your Baseline" gets full prominence with
 * a single overall verdict card. Metric cards re-built with consistent layout.
 */
const V2Screen4 = () => {
  const metrics = [
    { key: "symmetry", label: "Lip symmetry",          today: 0.91, base: 0.93, unit: "index", delta: "−2%",  flag: false, note: "Within typical range." },
    { key: "corners",  label: "Corner stability",      today: 0.78, base: 0.86, unit: "index", delta: "−9%",  flag: true,  note: "Below baseline; consistent with elevated fatigue." },
    { key: "aperture", label: "Aperture consistency",  today: 0.84, base: 0.82, unit: "index", delta: "+2%",  flag: false, note: "On baseline." },
    { key: "fatigue",  label: "Self-reported fatigue", today: 4,    base: 2.4,  unit: "/10",   delta: "+1.6", flag: true,  note: "Higher than your 30-day mean." },
  ];

  return (
    <div className="v2 phone">
      <V2StatusBar />
      <div className="phone-scroll">
        <V2Header />

        {/* HERO — the most important screen */}
        <div className="opener" style={{ paddingBottom: 0 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Results · session 014</div>
          <h1 className="h1">
            Today <span style={{ color: "var(--v2-ink-3)", fontStyle: "italic" }}>vs.</span> your baseline
          </h1>
          <p className="body" style={{ marginTop: 12 }}>
            Compared against <span className="tnum" style={{ fontFamily: "var(--v2-mono)" }}>n=12</span> of your prior sessions. Descriptive, not diagnostic.
          </p>
        </div>

        {/* Verdict card — one calm summary */}
        <div style={{ padding: "var(--v2-s-5) var(--v2-s-5) 0" }}>
          <div className="card">
            <div className="card-head">
              <div className="eyebrow">Overall pattern</div>
              <span className="pill ochre"><span className="dot" /> Attention</span>
            </div>
            <div className="card-body">
              <h2 className="h2">Mild deviation from baseline.</h2>
              <p className="body-sm" style={{ marginTop: 10 }}>
                Two of four indicators sit below your prior range, alongside elevated self-reported fatigue. The pattern matches under-recovery, not a structural change.
              </p>
              <div style={{ marginTop: 18 }}>
                <V2DeviationStrip metrics={metrics} />
              </div>
            </div>
          </div>
        </div>

        {/* Metric cards */}
        <div style={{ padding: "var(--v2-s-5) var(--v2-s-5) 0", display: "flex", flexDirection: "column", gap: 12 }}>
          {metrics.map(m => <V2MetricCard key={m.key} m={m} />)}
        </div>

        {/* Trend */}
        <div style={{ padding: "var(--v2-s-5) var(--v2-s-5) 0" }}>
          <div className="card">
            <div className="card-head">
              <div>
                <div className="eyebrow" style={{ marginBottom: 4 }}>Corner stability — last 14 sessions</div>
                <div className="cap" style={{ textTransform: "none", letterSpacing: 0 }}>solid · session value &nbsp;·&nbsp; band · your baseline μ ± σ</div>
              </div>
            </div>
            <div className="card-body" style={{ paddingTop: 12 }}>
              <V2TrendChart />
            </div>
          </div>
        </div>

        {/* Baseline-rule signature — recurring */}
        <div style={{ padding: "var(--v2-s-4) var(--v2-s-5) 0" }}>
          <V2BaselineRule eyebrow="Interpretation">
            All values are read against <em style={{ fontFamily: "var(--v2-serif)" }}>your own</em> baseline. OrisTrack does not compare you to other players, and does not provide a diagnosis. Trend is more informative than any single session.
          </V2BaselineRule>
        </div>

        <div style={{ height: 180 }} />
      </div>

      <div className="phone-bottom-cta">
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-secondary" style={{ flex: 1 }}>Export PDF</button>
          <button className="btn" style={{ flex: 1 }}>Continue monitoring</button>
        </div>
      </div>

      <V2TabBar active="results" />
    </div>
  );
};

const V2MetricCard = ({ m }) => {
  const max = m.unit === "/10" ? 10 : 1;
  const todayPct = (m.today / max) * 100;
  const basePct  = (m.base / max) * 100;
  return (
    <div className="card">
      <div className="card-body" style={{ padding: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <div className="h3">{m.label}</div>
          <span className={`pill ${m.flag ? "ochre" : "muted"}`}>
            <span className="dot" /> {m.delta} vs baseline
          </span>
        </div>

        <div style={{ display: "flex", alignItems: "flex-end", gap: 20, marginTop: 14 }}>
          <div>
            <div className="cap">today</div>
            <div className="num-xl">
              {m.today.toFixed(m.unit === "/10" ? 1 : 2)}
              <span className="cap" style={{ marginLeft: 6 }}>{m.unit}</span>
            </div>
          </div>
          <div style={{ width: 1, alignSelf: "stretch", background: "var(--v2-hairline-2)" }} />
          <div>
            <div className="cap">your baseline</div>
            <div className="num-md">
              {m.base.toFixed(m.unit === "/10" ? 1 : 2)}
              <span className="cap" style={{ marginLeft: 6 }}>{m.unit}</span>
            </div>
          </div>
        </div>

        {/* range bar */}
        <div style={{ marginTop: 14, position: "relative", height: 22 }}>
          <div style={{ position: "absolute", top: 10, left: 0, right: 0, height: 2, background: "var(--v2-bone-2)" }} />
          <div style={{
            position: "absolute", top: 4, bottom: 4,
            left: `calc(${basePct}% - 0.5px)`,
            width: 1, borderLeft: "1px dashed var(--v2-ink-3)",
          }} />
          <div style={{
            position: "absolute", top: 6,
            left: `calc(${todayPct}% - 5px)`,
            width: 10, height: 10, borderRadius: "50%",
            background: "var(--v2-ink)",
            border: "2px solid var(--v2-paper)",
            boxShadow: "0 0 0 1px var(--v2-ink)",
          }} />
          <div className="cap" style={{ position: "absolute", left: 0, bottom: -2, fontSize: 10 }}>0</div>
          <div className="cap" style={{ position: "absolute", right: 0, bottom: -2, fontSize: 10 }}>{max === 10 ? "10" : "1.0"}</div>
        </div>

        <div className="body-sm" style={{ marginTop: 14, fontSize: 12.5 }}>{m.note}</div>
      </div>
    </div>
  );
};

const V2DeviationStrip = ({ metrics }) => (
  <div>
    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
      <div className="cap" style={{ fontSize: 10 }}>below</div>
      <div className="cap" style={{ fontSize: 10 }}>baseline</div>
      <div className="cap" style={{ fontSize: 10 }}>above</div>
    </div>
    <div style={{ position: "relative", height: 32 }}>
      <div style={{ position: "absolute", top: 14, left: 0, right: 0, height: 2, background: "var(--v2-bone-2)" }} />
      <div style={{ position: "absolute", top: 6, bottom: 6, left: "50%", width: 1, borderLeft: "1px dashed var(--v2-ink-3)" }} />
      {metrics.map(m => {
        const num = parseFloat(m.delta.replace("%", "").replace("−", "-"));
        const max = m.unit === "/10" ? 5 : 15;
        const ratio = Math.max(-1, Math.min(1, num / max));
        const left = 50 + ratio * 40;
        return (
          <div key={m.key} style={{
            position: "absolute",
            left: `calc(${left}% - 5px)`,
            top: 9,
            width: 10, height: 10, borderRadius: "50%",
            background: m.flag ? "var(--v2-ochre)" : "var(--v2-ink)",
            border: "2px solid var(--v2-paper)",
            boxShadow: "0 0 0 1px " + (m.flag ? "var(--v2-ochre)" : "var(--v2-ink)"),
          }} />
        );
      })}
    </div>
    <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
      {metrics.map(m => (
        <div key={m.key} style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{
            width: 7, height: 7, borderRadius: "50%",
            background: m.flag ? "var(--v2-ochre)" : "var(--v2-ink)",
          }} />
          <span className="cap" style={{ textTransform: "none", letterSpacing: 0, fontSize: 11 }}>{m.label.toLowerCase()}</span>
        </div>
      ))}
    </div>
  </div>
);

const V2TrendChart = () => {
  const data = [0.88, 0.86, 0.87, 0.85, 0.89, 0.86, 0.88, 0.87, 0.85, 0.86, 0.84, 0.83, 0.81, 0.78];
  const w = 320, h = 130, padX = 8, padY = 14;
  const baseline = 0.86, sigma = 0.03;
  const yMin = 0.74, yMax = 0.94;
  const xs = data.map((_, i) => padX + (i * (w - 2 * padX)) / (data.length - 1));
  const ys = data.map(v => padY + (1 - (v - yMin) / (yMax - yMin)) * (h - 2 * padY));
  const baseY = padY + (1 - (baseline - yMin) / (yMax - yMin)) * (h - 2 * padY);
  const sigUp = padY + (1 - ((baseline + sigma) - yMin) / (yMax - yMin)) * (h - 2 * padY);
  const sigDn = padY + (1 - ((baseline - sigma) - yMin) / (yMax - yMin)) * (h - 2 * padY);
  const path = xs.map((x, i) => `${i === 0 ? "M" : "L"} ${x.toFixed(1)} ${ys[i].toFixed(1)}`).join(" ");

  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} style={{ display: "block" }}>
      <rect x={0} y={sigUp} width={w} height={sigDn - sigUp} fill="var(--v2-bone-2)" />
      <line x1={0} x2={w} y1={baseY} y2={baseY} stroke="var(--v2-ink-3)" strokeDasharray="3 3" strokeWidth="1" />
      {[0.80, 0.85, 0.90].map(g => {
        const y = padY + (1 - (g - yMin) / (yMax - yMin)) * (h - 2 * padY);
        return (
          <g key={g}>
            <line x1={0} x2={w} y1={y} y2={y} stroke="var(--v2-hairline-2)" strokeWidth="1" />
            <text x={w - 2} y={y - 3} fontFamily="var(--v2-mono)" fontSize="9" fill="var(--v2-ink-3)" textAnchor="end">{g.toFixed(2)}</text>
          </g>
        );
      })}
      <path d={path} fill="none" stroke="var(--v2-today)" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
      {xs.map((x, i) => {
        const isLast = i === xs.length - 1;
        return (
          <circle key={i} cx={x} cy={ys[i]}
            r={isLast ? 4 : 2.2}
            fill={isLast ? "var(--v2-ink)" : "var(--v2-paper)"}
            stroke={isLast ? "var(--v2-paper)" : "var(--v2-today)"}
            strokeWidth={isLast ? 2 : 1.2}
          />
        );
      })}
      <text x={xs[xs.length - 1] - 6} y={ys[ys.length - 1] - 10} fontFamily="var(--v2-mono)" fontSize="10" fill="var(--v2-ink)" textAnchor="end">today · 0.78</text>
    </svg>
  );
};

window.V2Screen4 = V2Screen4;
