// screens-friends.jsx — Friends list + Mind (Sleep & Mood) + Bustout flow

const { useState: uS_f, useEffect: uE_f } = React;

function FriendsScreen() {
  const friends = window.APP_DATA.friends;
  const [view, setView] = uS_f('list'); // 'list' | 'map'
  const alive = friends.filter(f => f.status === 'alive' || f.status === 'on_break');
  const busted = friends.filter(f => f.status === 'busted');

  return (
    <div style={{ height: '100%', overflowY: 'auto', paddingBottom: 100 }}>
      <AppHeader eyebrow="The crew" title="Friends" right={
        <div style={{ display: 'flex', border: '1px solid var(--line-d-2)' }}>
          {['list','map'].map(v => (
            <button key={v} onClick={() => setView(v)} style={{
              all: 'unset', cursor: 'pointer', padding: '6px 10px',
              background: view === v ? 'var(--ivory-d)' : 'transparent',
              color: view === v ? 'var(--felt)' : 'var(--paper-d)',
              fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
            }}>{v}</button>
          ))}
        </div>
      }/>

      {view === 'map' ? (
        <FriendsMap friends={friends}/>
      ) : (
        <>
          <div style={{ padding: '8px 20px 4px' }}>
            <div className="section-num" style={{ color: 'var(--green-bright)' }}>● ALIVE · {alive.length}</div>
          </div>
          {alive.map(f => <FriendRow key={f.id} f={f}/>)}
          <div style={{ padding: '24px 20px 4px' }}>
            <div className="section-num" style={{ color: 'var(--red-bright)' }}>● BUSTED · {busted.length}</div>
          </div>
          {busted.map(f => <FriendRow key={f.id} f={f}/>)}
        </>
      )}
    </div>
  );
}

