// screens-draft.jsx — Fantasy Draft Room + Sign-in
// Snake draft of poker pros. Pre-populated pool + custom players + Hendon Mob links.

const { useState: uS_d, useEffect: uE_d, useRef: uR_d } = React;

// ============================================================================
// Pre-populated player pool
// ============================================================================
// $ cost = projected total points ceiling (used for cap-style budget)
// hm = Hendon Mob slug for the "verify real results" link
// tier = S (legends), A (top pros), B (regulars), C (locals/dark horses)
const POOL_DEFAULT = [
  // S-TIER
  { id: 'p_neg',   name: 'Daniel Negreanu',   cost: 95, tier: 'S', tag: 'Mixed/NLH', hm: '17765',  bio: 'PokerGO Tour. Forever wired.' },
  { id: 'p_hell',  name: 'Phil Hellmuth',     cost: 88, tier: 'S', tag: 'NLH/Bracelet', hm: '5436', bio: '17 bracelets. The Brat hunts more.' },
  { id: 'p_ivey',  name: 'Phil Ivey',         cost: 92, tier: 'S', tag: 'High Roller', hm: '14601', bio: 'Returns when the games are big.' },
  { id: 'p_deeb',  name: 'Shaun Deeb',        cost: 90, tier: 'S', tag: 'Workhorse',   hm: '36989', bio: 'Plays everything. Cashes everything.' },
  { id: 'p_kenney', name: 'Bryn Kenney',      cost: 86, tier: 'S', tag: 'High Roller', hm: '49963', bio: 'All-time money leader. High stakes only.' },
  { id: 'p_chid',   name: 'Stephen Chidwick', cost: 84, tier: 'S', tag: 'High Roller', hm: '67225', bio: 'Mixed-games threat at every super-high-roller.' },

  // A-TIER
  { id: 'p_koon',   name: 'Jason Koon',       cost: 78, tier: 'A', tag: 'High Roller', hm: '17170', bio: 'Triton regular. Cool under fire.' },
  { id: 'p_bonomo', name: 'Justin Bonomo',    cost: 76, tier: 'A', tag: 'Tournament',  hm: '60427', bio: 'Won the $1M Big One. Plays mostly mid+high.' },
  { id: 'p_cates',  name: 'Daniel Cates',     cost: 70, tier: 'A', tag: 'Mixed/Costume', hm: '171605', bio: 'PLO sicko. Drops a costume final table per series.' },
  { id: 'p_polk',   name: 'Doug Polk',        cost: 65, tier: 'A', tag: 'Heads-Up/PLO', hm: '109840', bio: 'Selectively plays. When in, threat.' },
  { id: 'p_seidel', name: 'Erik Seidel',      cost: 72, tier: 'A', tag: 'Mixed',        hm: '6759',   bio: '9 bracelets. Plays everything quietly.' },
  { id: 'p_mateos', name: 'Adrian Mateos',    cost: 74, tier: 'A', tag: 'PLO/NLH',      hm: '171605', bio: 'Spanish menace. 3 cashes a week minimum.' },
  { id: 'p_jorstad', name: 'Espen Jorstad',   cost: 68, tier: 'A', tag: 'Main Event',   hm: '286049', bio: 'Reigning Main Event mindset. Deep runs.' },
  { id: 'p_foxen',  name: 'Kristen Foxen',    cost: 66, tier: 'A', tag: 'Mixed',        hm: '108937', bio: 'Multi-format. Cashes consistently.' },
  { id: 'p_galfond', name: 'Phil Galfond',    cost: 64, tier: 'A', tag: 'PLO',          hm: '8459',   bio: 'PLO god. Rare WSOP appearances.' },
  { id: 'p_hastings', name: 'Brian Hastings', cost: 62, tier: 'A', tag: 'Mixed',        hm: '99413',  bio: 'Mixed games or bust. Bracelet threat.' },

  // B-TIER (workhorses + good prices)
  { id: 'p_ausmus', name: 'Jeremy Ausmus',    cost: 54, tier: 'B', tag: 'Tournament',   hm: '17107',  bio: 'Quiet grinder, multiple bracelets.' },
  { id: 'p_mckeehen', name: 'Joe McKeehen',   cost: 52, tier: 'B', tag: 'NLH',          hm: '171605', bio: 'Former Main Event winner. Aggressive.' },
  { id: 'p_kessler', name: 'Allen Kessler',   cost: 38, tier: 'B', tag: 'Volume',       hm: '8541',   bio: 'Plays literally every event. The Chainsaw.' },
  { id: 'p_dunst',  name: 'Tony Dunst',       cost: 46, tier: 'B', tag: 'NLH',          hm: '34316',  bio: 'WPT regular. Solid live read.' },
  { id: 'p_robl',   name: 'Andrew Robl',      cost: 44, tier: 'B', tag: 'Live Cash',    hm: '60412',  bio: 'High-stakes live. Selective tournaments.' },
  { id: 'p_marchese', name: 'Tom Marchese',   cost: 50, tier: 'B', tag: 'Tournament',   hm: '67224',  bio: 'Big tournament threat all series.' },
  { id: 'p_dwan',   name: 'Tom Dwan',         cost: 48, tier: 'B', tag: 'Wild Card',    hm: '15193',  bio: 'May show, may not. If he plays, you score.' },
  { id: 'p_engel',  name: 'Ari Engel',        cost: 40, tier: 'B', tag: 'Volume',       hm: '147466', bio: 'Mr. Volume. Tons of small cashes.' },
  { id: 'p_jaka',   name: 'Faraz Jaka',       cost: 42, tier: 'B', tag: 'Tournament',   hm: '5870',   bio: 'Volume play. Cashes show up.' },
  { id: 'p_konnikova', name: 'Maria Konnikova',cost: 36, tier: 'B', tag: 'Writer/NLH',  hm: '460268', bio: 'Author. Plays a focused calendar.' },

  // C-TIER (locals / dark horses / cheap)
  { id: 'p_kyle',   name: 'Kyle "Jack in the Box" Miholich', cost: 22, tier: 'C', tag: 'Wild Card', hm: '389470', bio: 'Coach Kyle. Plays Main Event in a giant mascot head.' },
  { id: 'p_holtz',  name: 'Mike Holtz',       cost: 28, tier: 'C', tag: 'Local Vegas',  hm: '171605', bio: 'Vegas local. Feud generator.' },
  { id: 'p_hawkins',name: 'Reece Hawkins',    cost: 30, tier: 'C', tag: 'Mid-Stakes',   hm: '171605', bio: 'ICM specialist. Final tables.' },
  { id: 'p_tilly',  name: 'Jennifer Tilly',   cost: 24, tier: 'C', tag: 'Celeb',        hm: '14148',  bio: 'Plays select events. Always a story.' },
];

