// Live screen — ambient in-bed view wired to MQTT vitals/target/sleep
function LiveScreen({ live, broker }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1000);
    return () => clearInterval(id);
  }, []);

  const hasHR = typeof live.hr === 'number';
  const hasBR = typeof live.br === 'number';
  const hrVal = hasHR ? live.hr : 0;
  const brVal = hasBR ? live.br : 0;
  const breathWave = live.phase.breath.length ? live.phase.breath : [];
  const heartWave = live.phase.heart.length ? live.phase.heart : [];

  const sinceMin = live.presenceSinceTs
    ? Math.max(0, Math.round((Date.now() - live.presenceSinceTs) / 60000))
    : null;

  const stageKey = live.stage || null;
  const stageLabel = stageKey ? stageKey.toUpperCase() : 'CLASSIFYING';
  const stageSinceMin = live.stageSinceTs
    ? Math.max(0, Math.round((Date.now() - live.stageSinceTs) / 60000))
    : null;

  const presenceLine = (() => {
    if (!live.online) return broker === 'connected' ? 'Device offline — no vitals for 15s' : `Broker ${broker}`;
    if (!live.inBed) return 'No presence detected — room is empty';
    return `Lux ${live.lux ?? '—'} · distance ${live.distance != null ? live.distance.toFixed(2) + ' m' : '—'}`;
  })();

  const regularityPct = typeof live.breathReg === 'number' ? Math.round(live.breathReg * 100) : null;

  return (
    <>
      <div className="page-header">
        <div>
          <div className="row items-center gap-8">
            <span className="live-dot" style={{
              background: live.online ? 'oklch(0.65 0.17 145)' : 'oklch(0.6 0.02 260)',
              boxShadow: live.online ? '0 0 0 3px oklch(0.65 0.17 145 / 0.2)' : 'none',
            }}/>
            <div className="page-eyebrow" style={{
              margin: 0,
              color: live.online ? 'oklch(0.5 0.14 145)' : 'var(--ink-3)',
            }}>
              {live.inBed
                ? `In bed · ${sinceMin ?? 0} min`
                : live.online ? 'Standby · no presence' : 'Offline'}
            </div>
          </div>
          <h1 className="page-title">{live.inBed ? 'Resting' : live.online ? 'Waiting for presence' : 'Not connected'}</h1>
          <div className="page-subtitle">{presenceLine}</div>
        </div>
        <div className="segment">
          <button className="active">Now</button>
        </div>
      </div>

      {/* Big ambient hero */}
      <div className="card" style={{ padding: 48, marginBottom: 16, background: 'linear-gradient(180deg, var(--bg-elev), var(--bg-sunken))' }}>
        <div className="row gap-32" style={{ flexWrap: 'wrap' }}>
          {/* Heart */}
          <div className="flex-1 col items-center" style={{ minWidth: 220 }}>
            <div className="text-xs text-ink-3" style={{ textTransform: 'uppercase', letterSpacing: '0.14em', fontWeight: 600, marginBottom: 12 }}>Heart rate</div>
            <div style={{ position: 'relative', width: 160, height: 160, display: 'grid', placeItems: 'center' }}>
              <div style={{
                position: 'absolute', inset: 0, borderRadius: '50%',
                border: '2px solid var(--hr-color)', opacity: hasHR ? 0.2 : 0.05,
                transform: hasHR ? `scale(${1 + (Math.sin(tick * (hrVal / 60) * Math.PI) + 1) * 0.04})` : 'scale(1)',
                transition: 'transform 0.4s ease-out',
              }}/>
              <div style={{
                position: 'absolute', inset: 16, borderRadius: '50%',
                background: 'var(--hr-color)', opacity: hasHR ? 0.06 : 0.02,
              }}/>
              <div className="col items-center">
                <span className="num" style={{ fontSize: 56, fontWeight: 600, letterSpacing: '-0.04em', color: 'var(--hr-color)' }}>
                  {hasHR ? Math.round(hrVal) : '—'}
                </span>
                <span className="text-xs text-ink-3" style={{ textTransform: 'uppercase', letterSpacing: '0.14em', marginTop: -4 }}>bpm</span>
              </div>
            </div>
            <div className="text-xs text-ink-3" style={{ marginTop: 12 }}>
              {hasHR ? 'Live from radar' : 'Awaiting vitals'}
            </div>
          </div>

          {/* Stage */}
          <div className="col items-center justify-center" style={{ minWidth: 200, gap: 12 }}>
            <span className={`stage-chip stage-${stageKey || 'awake'}`} style={{ fontSize: 13, padding: '6px 14px', opacity: stageKey ? 1 : 0.4 }}>
              <span className="stage-dot"/>{stageLabel}
            </span>
            <div className="col items-center gap-4">
              <span className="num" style={{ fontSize: 40, fontWeight: 500, letterSpacing: '-0.02em' }}>
                {typeof live.stageConfidence === 'number' ? Math.round(live.stageConfidence * 100) : '—'}
                <span className="text-sm text-ink-3">%</span>
              </span>
              <span className="text-xs text-ink-3">confidence</span>
            </div>
            <div className="text-xs text-ink-3" style={{ maxWidth: 200, textAlign: 'center', lineHeight: 1.5 }}>
              {stageKey && stageSinceMin !== null
                ? `In ${stageKey} for ${stageSinceMin} min`
                : live.inBed ? 'Classifier warming up (needs ~1 min of vitals)' : 'Classifier idle'}
            </div>
          </div>

          {/* Breath */}
          <div className="flex-1 col items-center" style={{ minWidth: 220 }}>
            <div className="text-xs text-ink-3" style={{ textTransform: 'uppercase', letterSpacing: '0.14em', fontWeight: 600, marginBottom: 12 }}>Breathing</div>
            <div style={{ position: 'relative', width: 160, height: 160, display: 'grid', placeItems: 'center' }}>
              <div style={{
                position: 'absolute', inset: 0, borderRadius: '50%',
                border: '2px solid var(--br-color)', opacity: hasBR ? 0.25 : 0.05,
                transform: hasBR ? `scale(${1 + Math.sin(tick / (60 / brVal) * Math.PI) * 0.08})` : 'scale(1)',
                transition: 'transform 1s ease-in-out',
              }}/>
              <div style={{
                position: 'absolute', inset: 16, borderRadius: '50%',
                background: 'var(--br-color)', opacity: hasBR ? 0.06 : 0.02,
              }}/>
              <div className="col items-center">
                <span className="num" style={{ fontSize: 56, fontWeight: 600, letterSpacing: '-0.04em', color: 'var(--br-color)' }}>
                  {hasBR ? Math.round(brVal) : '—'}
                </span>
                <span className="text-xs text-ink-3" style={{ textTransform: 'uppercase', letterSpacing: '0.14em', marginTop: -4 }}>rpm</span>
              </div>
            </div>
            <div className="text-xs text-ink-3" style={{ marginTop: 12 }}>
              {regularityPct != null ? `${regularityPct}% regularity` : 'Awaiting vitals'}
            </div>
          </div>
        </div>
      </div>

      {/* Phase waveforms */}
      <div className="grid-2" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="row justify-between items-center" style={{ marginBottom: 8 }}>
            <div className="card-title" style={{ margin: 0 }}>Breath phase</div>
            <span className="mono text-xs text-ink-3">rad · live</span>
          </div>
          <div style={{ color: 'var(--br-color)', minHeight: 80 }}>
            {breathWave.length
              ? <Sparkline data={breathWave} height={80} color="currentColor" strokeWidth={1.2} />
              : <div className="text-xs text-ink-3" style={{ padding: '28px 0', textAlign: 'center' }}>Waiting for phase data</div>}
          </div>
        </div>
        <div className="card">
          <div className="row justify-between items-center" style={{ marginBottom: 8 }}>
            <div className="card-title" style={{ margin: 0 }}>Heart phase</div>
            <span className="mono text-xs text-ink-3">rad · live</span>
          </div>
          <div style={{ color: 'var(--hr-color)', minHeight: 80 }}>
            {heartWave.length
              ? <Sparkline data={heartWave} height={80} color="currentColor" strokeWidth={1.2} />
              : <div className="text-xs text-ink-3" style={{ padding: '28px 0', textAlign: 'center' }}>Waiting for phase data</div>}
          </div>
        </div>
      </div>

      {/* Ambient metrics */}
      <div className="grid-4">
        <div className="card-flat">
          <Metric label="Distance" value={live.distance != null ? live.distance.toFixed(2) : '—'} unit="m" sub={live.distance != null ? 'from radar' : 'no target'} />
        </div>
        <div className="card-flat">
          <Metric label="Ambient light" value={live.lux != null ? live.lux : '—'} unit="lux" sub={live.lux != null && live.lux < 10 ? 'dark' : live.lux != null ? 'lit' : '—'} />
        </div>
        <div className="card-flat">
          <Metric label="Movement" value={live.movement != null ? live.movement.toFixed(2) : '—'} unit="idx" sub={live.movement != null && live.movement < 0.05 ? 'still' : live.movement != null ? 'active' : '—'} />
        </div>
        <div className="card-flat">
          <Metric label="HRV" value={live.hrv != null ? +live.hrv.toFixed(1) : '—'} unit="ms" sub={live.hrv != null ? 'from classifier' : 'awaiting epoch'} />
        </div>
      </div>
    </>
  );
}

window.LiveScreen = LiveScreen;
