// screens-doyle.jsx — Doyle chat + voice mode

const { useState: uS_a, useEffect: uE_a, useRef: uR_a } = React;

function CoachScreen({ onClose, initialMode = 'brief', context }) {
  const [mode, setMode] = uS_a(context ? 'chat' : initialMode); // 'brief' | 'chat' | 'voice'
  const data = window.APP_DATA;
  const [messages, setMessages] = uS_a(() => [...data.coachChat, ...(context ? [{
    from: 'coach', mode: 'sharp', time: 'now',
    text: context,
  }] : [])]);
  const [input, setInput] = uS_a('');
  const [tone, setTone] = uS_a('hybrid'); // sharp / mentor / zen / hybrid
  const [inBox, setInBox] = uS_a(false); // "Jack in the Box" private mode
  const [thinking, setThinking] = uS_a(false);
  const scrollRef = uR_a(null);

  uE_a(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, mode, thinking]);

  // When user toggles INTO the box, auto-send Kyle's opener
  uE_a(() => {
    if (!inBox) return;
    const lastMsg = messages[messages.length - 1];
    if (lastMsg && lastMsg.text && lastMsg.text.startsWith("Hey, this is Coach Kyle. You're now in the box")) return;
    setMessages(m => [...m, {
      from: 'coach', mode: 'mentor', time: 'now',
      text: "Hey, this is Coach Kyle. You're now in the box. What do you want to talk about?",
    }]);
  }, [inBox]);

  const send = async (text) => {
    if (!text.trim() || thinking) return;
    const userMsg = { from: 'me', text, time: 'now' };
    setMessages(m => [...m, userMsg]);
    setInput('');
    setThinking(true);

    // Pull user context for the system prompt
    let bankroll = null, sleepH = null, user = null;
    try {
      const p = JSON.parse(localStorage.getItem('plr_profile') || 'null');
      if (p && p.name) user = p.name;
    } catch (e) {}
    try {
      const br = JSON.parse(localStorage.getItem('plr_bankroll') || 'null');
      if (br && br.current != null) bankroll = br.current;
    } catch (e) {}
    if (data.sleepMood) {
      const today = data.sleepMood.last7.find(d => d.today) || data.sleepMood.last7[data.sleepMood.last7.length - 1];
      if (today && today.sleep) sleepH = today.sleep;
    }

    // Map message history to Claude API format
    const apiMessages = [...messages, userMsg]
      .filter(m => m.text)
      .map(m => ({ role: m.from === 'me' ? 'user' : 'assistant', content: m.text }));

    try {
      const r = await fetch('/api/coach', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: apiMessages, tone, inBox, bankroll, sleepH, user }),
      });
      const json = await r.json();
      const reply = json.reply || ("(Kyle's voice cut out — " + (json.error || 'try again') + ')');
      setMessages(prev => [...prev, { from: 'coach', mode: tone === 'hybrid' ? 'mentor' : tone, text: reply, time: 'now' }]);
    } catch (e) {
      setMessages(prev => [...prev, { from: 'coach', mode: 'sharp', text: "(Kyle's signal dropped. Try again.)", time: 'now' }]);
    } finally {
      setThinking(false);
    }
  };

  if (mode === 'voice') return <VoiceMode onExit={() => setMode('chat')} tone={tone}/>;
  if (mode === 'brief') return <CoachBrief data={data} onChat={() => setMode('chat')} onVoice={() => setMode('voice')} onClose={onClose}/>;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--felt)' }}>
      {/* Header */}
      <div style={{ padding: '8px 16px 12px', borderBottom: '1px solid var(--line-d)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', color: 'var(--paper-d)', fontSize: 22 }}>←</button>
        <CoachAvatar size={36} mode="sharp" talking />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="serif" style={{ fontSize: 18, lineHeight: 1 }}>Coach Kyle</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--gold)', letterSpacing: '0.1em', textTransform: 'uppercase', marginTop: 2 }}>a.k.a. Jack in the Box</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--green-bright)', letterSpacing: '0.1em', textTransform: 'uppercase', marginTop: 2 }}>● Listening · {tone}</div>
        </div>
        <button onClick={() => setInBox(b => !b)} className="mono" style={{
          all: 'unset', cursor: 'pointer', padding: '5px 9px',
          border: '1px solid ' + (inBox ? 'var(--gold)' : 'var(--line-d-2)'),
          background: inBox ? 'var(--gold)' : 'transparent',
          color: inBox ? '#0e1422' : 'var(--paper-d)',
          fontSize: 10, letterSpacing: '0.08em', fontWeight: 700, marginRight: 4,
        }}>{inBox ? '◆ IN BOX' : 'GO IN BOX'}</button>
        <button onClick={() => setMode('voice')} className="btn btn-ghost" style={{ padding: '6px 10px' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="9" y="3" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/></svg>
          <span style={{ fontSize: 11 }}>Voice</span>
        </button>
      </div>

      {/* Tone switcher */}
      <div style={{ display: 'flex', padding: '8px 16px', gap: 6, borderBottom: '1px solid var(--line-d)' }}>
        {['hybrid','sharp','mentor','zen'].map(t => (
          <button key={t} onClick={() => setTone(t)} style={{
            all: 'unset', cursor: 'pointer', padding: '4px 10px',
            border: '1px solid ' + (tone === t ? 'var(--gold)' : 'var(--line-d-2)'),
            background: tone === t ? 'var(--gold-tint)' : 'transparent',
            color: tone === t ? 'var(--gold)' : 'var(--paper-d)',
            fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase',
          }}>{t}</button>
        ))}
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            display: 'flex', gap: 10, marginBottom: 16,
            flexDirection: m.from === 'me' ? 'row-reverse' : 'row',
          }}>
            {m.from === 'coach' && <CoachAvatar size={28} mode={m.mode || 'sharp'}/>}
            <div style={{ maxWidth: '76%' }}>
              <div style={{
                padding: '10px 12px',
                background: m.from === 'me' ? 'var(--ivory-d)' : 'var(--felt-2)',
                color: m.from === 'me' ? 'var(--felt)' : 'var(--ivory-d)',
                border: m.from === 'me' ? 'none' : '1px solid var(--line-d)',
                fontFamily: m.from === 'coach' ? 'var(--font-serif)' : 'var(--font-system)',
                fontSize: m.from === 'coach' ? 16 : 14, lineHeight: 1.35,
                whiteSpace: 'pre-wrap',
              }}>
                {m.text}
              </div>
              <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)', marginTop: 4, letterSpacing: '0.08em',
                textAlign: m.from === 'me' ? 'right' : 'left' }}>
                {m.from === 'coach' && m.mode ? `D · ${m.mode.toUpperCase()} · ${m.time}` : m.time}
              </div>
            </div>
          </div>
        ))}
        {thinking && (
          <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
            <CoachAvatar size={28} mode="sharp"/>
            <div className="mono" style={{ padding: '10px 12px', background: 'var(--felt-2)', border: '1px solid var(--line-d)', color: 'var(--muted-d)', fontSize: 12 }}>
              Kyle is thinking…
            </div>
          </div>
        )}
      </div>

      {/* Quick prompts */}
      <div style={{ padding: '0 16px 8px', display: 'flex', gap: 6, overflowX: 'auto' }}>
        {['Build my WSOP schedule','I just busted','should I rebuy?','tell me about Mike Holtz vs Reece','Frozen yogurt story','I need sleep'].map(p => (
          <button key={p} onClick={() => send(p)} style={{
            all: 'unset', cursor: 'pointer', whiteSpace: 'nowrap',
            padding: '6px 10px', border: '1px solid var(--line-d-2)',
            fontSize: 12, color: 'var(--paper-d)',
          }}>{p}</button>
        ))}
      </div>

      {/* Input */}
      <div style={{ padding: '8px 12px 12px', borderTop: '1px solid var(--line-d)', display: 'flex', gap: 8 }}>
        <input
          value={input} onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && send(input)}
          placeholder="Talk to Coach Kyle…"
          style={{
            flex: 1, background: 'var(--felt-2)', border: '1px solid var(--line-d-2)',
            color: 'var(--ivory-d)', padding: '10px 12px', fontSize: 14,
            fontFamily: 'var(--font-system)', outline: 'none',
          }}
        />
        <button onClick={() => send(input)} className="btn btn-gold" style={{ padding: '10px 14px' }}>↵</button>
      </div>
    </div>
  );
}