// ============================================================================
// DraftRoom screen
// ============================================================================
function DraftRoomScreen({ onClose, onComplete }) {
  // ─── Config ──────────────────────────────────────────────────────────
  const [step, setStep] = uS_d('setup'); // setup | drafting | done
  const [teamCount, setTeamCount] = uS_d(8);
  const [rosterSize, setRosterSize] = uS_d(5);
  const [budget, setBudget] = uS_d(300);
  const [myTeamName, setMyTeamName] = uS_d('Your Team');
  const [otherTeams, setOtherTeams] = uS_d(['Coach K\'s Crushers','River Rats','Tilt City','Pocket Aces','Felt Sharks','Dead Money','The Donks']);

  // ─── Draft state ─────────────────────────────────────────────────────
  const [pool, setPool] = uS_d(POOL_DEFAULT);
  const [customName, setCustomName] = uS_d('');
  const [customCost, setCustomCost] = uS_d(40);
  const [picks, setPicks] = uS_d([]); // [{ round, slot, teamIdx, playerId }]
  const [filter, setFilter] = uS_d('all'); // all | S | A | B | C

  const allTeams = [myTeamName, ...otherTeams.slice(0, teamCount - 1)];
  const myIdx = 0;
  const totalPicks = teamCount * rosterSize;
  const currentPickIdx = picks.length;
  const round = Math.floor(currentPickIdx / teamCount) + 1;
  const slotInRound = currentPickIdx % teamCount;
  // Snake: odd rounds 0..N-1, even rounds N-1..0
  const teamOnClock = round % 2 === 1 ? slotInRound : (teamCount - 1 - slotInRound);
  const onClockTeam = allTeams[teamOnClock];
  const isMyTurn = teamOnClock === myIdx;

  const draftedIds = new Set(picks.map(p => p.playerId));
  const availablePool = pool.filter(p => !draftedIds.has(p.id) && (filter === 'all' || p.tier === filter));

  const myRoster = picks.filter(p => p.teamIdx === myIdx).map(p => pool.find(pl => pl.id === p.playerId)).filter(Boolean);
  const myBudgetSpent = myRoster.reduce((s, p) => s + (p?.cost || 0), 0);
  const myBudgetLeft = budget - myBudgetSpent;

  // ─── Auto-draft for other teams ──────────────────────────────────────
  uE_d(() => {
    if (step !== 'drafting' || isMyTurn || currentPickIdx >= totalPicks) return;
    const t = setTimeout(() => {
      // Each AI team picks roughly by cost (best available, with some noise)
      const teamRoster = picks.filter(p => p.teamIdx === teamOnClock).map(p => pool.find(pl => pl.id === p.playerId)).filter(Boolean);
      const teamSpent = teamRoster.reduce((s, p) => s + p.cost, 0);
      const teamLeft = budget - teamSpent;
      const picksLeftForTeam = rosterSize - teamRoster.length;
      const maxThisPick = picksLeftForTeam > 1 ? teamLeft - (picksLeftForTeam - 1) * 20 : teamLeft;
      const affordable = pool.filter(p => !draftedIds.has(p.id) && p.cost <= maxThisPick);
      const candidates = affordable.sort((a, b) => b.cost - a.cost).slice(0, 4);
      if (!candidates.length) {
        // Take cheapest available
        const cheap = pool.filter(p => !draftedIds.has(p.id)).sort((a, b) => a.cost - b.cost)[0];
        if (cheap) setPicks(prev => [...prev, { round, slot: slotInRound, teamIdx: teamOnClock, playerId: cheap.id }]);
        return;
      }
      const pick = candidates[Math.floor(Math.random() * candidates.length)];
      setPicks(prev => [...prev, { round, slot: slotInRound, teamIdx: teamOnClock, playerId: pick.id }]);
    }, 900);
    return () => clearTimeout(t);
  }, [step, currentPickIdx, isMyTurn]);

  // ─── Detect draft complete ───────────────────────────────────────────
  uE_d(() => {
    if (step === 'drafting' && currentPickIdx >= totalPicks) {
      setStep('done');
    }
  }, [currentPickIdx, step]);

  const makePick = (player) => {
    if (!isMyTurn || player.cost > myBudgetLeft) return;
    setPicks(prev => [...prev, { round, slot: slotInRound, teamIdx: myIdx, playerId: player.id }]);
  };

  const addCustomPlayer = () => {
    if (!customName.trim()) return;
    const id = 'custom_' + Date.now();
    setPool(prev => [...prev, {
      id, name: customName.trim(), cost: Number(customCost) || 40,
      tier: 'C', tag: 'Custom', hm: '', bio: 'Your pick. Track manually.',
    }]);
    setCustomName('');
  };

  // ─── Save on completion ─────────────────────────────────────────────
  uE_d(() => {
    if (step !== 'done') return;
    const result = {
      season: 'WSOP 2026',
      myTeam: myTeamName,
      roster: myRoster.map(p => ({ id: p.id, name: p.name, cost: p.cost, hm: p.hm })),
      otherTeams: allTeams.slice(1).map((name, i) => ({
        name,
        roster: picks.filter(p => p.teamIdx === i + 1).map(p => {
          const pl = pool.find(pp => pp.id === p.playerId);
          return pl ? { id: pl.id, name: pl.name, cost: pl.cost } : null;
        }).filter(Boolean),
      })),
      draftedAt: new Date().toISOString(),
    };
    try { localStorage.setItem('plr_draft_result', JSON.stringify(result)); } catch (e) {}
  }, [step]);

  // ─── Rendering ───────────────────────────────────────────────────────
  if (step === 'setup') return renderSetup();
  if (step === 'drafting') return renderDrafting();
  if (step === 'done') return renderDone();

  // ─────────────────────────────────────────────────────────────────────
  function renderSetup() {
    return (
      <div style={{ height: '100%', overflowY: 'auto', background: 'var(--felt)', color: '#fff', paddingBottom: 100 }}>
        <div style={{ padding: '64px 18px 0', background: 'linear-gradient(180deg, #0e1422 0%, #1a2236 100%)', borderBottom: '1px solid rgba(212,175,55,0.3)' }}>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', color: '#d4af37', fontSize: 22 }}>←</button>
          <div className="mono" style={{ fontSize: 9, color: '#d4af37', letterSpacing: '0.14em', fontWeight: 700, marginTop: 4 }}>◆ DRAFT ROOM</div>
          <h1 className="serif" style={{ fontSize: 28, lineHeight: 1.05, marginTop: 4 }}>Set up your league</h1>
          <p className="mono" style={{ fontSize: 11, color: '#a8b0c0', marginTop: 6, marginBottom: 20 }}>Pick a format. Snake draft. Real or made-up teams. Track real pros on Hendon Mob.</p>
        </div>

        <div style={{ padding: '20px 18px', display: 'grid', gap: 16 }}>
          <div>
            <label className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: '#a8b0c0' }}>YOUR TEAM NAME</label>
            <input value={myTeamName} onChange={e => setMyTeamName(e.target.value)} style={inputStyle}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
            <div>
              <label className="mono" style={{ fontSize: 10, color: '#a8b0c0' }}>TEAMS</label>
              <select value={teamCount} onChange={e => setTeamCount(Number(e.target.value))} style={inputStyle}>
                {[4,6,8,10,12].map(n => <option key={n} value={n}>{n}</option>)}
              </select>
            </div>
            <div>
              <label className="mono" style={{ fontSize: 10, color: '#a8b0c0' }}>ROSTER SIZE</label>
              <select value={rosterSize} onChange={e => setRosterSize(Number(e.target.value))} style={inputStyle}>
                {[3,4,5,6,7,8].map(n => <option key={n} value={n}>{n}</option>)}
              </select>
            </div>
            <div>
              <label className="mono" style={{ fontSize: 10, color: '#a8b0c0' }}>BUDGET</label>
              <select value={budget} onChange={e => setBudget(Number(e.target.value))} style={inputStyle}>
                {[200,250,300,350,400,500].map(n => <option key={n} value={n}>${n}</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: '#a8b0c0' }}>OTHER TEAMS (one per line)</label>
            <textarea value={otherTeams.join('\n')} onChange={e => setOtherTeams(e.target.value.split('\n'))}
              rows={6} style={{ ...inputStyle, fontFamily: 'var(--font-mono)', fontSize: 12 }}/>
          </div>

          <button onClick={() => setStep('drafting')} style={{
            background: '#d4af37', color: '#0e1422', border: 'none', padding: '14px 24px',
            fontWeight: 700, fontSize: 14, letterSpacing: '0.08em', textTransform: 'uppercase',
            cursor: 'pointer', marginTop: 8,
          }}>Start Draft ◆ {teamCount} teams · {teamCount * rosterSize} picks</button>
        </div>
      </div>
    );
  }

  function renderDrafting() {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--felt)', color: '#fff' }}>
        {/* Header with current pick */}
        <div style={{ padding: '54px 16px 12px', background: isMyTurn ? 'linear-gradient(180deg, #1a3a1a, #0e1422)' : 'linear-gradient(180deg, #1a2236, #0e1422)', borderBottom: '1px solid rgba(212,175,55,0.3)' }}>
          <button onClick={onClose} style={{ all: 'unset', cursor: 'pointer', color: '#d4af37', fontSize: 20 }}>← Exit</button>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
            <div>
              <div className="mono" style={{ fontSize: 9, color: '#d4af37', letterSpacing: '0.14em' }}>ROUND {round} · PICK {currentPickIdx + 1} / {totalPicks}</div>
              <div className="serif" style={{ fontSize: 22, marginTop: 2 }}>{isMyTurn ? 'You\'re on the clock' : `${onClockTeam} is picking…`}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="mono" style={{ fontSize: 9, color: '#a8b0c0', letterSpacing: '0.12em' }}>YOUR BUDGET</div>
              <div className="num serif" style={{ fontSize: 22, color: myBudgetLeft >= 0 ? '#d4af37' : '#d63b32' }}>${myBudgetLeft}</div>
            </div>
          </div>
        </div>

        {/* Filter pills */}
        <div style={{ display: 'flex', gap: 6, padding: '10px 16px', borderBottom: '1px solid var(--line-d)', overflowX: 'auto' }}>
          {['all','S','A','B','C'].map(t => (
            <button key={t} onClick={() => setFilter(t)} style={{
              all: 'unset', cursor: 'pointer', padding: '4px 12px',
              border: '1px solid ' + (filter === t ? 'var(--gold)' : 'var(--line-d-2)'),
              background: filter === t ? 'var(--gold-tint)' : 'transparent',
              color: filter === t ? 'var(--gold)' : 'var(--paper-d)',
              fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
            }}>{t === 'all' ? 'All' : `Tier ${t}`}</button>
          ))}
        </div>

        {/* Available pool */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
          {availablePool.map(p => {
            const canAfford = isMyTurn && p.cost <= myBudgetLeft;
            return (
              <div key={p.id} onClick={() => canAfford && makePick(p)} style={{
                padding: '12px 16px', borderBottom: '1px solid var(--line-d)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10,
                cursor: canAfford ? 'pointer' : 'default', opacity: canAfford ? 1 : (isMyTurn ? 0.4 : 0.7),
              }}>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className="serif" style={{ fontSize: 16 }}>{p.name}</span>
                    <span className="mono" style={{ fontSize: 9, padding: '1px 6px', background: tierColor(p.tier), color: '#0e1422', fontWeight: 700 }}>{p.tier}</span>
                  </div>
                  <div className="mono" style={{ fontSize: 10, color: '#a8b0c0', marginTop: 2 }}>{p.tag} · {p.bio}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="num serif" style={{ fontSize: 18, color: canAfford ? '#d4af37' : '#a8b0c0' }}>${p.cost}</div>
                  {p.hm && <a href={`https://pokerdb.thehendonmob.com/player.php?a=r&n=${p.hm}`} target="_blank" rel="noopener" onClick={e => e.stopPropagation()} className="mono" style={{ fontSize: 9, color: '#a8b0c0', letterSpacing: '0.08em' }}>Hendon Mob ↗</a>}
                </div>
              </div>
            );
          })}

          {/* Add custom player row */}
          <div style={{ padding: '14px 16px', background: '#0e1422', borderTop: '1px solid var(--line-d)' }}>
            <div className="mono" style={{ fontSize: 9, letterSpacing: '0.1em', color: '#a8b0c0', marginBottom: 6 }}>+ ADD A CUSTOM PLAYER</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <input placeholder="Player name" value={customName} onChange={e => setCustomName(e.target.value)} style={{ ...inputStyle, marginTop: 0, flex: 1 }}/>
              <input placeholder="$" type="number" value={customCost} onChange={e => setCustomCost(e.target.value)} style={{ ...inputStyle, marginTop: 0, width: 70 }}/>
              <button onClick={addCustomPlayer} style={{ background: '#d4af37', color: '#0e1422', border: 'none', padding: '6px 12px', cursor: 'pointer', fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700 }}>ADD</button>
            </div>
          </div>
        </div>

        {/* My roster bar */}
        <div style={{ borderTop: '1px solid rgba(212,175,55,0.3)', padding: '10px 16px', background: '#0e1422' }}>
          <div className="mono" style={{ fontSize: 9, letterSpacing: '0.1em', color: '#a8b0c0' }}>YOUR ROSTER · {myRoster.length}/{rosterSize}</div>
          <div style={{ display: 'flex', gap: 8, marginTop: 6, flexWrap: 'wrap' }}>
            {myRoster.map(p => (
              <div key={p.id} style={{ padding: '4px 8px', border: '1px solid var(--line-gold)', background: 'rgba(212,175,55,0.08)' }}>
                <span style={{ fontSize: 12 }}>{p.name}</span>
                <span className="mono" style={{ fontSize: 10, color: '#d4af37', marginLeft: 6 }}>${p.cost}</span>
              </div>
            ))}
            {Array.from({ length: rosterSize - myRoster.length }).map((_, i) => (
              <div key={'e' + i} style={{ padding: '4px 8px', border: '1px dashed var(--line-d-2)', color: '#a8b0c0', fontSize: 12 }}>—</div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  function renderDone() {
    return (
      <div style={{ height: '100%', overflowY: 'auto', background: 'var(--felt)', color: '#fff', padding: '60px 18px 100px' }}>
        <div className="mono" style={{ fontSize: 9, color: '#d4af37', letterSpacing: '0.14em' }}>◆ DRAFT COMPLETE</div>
        <h1 className="serif" style={{ fontSize: 30, marginTop: 4 }}>Your roster is locked in.</h1>
        <p className="mono" style={{ fontSize: 11, color: '#a8b0c0', marginTop: 6 }}>Tracking against real Hendon Mob results. Updates whenever your players cash live.</p>

        <div style={{ marginTop: 20 }}>
          <div className="mono" style={{ fontSize: 10, color: '#a8b0c0', letterSpacing: '0.1em' }}>{myTeamName.toUpperCase()} — ${myBudgetSpent} OF ${budget}</div>
          {myRoster.map(p => (
            <div key={p.id} style={{ padding: '12px 0', borderBottom: '1px solid var(--line-d)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <div className="serif" style={{ fontSize: 17 }}>{p.name}</div>
                <div className="num serif" style={{ fontSize: 16, color: '#d4af37' }}>${p.cost}</div>
              </div>
              <div className="mono" style={{ fontSize: 10, color: '#a8b0c0', marginTop: 2 }}>
                {p.tag}{p.hm && <> · <a href={`https://pokerdb.thehendonmob.com/player.php?a=r&n=${p.hm}`} target="_blank" rel="noopener" style={{ color: '#a8b0c0' }}>Hendon Mob ↗</a></>}
              </div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 24 }}>
          <div className="mono" style={{ fontSize: 10, color: '#a8b0c0', letterSpacing: '0.1em', marginBottom: 8 }}>OTHER TEAMS IN THE LEAGUE</div>
          {allTeams.slice(1).map((tname, ti) => {
            const ros = picks.filter(p => p.teamIdx === ti + 1).map(p => pool.find(pl => pl.id === p.playerId)).filter(Boolean);
            return (
              <details key={tname} style={{ padding: '8px 0', borderBottom: '1px solid var(--line-d)' }}>
                <summary style={{ cursor: 'pointer', listStyle: 'none' }}>
                  <span className="serif" style={{ fontSize: 15 }}>{tname}</span>
                  <span className="mono" style={{ fontSize: 10, color: '#a8b0c0', marginLeft: 8 }}>${ros.reduce((s, p) => s + p.cost, 0)}</span>
                </summary>
                <div style={{ marginTop: 6, fontSize: 12, color: '#a8b0c0' }}>
                  {ros.map(p => p.name).join(' · ')}
                </div>
              </details>
            );
          })}
        </div>

        <button onClick={() => { onComplete && onComplete(); onClose(); }} style={{
          background: '#d4af37', color: '#0e1422', border: 'none', padding: '14px 24px',
          fontWeight: 700, fontSize: 14, letterSpacing: '0.08em', textTransform: 'uppercase',
          cursor: 'pointer', marginTop: 24, width: '100%',
        }}>Back to Fantasy ◆</button>
      </div>
    );
  }
}

const inputStyle = {
  width: '100%', marginTop: 4, padding: '10px 12px', background: '#0e1422',
  color: '#fff', border: '1px solid var(--line-d-2)', borderRadius: 0,
  fontFamily: 'var(--font-body)', fontSize: 14, outline: 'none',
};

function tierColor(t) {
  return { S: '#f0d97a', A: '#d4af37', B: '#a8b0c0', C: '#737373' }[t] || '#a8b0c0';
}

// ============================================================================
// Sign-in (lightweight — email + display name, localStorage)
// ============================================================================
function SignInScreen({ onSignedIn }) {
  const [email, setEmail] = uS_d('');
  const [name, setName] = uS_d('');
  const submit = () => {
    if (!email.trim() || !name.trim()) return;
    const profile = { email: email.trim(), name: name.trim(), signedInAt: new Date().toISOString() };
    try { localStorage.setItem('plr_profile', JSON.stringify(profile)); } catch (e) {}
    onSignedIn(profile);
  };
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', background: 'var(--felt)', color: '#fff', padding: '0 24px' }}>
      <div className="mono" style={{ fontSize: 9, color: '#d4af37', letterSpacing: '0.16em' }}>◆ POKER LATE REG</div>
      <h1 className="serif" style={{ fontSize: 36, lineHeight: 1, marginTop: 8, textAlign: 'center' }}>Sign in</h1>
      <p className="mono" style={{ fontSize: 11, color: '#a8b0c0', marginTop: 10, marginBottom: 30, textAlign: 'center', maxWidth: 280 }}>
        Just a name + email so we can save your draft and your fantasy roster. No password. No spam.
      </p>
      <input placeholder="Display name" value={name} onChange={e => setName(e.target.value)} style={{ ...inputStyle, marginBottom: 10, maxWidth: 320 }}/>
      <input placeholder="Email" type="email" value={email} onChange={e => setEmail(e.target.value)} style={{ ...inputStyle, marginBottom: 16, maxWidth: 320 }}/>
      <button onClick={submit} style={{
        background: '#d4af37', color: '#0e1422', border: 'none', padding: '14px 32px',
        fontWeight: 700, fontSize: 14, letterSpacing: '0.08em', textTransform: 'uppercase',
        cursor: 'pointer', maxWidth: 320, width: '100%',
      }}>Enter Poker Late Reg ◆</button>
    </div>
  );
}

// Export
Object.assign(window, { DraftRoomScreen, SignInScreen });
