// Playback screen — replays a past session with scrubber, speed, CSV export
function PlaybackScreen({ playback, onExit, onPlayPause, onScrub, onSetSpeed, onDownloadCSV }) {
  const { status, session, vitals, epochs, index, playing, speed, error } = playback;

  if (status === 'loading' || status === 'idle') {
    return (
      <>
        <div className="page-header">
          <div>
            <div className="page-eyebrow">Playback</div>
            <h1 className="page-title">Loading session…</h1>
            <div className="page-subtitle">Fetching vitals and sleep epochs from backend</div>
          </div>
          <div className="row gap-8">
            <button className="btn" onClick={onExit}>Back to trends</button>
          </div>
        </div>
        <div className="card" style={{ padding: 32 }}>
          <div className="text-sm text-ink-3">One moment — the backend is streaming the session data.</div>
        </div>
      </>
    );
  }

  if (status === 'error' || !vitals.length) {
    return (
      <>
        <div className="page-header">
          <div>
            <div className="page-eyebrow">Playback</div>
            <h1 className="page-title">Session unavailable</h1>
            <div className="page-subtitle">{error || 'No vitals returned for this session.'}</div>
          </div>
          <div className="row gap-8">
            <button className="btn" onClick={onExit}>Back to trends</button>
          </div>
        </div>
        <div className="card" style={{ padding: 32 }}>
          <div className="text-sm text-ink-3" style={{ lineHeight: 1.6 }}>
            The playback view needs the Railway backend (the <code>/api/sessions</code> and <code>/api/vitals</code> endpoints). If the backend is offline or the session has no stored vitals, we land here. Retry once the API is back up.
          </div>
        </div>
      </>
    );
  }

  const cur = vitals[index] || vitals[0];
  const startTs = session?.start_time || vitals[0].timestamp;
  const endTs = session?.end_time || vitals[vitals.length - 1].timestamp;
  const pad = n => String(n).padStart(2, '0');
  const fmtTime = ts => {
    const d = new Date(ts * 1000);
    return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  };
  const curTime = cur ? fmtTime(cur.timestamp) : '—';
  const elapsedSec = cur ? Math.max(0, cur.timestamp - startTs) : 0;
  const totalSec = Math.max(1, endTs - startTs);

  const hrTrace = vitals.slice(0, index + 1).map(v => v.hr).filter(v => typeof v === 'number');
  const brTrace = vitals.slice(0, index + 1).map(v => v.br ?? v.rr).filter(v => typeof v === 'number');

  // Build hypnogram from epochs
  const STAGE_BY_NUM = { 0: 'deep', 1: 'rem', 2: 'light', 3: 'awake' };
  const STAGE_ALIASES = { DEEP: 'deep', REM: 'rem', LIGHT: 'light', AWAKE: 'awake' };
  const stageOf = (e) => STAGE_ALIASES[e.stage] || STAGE_BY_NUM[e.stage_num] || (typeof e.stage === 'string' ? e.stage.toLowerCase() : null);
  const durationMin = Math.max(1, Math.round((endTs - startTs) / 60));
  const hypnogram = (() => {
    if (!epochs.length) return [{ t: 0, stage: 'awake' }, { t: durationMin, stage: 'awake' }];
    const out = [];
    let last = null;
    for (const ep of epochs) {
      const t = Math.max(0, Math.round((ep.timestamp - startTs) / 60));
      const s = stageOf(ep);
      if (s && s !== last) { out.push({ t, stage: s }); last = s; }
    }
    if (!out.length || out[0].t > 0) out.unshift({ t: 0, stage: 'awake' });
    out.push({ t: durationMin, stage: out[out.length - 1].stage });
    return out;
  })();

  // Current stage at index
  const curStage = (() => {
    let match = null;
    for (const ep of epochs) {
      if (ep.timestamp > cur.timestamp + 15) break;
      match = ep;
    }
    return match ? stageOf(match) : null;
  })();

  const sessionDateLabel = new Date(startTs * 1000).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
  const cursorPct = (elapsedSec / totalSec) * 100;

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Playback · {sessionDateLabel}</div>
          <h1 className="page-title">Session replay</h1>
          <div className="page-subtitle">{fmtTime(startTs)} → {fmtTime(endTs)} · {vitals.length} samples · {epochs.length} epochs</div>
        </div>
        <div className="row gap-8">
          <button className="btn" onClick={onDownloadCSV}><Icon name="download" size={14}/> CSV</button>
          <button className="btn btn-ghost" onClick={onExit}>Back to trends</button>
        </div>
      </div>

      {/* Current state KPIs */}
      <div className="grid-4" style={{ marginBottom: 16 }}>
        <div className="card">
          <Metric label="Current HR" value={typeof cur.hr === 'number' ? Math.round(cur.hr) : '—'} unit="bpm" sub={curTime} />
        </div>
        <div className="card">
          <Metric label="Current BR" value={typeof (cur.br ?? cur.rr) === 'number' ? Math.round(cur.br ?? cur.rr) : '—'} unit="rpm" sub={cur.presence ? 'in bed' : 'absent'} />
        </div>
        <div className="card">
          <Metric label="Stage" value={curStage ? curStage.toUpperCase() : '—'} sub={`${epochs.length} epochs in session`} />
        </div>
        <div className="card">
          <Metric label="Elapsed" value={`${Math.floor(elapsedSec / 60)}m`} sub={`of ${Math.floor(totalSec / 60)}m`} />
        </div>
      </div>

      {/* Hypnogram with cursor */}
      <div className="card" style={{ marginBottom: 16 }}>
        <div className="row justify-between items-center" style={{ marginBottom: 16 }}>
          <div className="card-title" style={{ margin: 0 }}>Sleep stages</div>
          <div className="row gap-12 text-xs">
            {[{k:'awake',l:'Awake'},{k:'rem',l:'REM'},{k:'light',l:'Light'},{k:'deep',l:'Deep'}].map(s => (
              <span key={s.k} className={`stage-chip stage-${s.k}`}><span className="stage-dot" />{s.l}</span>
            ))}
          </div>
        </div>
        <div style={{ position: 'relative', paddingLeft: 44 }}>
          <Hypnogram data={hypnogram} durationMin={durationMin}
            onsetLabel={fmtTime(startTs)} wakeLabel={fmtTime(endTs)} height={140} />
          <div style={{
            position: 'absolute',
            left: `calc(44px + ${cursorPct}% * (100% - 44px) / 100)`,
            top: 0, bottom: 20,
            width: 2, background: 'var(--accent)', borderRadius: 2,
            pointerEvents: 'none',
            boxShadow: '0 0 0 3px oklch(0.55 0.12 265 / 0.15)',
          }}/>
        </div>
      </div>

      {/* Vitals sparklines */}
      <div className="grid-2" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="card-title">Heart rate (up to cursor)</div>
          <div style={{ color: 'var(--hr-color)', minHeight: 80 }}>
            {hrTrace.length ? <Sparkline data={hrTrace} height={80} color="currentColor" fill /> : <div className="text-xs text-ink-3" style={{ padding: '28px 0', textAlign: 'center' }}>No HR samples yet</div>}
          </div>
        </div>
        <div className="card">
          <div className="card-title">Breathing rate (up to cursor)</div>
          <div style={{ color: 'var(--br-color)', minHeight: 80 }}>
            {brTrace.length ? <Sparkline data={brTrace} height={80} color="currentColor" fill /> : <div className="text-xs text-ink-3" style={{ padding: '28px 0', textAlign: 'center' }}>No BR samples yet</div>}
          </div>
        </div>
      </div>

      {/* Playback control bar */}
      <div className="card" style={{ position: 'sticky', bottom: 16, marginTop: 8, padding: 16 }}>
        <div className="row items-center gap-16" style={{ flexWrap: 'wrap' }}>
          <button className="btn btn-primary" onClick={onPlayPause} style={{ minWidth: 90 }}>
            {playing ? 'Pause' : (index >= vitals.length - 1 ? 'Restart' : 'Play')}
          </button>
          <div className="row items-center gap-8">
            <span className="text-xs text-ink-3" style={{ textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>Speed</span>
            <div className="segment">
              {[1, 2, 5, 10].map(sp => (
                <button key={sp} className={speed === sp ? 'active' : ''} onClick={() => onSetSpeed(sp)}>{sp}×</button>
              ))}
            </div>
          </div>
          <div className="flex-1" style={{ minWidth: 240 }}>
            <input type="range" min={0} max={vitals.length - 1} value={index}
              onChange={e => onScrub(parseInt(e.target.value, 10))}
              style={{ width: '100%', accentColor: 'var(--accent)' }} />
            <div className="row justify-between text-xs text-ink-3 mono" style={{ marginTop: 4 }}>
              <span>{fmtTime(startTs)}</span>
              <span>{curTime}</span>
              <span>{fmtTime(endTs)}</span>
            </div>
          </div>
          <span className="text-xs text-ink-3 num" style={{ minWidth: 70, textAlign: 'right' }}>
            {index + 1} / {vitals.length}
          </span>
        </div>
      </div>
    </>
  );
}

window.PlaybackScreen = PlaybackScreen;