// ─── Voice Mode ──────────────────────────────────────────────────────────
function VoiceMode({ onExit, tone }) {
  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'space-between',
      background: 'radial-gradient(circle at 50% 30%, #1a0a0a 0%, var(--felt) 60%)',
      padding: '60px 20px 40px',
    }}>
      <div style={{ textAlign: 'center' }}>
        <div className="eyebrow" style={{ color: 'var(--gold)', marginBottom: 8 }}>Voice mode · {tone}</div>
        <div className="serif" style={{ fontSize: 24, lineHeight: 1.2 }}>
          Coach Kyle is listening
        </div>
      </div>

      {/* Big breathing orb */}
      <div style={{ position: 'relative', width: 220, height: 220 }}>
        {[0,1,2].map(i => (
          <div key={i} style={{
            position: 'absolute', inset: 0, borderRadius: '50%',
            border: `1.5px solid ${i === 0 ? 'var(--red-bright)' : 'var(--gold)'}`,
            opacity: 0.6 - i * 0.18,
            animation: `mapPulse ${2 + i*0.4}s infinite`,
          }}/>
        ))}
        <div style={{
          position: 'absolute', inset: 30, borderRadius: '50%',
          background: 'radial-gradient(circle, #2a0e0e, #0a0a0b)',
          border: '1px solid var(--line-gold)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 0 60px rgba(212,175,55,0.25)',
        }}>
          <CoachAvatar size={80} mode="sharp" talking />
        </div>
      </div>

      {/* Live waveform */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, height: 40 }}>
        {[...Array(24)].map((_, i) => (
          <div key={i} style={{
            width: 3, background: 'var(--gold)',
            height: 24 + (i % 4) * 6,
            animation: `wave ${0.8 + (i % 5) * 0.1}s ${i * 0.05}s infinite`,
            transformOrigin: 'center',
          }}/>
        ))}
      </div>

      <div style={{ textAlign: 'center', maxWidth: 280 }}>
        <p className="serif" style={{ fontSize: 18, lineHeight: 1.35, color: 'var(--ivory-d)', marginBottom: 12, fontStyle: 'italic' }}>
          "Tell me about the hand. Start from preflop. Take your time — I'm not going anywhere."
        </p>
        <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)', letterSpacing: '0.15em' }}>TAP TO INTERRUPT</div>
      </div>

      <div style={{ display: 'flex', gap: 12 }}>
        <button onClick={onExit} className="btn btn-ghost">Back to chat</button>
        <button className="btn btn-red">End session</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// CoachBrief — full-screen status panel + bankroll + Kyle's read
