// Body — HRV/sleep/readiness + the HRV-social correlation insight

function BodyScreen({ go }) {
  const d = LifeData;
  const h = d.health.today;
  const base = d.health.baseline;
  const week = d.health.week;

  const haveData = h.hrv_ms > 0 || h.sleep_hours > 0;
  const dayName = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][new Date().getDay()];

  if (!haveData) {
    return (
      <div style={{ paddingBottom: 110 }}>
        <div style={{ padding: '64px 20px 8px' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>Body · {dayName}</div>
          <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.6, lineHeight: '38px', marginTop: 4 }}>No health data.</div>
          <div style={{ fontSize: 15, color: T.label2, marginTop: 4 }}>Send an Apple Health export to see your recovery.</div>
        </div>
        <div style={{ padding: '20px 16px' }}>
          <Card style={{ padding: 20, textAlign: 'center' }}>
            <IconPulse size={40} color={T.label3} />
            <div style={{ fontSize: 16, fontWeight: 600, marginTop: 12 }}>Import Apple Health</div>
            <div style={{ fontSize: 14, color: T.label2, marginTop: 6, lineHeight: '20px' }}>
              POST your export.xml to <code style={{ fontSize: 12 }}>/ingest/health/shay</code>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  const readinessLabel = h.readiness >= 80 ? 'High' : h.readiness >= 60 ? 'Moderate' : 'Low';
  const readinessHint = h.readiness >= 80
    ? 'Great recovery. You\'re good for a hard session today.'
    : h.readiness >= 60
    ? 'Moderate recovery. Consider lighter training.'
    : 'Low HRV + short sleep. Rest or mobility today.';

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Header */}
      <div style={{ padding: '64px 20px 8px' }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: T.label2, letterSpacing: 0.4, textTransform: 'uppercase' }}>
          Body · {dayName}
        </div>
        <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: -0.6, lineHeight: '38px', marginTop: 4 }}>
          {readinessLabel === 'Low' ? 'Go easy today.' : readinessLabel === 'High' ? 'You\'re recovered.' : 'Feeling moderate.'}
        </div>
        <div style={{ fontSize: 15, color: T.label2, marginTop: 4 }}>
          {readinessHint}
        </div>
      </div>

      {/* Readiness ring */}
      {h.readiness > 0 && (
        <div style={{ padding: '14px 16px 0' }}>
          <Card style={{
            background: grad('#1C1C1E','#2C2C2E'),
            color: '#fff',
            padding: 22,
            display: 'flex', alignItems: 'center', gap: 18,
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', top: -60, left: -60, width: 220, height: 220, borderRadius: 999,
              background: grad('rgba(255,59,48,0.25)','rgba(255,149,0,0.08)'), filter: 'blur(24px)',
            }} />
            <ReadinessRing value={Math.round(h.readiness)} />
            <div style={{ flex: 1, position: 'relative' }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: 0.5, color: '#FFCC00', textTransform: 'uppercase' }}>Readiness</div>
              <div style={{ fontSize: 28, fontWeight: 700, marginTop: 2, lineHeight: '32px' }}>{readinessLabel}</div>
              <div style={{ fontSize: 13, opacity: 0.7, marginTop: 6, lineHeight: '18px' }}>
                {readinessHint}
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* Big stats */}
      <Section title="Today" style={{ marginTop: 22 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {h.hrv_ms > 0 && (
            <BigStat
              icon={<IconPulse size={16} color={T.red} />}
              label="HRV" value={Math.round(h.hrv_ms)} unit="ms"
              delta={base.hrv_ms ? `${h.hrv_ms < base.hrv_ms ? '–' : '+'}${Math.round(Math.abs(h.hrv_ms - base.hrv_ms))}` : '—'} bad={base.hrv_ms && h.hrv_ms < base.hrv_ms}
              spark={week.map(w => w.hrv || 0)}
            />
          )}
          {h.rhr_bpm > 0 && (
            <BigStat
              icon={<IconHeart size={16} color={T.pink} />}
              label="Resting HR" value={Math.round(h.rhr_bpm)} unit="bpm"
              delta={base.rhr_bpm ? `${h.rhr_bpm > base.rhr_bpm ? '+' : ''}${Math.round(h.rhr_bpm - base.rhr_bpm)}` : '—'} bad={base.rhr_bpm && h.rhr_bpm > base.rhr_bpm}
              spark={week.map(w => w.rhr || 0)} inverted
            />
          )}
          {h.sleep_hours > 0 && (
            <BigStat
              icon={<IconBed size={16} color={T.indigo} />}
              label="Sleep" value={`${Math.floor(h.sleep_hours)}h${Math.round((h.sleep_hours%1)*60).toString().padStart(2,'0')}`}
              delta={base.sleep_hours ? `${(h.sleep_hours - base.sleep_hours).toFixed(1)}h` : '—'} bad={base.sleep_hours && h.sleep_hours < base.sleep_hours}
              spark={week.map(w => w.sleep || 0)}
            />
          )}
          {h.readiness > 0 && (
            <BigStat
              icon={<IconBolt size={16} color={T.green} />}
              label="Readiness" value={Math.round(h.readiness)} unit="%"
              delta="vs avg" bad={h.readiness < 60}
              spark={week.map(w => w.readiness || 0)}
            />
          )}
        </div>
      </Section>

      {/* Sleep stages — only if we have the breakdown */}
      {(h.sleep_rem_hours > 0 || h.sleep_deep_hours > 0 || h.sleep_core_hours > 0) && (
        <Section title="Sleep stages, last night" style={{ marginTop: 22 }}>
          <Card>
            <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: -0.5, fontVariantNumeric: 'tabular-nums' }}>
              {Math.floor(h.sleep_hours)}h {Math.round((h.sleep_hours%1)*60)}m
            </div>
            <div style={{ fontSize: 12, color: T.label2, marginBottom: 14 }}>
              {base.sleep_hours ? `${Math.abs((h.sleep_hours - base.sleep_hours)*60).toFixed(0)}m ${h.sleep_hours < base.sleep_hours ? 'below' : 'above'} your ${Math.floor(base.sleep_hours)}h${Math.round((base.sleep_hours%1)*60).toString().padStart(2,'0')} baseline` : 'Sleep breakdown'}
            </div>
            <SleepBar h={h} />
            <div style={{ display: 'flex', gap: 14, marginTop: 14, fontSize: 12 }}>
              <SleepLegend color={T.teal} label="REM" value={formatH(h.sleep_rem_hours)} />
              <SleepLegend color={T.indigo} label="Deep" value={formatH(h.sleep_deep_hours)} />
              <SleepLegend color="#A2A4F5" label="Core" value={formatH(h.sleep_core_hours)} />
            </div>
          </Card>
        </Section>
      )}

      {/* Cross-signal insight */}
      {d.people.length > 0 && h.hrv_ms > 0 && (
        <Section title="Pattern" style={{ marginTop: 22 }}>
          <Card style={{ padding: 18, background: '#fff' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <IconSparkle size={14} color={T.purple} fill={T.purple} sw={0} />
              <span style={{ fontSize: 11, fontWeight: 600, color: T.purple, letterSpacing: 0.5, textTransform: 'uppercase' }}>Cross-signal pattern</span>
            </div>
            <div style={{ fontSize: 17, lineHeight: '23px', marginTop: 10, letterSpacing: -0.2 }}>
              Your HRV drops in weeks you talk to family less than twice. Check your radar.
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
              <button onClick={() => go('radar')} style={{
                flex: 1, height: 38, borderRadius: 10, border: 'none', background: T.bg, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
              }}>
                <IconRadar size={14} color={T.label} /> Open radar
              </button>
              <button onClick={() => go('chat')} style={{
                flex: 1, height: 38, borderRadius: 10, border: 'none', background: T.purple, color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>Ask Life OS</button>
            </div>
          </Card>
        </Section>
      )}

      {/* HRV trend */}
      {week.some(w => w.hrv > 0) && (
        <Section title="HRV · 7 days" style={{ marginTop: 22 }}>
          <Card>
            <HRVChart week={week} baseline={base.hrv_ms || 0} />
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11, color: T.label2, fontVariantNumeric: 'tabular-nums' }}>
              {week.map((w, i) => <span key={i}>{w.date}</span>)}
            </div>
          </Card>
        </Section>
      )}

      <div style={{ padding: '20px 16px 0', fontSize: 11, color: T.label3, textAlign: 'center', lineHeight: '17px' }}>
        <IconShield size={11} color={T.label3} /> Health raw data never leaves your Thinkpad.
      </div>
    </div>
  );
}