function FriendRow({ f }) {
  const stackRatio = f.avg ? f.chips / f.avg : 0;
  return (
    <div style={{ padding: '14px 20px', borderTop: '1px solid var(--line-d)', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <div style={{
        width: 38, height: 38, borderRadius: '50%',
        background: 'var(--felt-3)', border: `1.5px solid ${f.status === 'alive' ? 'var(--green-bright)' : f.status === 'busted' ? 'var(--red-bright)' : 'var(--amber-c)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, flexShrink: 0,
      }}>{f.avatar}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 2 }}>
          <div className="serif" style={{ fontSize: 18, lineHeight: 1 }}>{f.name}</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)' }}>{f.handle}</div>
        </div>
        <div style={{ fontSize: 13, color: 'var(--paper-d)', marginBottom: 4 }}>{f.where}</div>
        {f.status === 'alive' && (
          <div className="mono" style={{ fontSize: 11, color: 'var(--gold)' }}>
            {(f.chips/1000).toFixed(1)}k chips · {stackRatio > 1 ? '+' : ''}{Math.round((stackRatio - 1) * 100)}% vs avg · {f.table}
          </div>
        )}
        {f.status === 'on_break' && (
          <div className="mono" style={{ fontSize: 11, color: 'var(--amber-c)' }}>
            ON BREAK · {(f.chips/1000).toFixed(1)}k · {f.table}
          </div>
        )}
        {f.status === 'busted' && (
          <div className="mono" style={{ fontSize: 11, color: 'var(--red-bright)' }}>
            {f.lastResult}
          </div>
        )}
        <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)', marginTop: 4 }}>{f.lastSeen}</div>
      </div>
      {f.status === 'alive' && (
        <StackBar ratio={stackRatio}/>
      )}
    </div>
  );
}

function StackBar({ ratio }) {
  const pct = Math.min(200, Math.max(10, ratio * 100));
  const color = ratio > 1.2 ? 'var(--green-bright)' : ratio > 0.7 ? 'var(--gold)' : 'var(--red-bright)';
  return (
    <div style={{ width: 60, flexShrink: 0 }}>
      <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)', textAlign: 'right', marginBottom: 3 }}>STACK</div>
      <div style={{ height: 4, background: 'var(--felt-3)', position: 'relative' }}>
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${Math.min(100, pct/2)}%`, background: color }}/>
        <div style={{ position: 'absolute', left: '50%', top: -2, bottom: -2, width: 1, background: 'var(--paper-d)', opacity: 0.4 }}/>
      </div>
    </div>
  );
}

function FriendsMap({ friends }) {
  return (
    <div style={{ margin: '12px 20px', height: 460, position: 'relative',
      background: 'linear-gradient(180deg, #0d0d10, #08080a)',
      border: '1px solid var(--line-d)', overflow: 'hidden',
    }}>
      <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0, opacity: 0.18 }}>
        {[...Array(12)].map((_,i) => <line key={'h'+i} x1="0" x2="100%" y1={`${i*8.33}%`} y2={`${i*8.33}%`} stroke="rgba(212,175,55,0.4)" strokeWidth="0.5" strokeDasharray="2 4"/>)}
      </svg>
      <div style={{
        position: 'absolute', left: '50%', top: '4%', bottom: '4%', width: 1,
        background: 'linear-gradient(180deg, transparent, var(--gold) 10%, var(--gold) 90%, transparent)',
        transform: 'translateX(-50%) rotate(-8deg)',
      }}/>
      <div className="mono" style={{ position: 'absolute', top: 8, right: 12, fontSize: 9, color: 'var(--gold)', letterSpacing: '0.15em' }}>THE STRIP</div>

      {friends.map((f, i) => {
        const positions = [
          { x: 38, y: 50 }, { x: 62, y: 52 }, { x: 38, y: 18 },
          { x: 38, y: 50 }, { x: 62, y: 8 },  { x: 38, y: 50 },
        ];
        const pos = positions[i] || { x: 50, y: 50 };
        return (
          <div key={f.id} style={{ position: 'absolute', left: `${pos.x}%`, top: `${pos.y}%`, transform: 'translate(-50%,-50%)' }}>
            <FriendDot friend={f} x={50} y={50}/>
            <div className="mono" style={{
              position: 'absolute', top: '110%', left: '50%', transform: 'translateX(-50%)',
              fontSize: 9, color: f.status === 'alive' ? 'var(--green-bright)' : 'var(--red-bright)',
              whiteSpace: 'nowrap', marginTop: 6,
            }}>{f.name} · {f.status === 'alive' ? `${(f.chips/1000).toFixed(0)}k` : 'OUT'}</div>
          </div>
        );
      })}
      <div style={{ position: 'absolute', left: '50%', top: '56%', transform: 'translate(-50%,-50%)' }}>
        <div style={{
          width: 18, height: 18, borderRadius: '50%',
          background: 'var(--ivory-d)', boxShadow: '0 0 0 2px var(--ivory-d), 0 0 16px rgba(255,255,255,0.4)',
        }}/>
        <div className="mono" style={{ position: 'absolute', top: '110%', left: '50%', transform: 'translateX(-50%)',
          fontSize: 9, color: 'var(--ivory-d)', whiteSpace: 'nowrap', marginTop: 6 }}>YOU</div>
      </div>
    </div>
  );
}