// Opens when the user taps Coach Kyle. Serious-but-fun take based on real
// activity data. Tap "Talk to Kyle" → chat. Tap "Voice" → voice mode.
// ─────────────────────────────────────────────────────────────────────────
function CoachBrief({ data, onChat, onVoice, onClose }) {
  const sm = data.sleepMood;
  const initialBR = (() => {
    try {
      const raw = localStorage.getItem('plr_bankroll');
      if (raw) return JSON.parse(raw);
    } catch (e) {}
    return data.bankroll;
  })();
  const [br, setBr] = uS_a(initialBR);
  const [editingBR, setEditingBR] = uS_a(false);
  const [logOpen, setLogOpen] = uS_a(false);
  const [logEvent, setLogEvent] = uS_a('');
  const [logNet, setLogNet] = uS_a('');

  const persist = (next) => {
    setBr(next);
    try { localStorage.setItem('plr_bankroll', JSON.stringify(next)); } catch (e) {}
  };

  const today = sm.last7.find(d => d.today) || sm.last7[sm.last7.length - 1];
  const last3SleepAvg = (sm.last7.slice(-3).reduce((s, d) => s + (d.sleep || 0), 0) / 3).toFixed(1);
  const trendDown = sm.last7.slice(-3).every((d, i, arr) => i === 0 || d.sleep <= arr[i - 1].sleep);

  // Synthesize Kyle's read from the actual data
  const reads = [];
  if (today && today.sleep < 6) reads.push({ tone: 'sharp', text: `You slept ${today.sleep}h last night. You\'re not playing your A-game. Skip anything > $1k today.` });
  if (sm.todayHydration < 1.5) reads.push({ tone: 'sharp', text: `Hydration\'s at ${sm.todayHydration}L. Drink a full liter in the next 30 minutes or you\'ll hit a wall at level 4.` });
  if (br.delta < 0) reads.push({ tone: 'mentor', text: `You\'re down $${Math.abs(br.delta).toLocaleString()} on the trip. Lock down — only +EV spots, no live straddles, no rebuying chips you wouldn\'t buy in fresh.` });
  if (br.delta > 5000) reads.push({ tone: 'mentor', text: `You\'re up $${br.delta.toLocaleString()}. Don\'t give it back chasing a "complete the trip" win. Bank half. Play with the other half.` });
  if (trendDown) reads.push({ tone: 'zen', text: `Three straight nights of less sleep. Your body knows. One full reset day might earn you back more EV than three half-asleep sessions.` });
  if (!reads.length) reads.push({ tone: 'mentor', text: `You\'re running clean. Sleep\'s decent, hydration\'s OK, bankroll healthy. Pick the soft fields, don\'t force buy-ins above $1k unless the structure justifies it.` });

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--felt)', color: '#fff' }}>
      {/* Header */}
      <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line-d)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', color: 'var(--paper-d)', fontSize: 22 }}>←</button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="serif" style={{ fontSize: 18, lineHeight: 1 }}>Coach Kyle</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--gold)', letterSpacing: '0.1em', marginTop: 2 }}>a.k.a. Jack in the Box</div>
        </div>
        <button onClick={onVoice} className="mono" style={{
          all: 'unset', cursor: 'pointer', padding: '5px 10px',
          border: '1px solid var(--line-d-2)', color: '#fff', fontSize: 10, letterSpacing: '0.1em',
        }}>VOICE</button>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 100px' }}>
        {/* ── Kyle's take (top, hero) ── */}
        <div style={{ padding: '14px 14px', background: 'rgba(212,175,55,0.08)', border: '1px solid var(--line-gold)', marginBottom: 18 }}>
          <div className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', color: 'var(--gold)', fontWeight: 700, marginBottom: 6 }}>◆ HERE'S THE DEAL</div>
          {reads.map((r, i) => (
            <div key={i} className="serif" style={{ fontSize: 16, lineHeight: 1.3, marginBottom: i === reads.length - 1 ? 0 : 10 }}>{r.text}</div>
          ))}
        </div>

        {/* ── Bankroll ── */}
        <div style={{ marginBottom: 22 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--gold)', fontWeight: 700 }}>◆ BANKROLL</div>
            <button onClick={() => setEditingBR(!editingBR)} className="mono" style={{
              all: 'unset', cursor: 'pointer', color: 'var(--gold)',
              fontSize: 10, letterSpacing: '0.1em',
            }}>{editingBR ? 'DONE' : 'EDIT'}</button>
          </div>
          <div style={{ padding: 14, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line-d)' }}>
            {editingBR ? (
              <div style={{ display: 'grid', gap: 8 }}>
                <label className="mono" style={{ fontSize: 10, color: 'var(--muted-d)' }}>CURRENT ($)</label>
                <input type="number" value={br.current} onChange={e => persist({ ...br, current: Number(e.target.value), delta: Number(e.target.value) - br.startOfTrip })}
                  style={{ background: '#0e1422', color: '#fff', border: '1px solid var(--line-d-2)', padding: '8px 10px', fontSize: 16, fontFamily: 'var(--font-mono)' }}/>
                <label className="mono" style={{ fontSize: 10, color: 'var(--muted-d)' }}>START OF TRIP ($)</label>
                <input type="number" value={br.startOfTrip} onChange={e => persist({ ...br, startOfTrip: Number(e.target.value), delta: br.current - Number(e.target.value) })}
                  style={{ background: '#0e1422', color: '#fff', border: '1px solid var(--line-d-2)', padding: '8px 10px', fontSize: 16, fontFamily: 'var(--font-mono)' }}/>
              </div>
            ) : (
              <>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <div>
                    <div className="num serif" style={{ fontSize: 42, color: '#fff', lineHeight: 1 }}>${br.current.toLocaleString()}</div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)', letterSpacing: '0.06em', marginTop: 4 }}>CURRENT</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="num serif" style={{ fontSize: 22, color: br.delta >= 0 ? 'var(--green-bright)' : 'var(--red-bright)', lineHeight: 1 }}>
                      {br.delta >= 0 ? '+' : ''}${br.delta.toLocaleString()}
                    </div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)', letterSpacing: '0.08em', marginTop: 2 }}>TRIP P/L</div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 14, marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line-d)' }}>
                  <Stat2 label="Sessions" value={br.sessions}/>
                  <Stat2 label="Cashes" value={br.cashes}/>
                  <Stat2 label="Win rate" value={`${Math.round((br.cashes / Math.max(1, br.sessions)) * 100)}%`}/>
                </div>
                {br.biggest && (
                  <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line-d)', fontSize: 12, color: 'var(--muted-d)' }}>
                    <span className="mono" style={{ letterSpacing: '0.06em' }}>BIGGEST: </span>{br.biggest.event} <span style={{ color: 'var(--green-bright)' }}>+${br.biggest.net}</span>
                    {br.worst && <><br/><span className="mono" style={{ letterSpacing: '0.06em' }}>WORST: </span>{br.worst.event} <span style={{ color: 'var(--red-bright)' }}>{br.worst.net >= 0 ? '+' : ''}${br.worst.net}</span></>}
                  </div>
                )}
              </>
            )}
          </div>

          {/* Log a session */}
          {!editingBR && (
            <div style={{ marginTop: 10 }}>
              {!logOpen ? (
                <button onClick={() => setLogOpen(true)} className="mono" style={{
                  all: 'unset', cursor: 'pointer', display: 'block',
                  border: '1px solid var(--line-d-2)', color: '#fff',
                  padding: '10px 14px', fontSize: 11, letterSpacing: '0.1em',
                  textAlign: 'center', width: '100%',
                }}>+ LOG A SESSION</button>
              ) : (
                <div style={{ padding: 12, background: '#0e1422', border: '1px solid var(--line-d)' }}>
                  <input placeholder="Event (e.g. Wynn Mystery $400)" value={logEvent} onChange={e => setLogEvent(e.target.value)}
                    style={{ width: '100%', background: '#0e1422', color: '#fff', border: '1px solid var(--line-d-2)', padding: '8px 10px', marginBottom: 8, boxSizing: 'border-box', fontSize: 13 }}/>
                  <input placeholder="Net $ (positive for cash, negative for loss)" type="number" value={logNet} onChange={e => setLogNet(e.target.value)}
                    style={{ width: '100%', background: '#0e1422', color: '#fff', border: '1px solid var(--line-d-2)', padding: '8px 10px', marginBottom: 10, boxSizing: 'border-box', fontSize: 13 }}/>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button onClick={() => { setLogOpen(false); setLogEvent(''); setLogNet(''); }} className="mono" style={{
                      all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center', padding: '8px',
                      border: '1px solid var(--line-d-2)', color: 'var(--muted-d)', fontSize: 11,
                    }}>CANCEL</button>
                    <button onClick={() => {
                      const net = Number(logNet) || 0;
                      const next = {
                        ...br,
                        current: br.current + net,
                        delta: (br.current + net) - br.startOfTrip,
                        sessions: br.sessions + 1,
                        cashes: br.cashes + (net > 0 ? 1 : 0),
                      };
                      persist(next);
                      setLogOpen(false); setLogEvent(''); setLogNet('');
                    }} className="mono" style={{
                      all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center', padding: '8px',
                      background: 'var(--gold)', color: '#0e1422', fontSize: 11, fontWeight: 700,
                    }}>SAVE SESSION</button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* ── Today's status ── */}
        <div style={{ marginBottom: 22 }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--gold)', fontWeight: 700, marginBottom: 8 }}>◆ TODAY</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            <StatBox label="SLEEP" value={`${today && today.sleep ? today.sleep + 'h' : '—'}`} sub={trendDown ? 'trending down' : `3-day avg ${last3SleepAvg}h`} warn={today && today.sleep < 6}/>
            <StatBox label="HYDRATION" value={`${sm.todayHydration}L`} sub="goal: 3L" warn={sm.todayHydration < 1.5}/>
            <StatBox label="MOOD" value={`${sm.todayMood}/10`} sub="self-reported" warn={sm.todayMood < 5}/>
          </div>
          <div style={{ marginTop: 10, padding: '10px 12px', background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line-d)' }}>
            <span className="mono" style={{ fontSize: 10, color: 'var(--muted-d)', letterSpacing: '0.06em' }}>FUEL: </span>
            <span style={{ fontSize: 13 }}>{sm.todayFood}</span>
          </div>
        </div>

        {/* ── 7-day sleep ── */}
        <div style={{ marginBottom: 22 }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--gold)', fontWeight: 700, marginBottom: 8 }}>◆ LAST 7 NIGHTS</div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end', height: 80 }}>
            {sm.last7.map(d => {
              const h = Math.max(6, (d.sleep || 0) * 9);
              const color = d.sleep >= 7 ? 'var(--green-bright)' : d.sleep >= 6 ? 'var(--gold)' : 'var(--red-bright)';
              return (
                <div key={d.day} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
                  <div style={{ width: '100%', height: h, background: color, opacity: d.today ? 1 : 0.7 }}/>
                  <div className="mono" style={{ fontSize: 9, color: d.today ? 'var(--gold)' : 'var(--muted-d)', letterSpacing: '0.05em' }}>{d.day.toUpperCase()}</div>
                  <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)' }}>{d.sleep ? d.sleep.toFixed(1) : '—'}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Sticky bottom — chat starter */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 14, background: 'rgba(14,20,34,0.95)', borderTop: '1px solid var(--line-gold)', backdropFilter: 'blur(12px)' }}>
        <button onClick={onChat} style={{
          all: 'unset', cursor: 'pointer', display: 'block',
          background: 'var(--gold)', color: '#0e1422', padding: '14px',
          textAlign: 'center', width: '100%',
          fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase',
        }}>◆ Talk to Coach Kyle</button>
      </div>
    </div>
  );
}

function StatBox({ label, value, sub, warn }) {
  return (
    <div style={{ padding: 10, background: warn ? 'rgba(200,49,43,0.12)' : 'rgba(255,255,255,0.04)', border: '1px solid ' + (warn ? 'rgba(200,49,43,0.3)' : 'var(--line-d)') }}>
      <div className="mono" style={{ fontSize: 9, color: warn ? 'var(--red-bright)' : 'var(--muted-d)', letterSpacing: '0.1em' }}>{label}</div>
      <div className="num serif" style={{ fontSize: 22, color: '#fff', lineHeight: 1, marginTop: 4 }}>{value}</div>
      {sub && <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)', letterSpacing: '0.05em', marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function Stat2({ label, value }) {
  return (
    <div style={{ flex: 1 }}>
      <div className="num serif" style={{ fontSize: 18, color: '#fff', lineHeight: 1 }}>{value}</div>
      <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)', letterSpacing: '0.06em', marginTop: 2 }}>{label.toUpperCase()}</div>
    </div>
  );
}

Object.assign(window, { CoachScreen, VoiceMode, CoachBrief });