function ReadinessRing({ value }) {
  const r = 44, c = 2 * Math.PI * r;
  const offset = c * (1 - value / 100);
  return (
    <svg width="106" height="106" viewBox="0 0 106 106">
      <defs>
        <linearGradient id="readGrad" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="#FFCC00" />
          <stop offset="100%" stopColor="#FF9500" />
        </linearGradient>
      </defs>
      <circle cx="53" cy="53" r={r} fill="none" stroke="rgba(255,255,255,0.12)" strokeWidth="9" />
      <circle cx="53" cy="53" r={r} fill="none" stroke="url(#readGrad)" strokeWidth="9"
        strokeLinecap="round" strokeDasharray={c} strokeDashoffset={offset}
        transform="rotate(-90 53 53)" />
      <text x="53" y="56" textAnchor="middle" fill="#fff" fontSize="26" fontWeight="700" letterSpacing="-0.5">{value}</text>
      <text x="53" y="71" textAnchor="middle" fill="rgba(255,255,255,0.6)" fontSize="9" fontWeight="600" letterSpacing="0.5">/100</text>
    </svg>
  );
}

function BigStat({ icon, label, value, unit, delta, bad, spark, inverted }) {
  const validSpark = spark.filter(v => v > 0);
  const max = validSpark.length > 0 ? Math.max(...spark) : 1;
  const min = validSpark.length > 0 ? Math.min(...spark) : 0;
  const range = max - min || 1;
  return (
    <Card style={{ padding: 14, position: 'relative', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
        {icon}
        <span style={{ fontSize: 11, fontWeight: 600, color: T.label2, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</span>
      </div>
      <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: -0.5, marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>
        {value}
        {unit && <span style={{ fontSize: 13, fontWeight: 500, color: T.label2, marginLeft: 3 }}>{unit}</span>}
      </div>
      {delta !== '—' && <div style={{ fontSize: 12, color: bad ? T.red : T.green, marginTop: 1, fontWeight: 500 }}>{delta} vs avg</div>}
      {validSpark.length > 1 && (
        <svg width="100%" height="22" viewBox="0 0 100 22" style={{ marginTop: 8, display: 'block' }}>
          <polyline points={spark.map((v, i) => {
            const x = (i / (spark.length - 1)) * 100;
            const y = 20 - ((v - min) / range) * 18;
            return `${x},${y}`;
          }).join(' ')} fill="none" stroke={bad ? T.red : T.green} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
          <circle cx="100" cy={20 - ((spark[spark.length-1] - min) / range) * 18} r="2.4" fill={bad ? T.red : T.green} />
        </svg>
      )}
    </Card>
  );
}

function SleepBar({ h }) {
  const total = h.sleep_rem_hours + h.sleep_deep_hours + h.sleep_core_hours || 1;
  const segs = [
    { color: T.teal, mins: h.sleep_rem_hours },
    { color: T.indigo, mins: h.sleep_deep_hours },
    { color: '#A2A4F5', mins: h.sleep_core_hours },
  ].filter(s => s.mins > 0);
  return (
    <div style={{ display: 'flex', gap: 1, height: 38, borderRadius: 8, overflow: 'hidden' }}>
      {segs.map((s, i) => (
        <div key={i} style={{ flex: s.mins / total, background: s.color }} />
      ))}
    </div>
  );
}

function SleepLegend({ color, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
      <span style={{ width: 8, height: 8, borderRadius: 2, background: color }} />
      <span style={{ color: T.label2 }}>{label}</span>
      <span style={{ fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
    </div>
  );
}

function formatH(hours) {
  if (!hours) return '0m';
  const h = Math.floor(hours);
  const m = Math.round((hours - h) * 60);
  return h > 0 ? `${h}h${String(m).padStart(2,'0')}` : `${m}m`;
}

function HRVChart({ week, baseline }) {
  const validHRV = week.map(w => w.hrv).filter(v => v > 0);
  if (validHRV.length === 0) return null;
  const W = 320, H = 90, pad = 8;
  const max = Math.max(...validHRV, baseline || 0) + 4;
  const min = Math.min(...validHRV) - 4;
  const range = max - min || 1;
  const bw = (W - 2*pad) / week.length;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
      {baseline > 0 && (
        <>
          <line x1={pad} x2={W-pad}
            y1={pad + (1 - (baseline - min) / range) * (H - 2*pad)}
            y2={pad + (1 - (baseline - min) / range) * (H - 2*pad)}
            stroke="rgba(60,60,67,0.2)" strokeDasharray="3 3" strokeWidth="1" />
          <text x={W - pad - 2} y={pad + (1 - (baseline - min) / range) * (H - 2*pad) - 4}
            textAnchor="end" fontSize="9" fill={T.label2}>avg {Math.round(baseline)}ms</text>
        </>
      )}
      {week.map((w, i) => {
        if (!w.hrv) return null;
        const x = pad + i * bw + bw/2 - 9;
        const barH = ((w.hrv - min) / range) * (H - 2*pad);
        const y = H - pad - barH;
        const isLow = baseline > 0 && w.hrv < baseline;
        return (
          <g key={w.date}>
            <rect x={x} y={y} width={18} height={barH} rx={4}
              fill={isLow ? T.red : T.green} opacity={i === week.length - 1 ? 1 : 0.4} />
            <text x={x + 9} y={y - 4} textAnchor="middle" fontSize="9" fontWeight="600" fill={T.label2}>{w.hrv}</text>
          </g>
        );
      })}
    </svg>
  );
}

window.BodyScreen = BodyScreen;