// ─── Mind (Sleep & Mood) ─────────────────────────────────────────────────
function MindScreen({ onCoach, onBack }) {
  const sm = window.APP_DATA.sleepMood;
  const [mood, setMood] = uS_f(sm.todayMood);

  return (
    <div style={{ height: '100%', overflowY: 'auto', paddingBottom: 100 }}>
      {onBack
        ? <SubHeader title="Mind" eyebrow="Sleep · mood · body" onBack={onBack}/>
        : <AppHeader eyebrow="Sleep · mood · body" title="Mind"/>
      }

      <div style={{ padding: '0 20px 4px' }}>
        <div className="card" style={{ background: 'linear-gradient(135deg, rgba(212,175,55,0.08), transparent)', borderColor: 'var(--line-gold)' }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <CoachAvatar size={32} mode="zen"/>
            <div>
              <div className="eyebrow" style={{ color: 'var(--gold)', marginBottom: 4 }}>Kyle's read</div>
              <div className="serif" style={{ fontSize: 17, lineHeight: 1.3 }}>{sm.coachRead}</div>
              <button onClick={onCoach} style={{ all: 'unset', cursor: 'pointer', marginTop: 8,
                fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--gold)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                Talk it out →
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Sleep chart */}
      <div style={{ padding: '24px 20px 0' }}>
        <div className="section-num">01 · LAST 7 NIGHTS</div>
        <h2 className="serif" style={{ fontSize: 26, marginTop: 2, marginBottom: 16 }}>Sleep & mood</h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6, marginBottom: 8 }}>
          {sm.last7.map(d => (
            <div key={d.day} style={{ textAlign: 'center' }}>
              <div style={{ height: 80, display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
                <div style={{
                  width: '70%', height: `${(d.sleep/9)*100}%`,
                  background: d.today ? 'var(--gold)' : d.sleep < 6 ? 'var(--red-bright)' : 'var(--paper-d)',
                  opacity: d.today ? 1 : 0.55,
                }}/>
              </div>
              <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)', marginTop: 4 }}>{d.day}</div>
              <div className="mono" style={{ fontSize: 11, color: d.today ? 'var(--gold)' : 'var(--paper-d)', fontWeight: 500 }}>{d.sleep}h</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--muted-d)' }}>AVG · 6.1h</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--red-bright)' }}>↓ Below your 7.2h baseline</div>
        </div>
      </div>

      {/* Mood today */}
      <div style={{ padding: '24px 20px 0' }}>
        <div className="section-num">02 · CHECK-IN</div>
        <h2 className="serif" style={{ fontSize: 26, marginTop: 2, marginBottom: 12 }}>How's your head?</h2>
        <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
          {[1,2,3,4,5,6,7,8,9,10].map(n => (
            <button key={n} onClick={() => setMood(n)} style={{
              all: 'unset', cursor: 'pointer', flex: 1, height: 38,
              border: '1px solid ' + (mood === n ? 'var(--gold)' : 'var(--line-d-2)'),
              background: mood === n ? 'var(--gold)' : 'transparent',
              color: mood === n ? 'var(--felt)' : 'var(--paper-d)',
              fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 500,
              textAlign: 'center',
            }}>{n}</button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div className="card">
            <div className="eyebrow" style={{ marginBottom: 6 }}>Today's fuel</div>
            <div className="serif" style={{ fontSize: 16, lineHeight: 1.2 }}>{sm.todayFood}</div>
            <button className="btn btn-ghost" style={{ marginTop: 10, padding: '6px 10px', fontSize: 11, width: '100%' }}>+ Log a meal</button>
          </div>
          <div className="card">
            <div className="eyebrow" style={{ marginBottom: 6 }}>Hydration</div>
            <div className="serif" style={{ fontSize: 16 }}>{sm.todayHydration} L</div>
            <div style={{ height: 4, background: 'var(--felt-3)', marginTop: 10 }}>
              <div style={{ height: '100%', width: `${sm.todayHydration*40}%`, background: 'var(--signal, #4a90e2)' }}/>
            </div>
          </div>
        </div>
      </div>

      {/* Doyle nudges */}
      <div style={{ padding: '24px 20px 0' }}>
        <div className="section-num">03 · NUDGES</div>
        <h2 className="serif" style={{ fontSize: 26, marginTop: 2, marginBottom: 12 }}>From Kyle, today</h2>
        {[
          { time: '11:30 AM', text: 'You\'re yawning at the felt. Eat something with protein in the next 20 min.', mode: 'sharp' },
          { time: '9:15 AM',  text: 'Five hours isn\'t enough. We\'re talking before you sit at any $1k+ table.', mode: 'mentor' },
          { time: 'Yesterday', text: 'You played 11 hours. That\'s the third 10+ session this week. Tomorrow we walk.', mode: 'zen' },
        ].map((n, i) => (
          <div key={i} style={{ padding: '12px 0', borderTop: '1px solid var(--line-d)', display: 'flex', gap: 12 }}>
            <CoachAvatar size={24} mode={n.mode}/>
            <div style={{ flex: 1 }}>
              <div className="serif" style={{ fontSize: 15, lineHeight: 1.3 }}>{n.text}</div>
              <div className="mono" style={{ fontSize: 9, color: 'var(--muted-d)', marginTop: 4, letterSpacing: '0.08em' }}>
                {n.time.toUpperCase()} · {n.mode.toUpperCase()}
              </div>
            </div>
          </div>
        ))}
      </div>

      <ResponsibleFooter/>
    </div>
  );
}

Object.assign(window, { FriendsScreen, MindScreen });
