/* ═══════════════════════════════════════════════════════
   screens-game · Confirm, Session (poker table), Caixa, Result
═══════════════════════════════════════════════════════ */

/* ── Game container ─────────────────────── */
const GameScreen = () => {
  const s = useStore();
  const game = s.currentGame;
  if (!game) return null;

  // Always refresh from store games in case state changed
  const fresh = s.games.find(x => x.id === game.id) || game;
  return (
    <div className="page-enter" style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <TopBar back onBack={() => update({ currentGame: null })}
              title={fresh.name}
              subtitle={`${fmtDateFull(fresh.date)}${fresh.timeStart ? ' · ' + fresh.timeStart : ''}`}
              right={fresh.status === 'open'
                ? <span className="chip chip-neon" style={{ padding: '4px 10px' }}>
                    <span className="live-dot" style={{ width: 6, height: 6 }}/>LIVE
                  </span>
                : <span className="chip" style={{ padding: '4px 10px' }}>FECHADA</span>}/>
      <GameTabs game={fresh}/>
      {fresh.status === 'closed' ? <ResultClosedTab game={fresh}/> :
        s.gameSubTab === 'confirm' ? <ConfirmTab game={fresh}/> :
        s.gameSubTab === 'session' ? <SessionTab game={fresh}/> :
        s.gameSubTab === 'caixa'   ? <CaixaTab   game={fresh}/> :
        s.gameSubTab === 'result'  ? <ResultTab  game={fresh}/> : null}
    </div>
  );
};

const GameTabs = ({ game }) => {
  const s = useStore();
  const tabs = (game.status === 'closed') ? [{ id: 'result', i: 'chart', l: 'Resultado' }] :
    isAdmin()
      ? [
          { id: 'confirm', i: 'check',  l: 'Mesa' },
          { id: 'session', i: 'play',   l: 'Sessão' },
          { id: 'caixa',   i: 'wallet', l: 'Caixa' },
          { id: 'result',  i: 'chart',  l: 'Result.' },
        ]
      : [{ id: 'confirm', i: 'check', l: 'Mesa' }];
  return (
    <div style={{
      display: 'flex', gap: 2, padding: 4,
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 14, margin: '0 16px 14px',
    }}>
      {tabs.map(t => (
        <button key={t.id} onClick={() => update({ gameSubTab: t.id })} style={{
          flex: 1, padding: '8px 4px',
          background: s.gameSubTab === t.id ? 'linear-gradient(135deg, var(--gold) 0%, var(--gold-deep) 100%)' : 'transparent',
          color: s.gameSubTab === t.id ? '#0d0d08' : 'var(--ink-3)',
          fontSize: 11, fontWeight: 700, borderRadius: 10,
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
          transition: 'all 0.18s var(--ease)',
        }}>
          <Icon name={t.i} size={16}/>
          <span style={{ fontSize: 10 }}>{t.l}</span>
        </button>
      ))}
    </div>
  );
};

/* ── CONFIRMACAO ─────────────────────────── */
const ConfirmTab = ({ game }) => {
  const s = useStore();
  const confirmed = toArr(game.confirmedPlayers);
  const waiting = toArr(game.waitingList);
  const maxP = game.maxPlayers || 0;
  const me = confirmed.find(p => p.uid === s.userUid);
  const myWait = waiting.find(p => p.uid === s.userUid);
  const limitReached = maxP > 0 && confirmed.length >= maxP;
  const myName = getCurrentUserName();
  const iAmMens = s.mensalistasList.some(m => m === myName || nameToRankKey(m) === s.userUid);

  const confirmMe = async () => {
    const entry = { uid: s.userUid, name: myName, confirmedAt: new Date().toISOString() };
    const newConfirmed = [...confirmed, entry];
    const sess = toArr(game.sessionPlayers);
    if (!sess.find(p => p.name === myName)) sess.push(mkPlayer(myName));
    await patchGame(game.id, { confirmedPlayers: newConfirmed, sessionPlayers: sess });
    toast('Presença confirmada!');
  };
  const joinWait = async () => {
    if (myWait) return;
    const wl = [...waiting, { uid: s.userUid, name: myName, requestedAt: new Date().toISOString() }];
    await patchGame(game.id, { waitingList: wl });
    toast('Adicionado à lista de espera');
  };
  const cancelMe = async () => {
    if (!confirm('Cancelar presença?')) return;
    const newConfirmed = confirmed.filter(p => p.uid !== s.userUid);
    const sess = toArr(game.sessionPlayers).filter(p => p.name !== me.name);
    let wl = toArr(game.waitingList);
    if (wl.length > 0 && maxP > 0) {
      const promoted = wl.shift();
      newConfirmed.push({ uid: promoted.uid, name: promoted.name, confirmedAt: new Date().toISOString(), promotedFromWaiting: true });
      if (!sess.find(p => p.name === promoted.name)) sess.push(mkPlayer(promoted.name));
    }
    await patchGame(game.id, { confirmedPlayers: newConfirmed, sessionPlayers: sess, waitingList: wl });
    toast('Presença cancelada');
  };
  const leaveWait = async () => {
    if (!confirm('Sair da lista de espera?')) return;
    const wl = waiting.filter(p => p.uid !== s.userUid);
    await patchGame(game.id, { waitingList: wl });
    toast('Saiu da lista');
  };
  const adminRemove = async (uid, name) => {
    const newConfirmed = confirmed.filter(p => p.uid !== uid);
    const sess = toArr(game.sessionPlayers).filter(p => p.name !== name);
    await patchGame(game.id, { confirmedPlayers: newConfirmed, sessionPlayers: sess });
  };
  const adminPromote = async (entry) => {
    if (!confirm('Mover ' + entry.name + ' para confirmados?')) return;
    const wl = waiting.filter(p => p.uid !== entry.uid);
    const newConfirmed = [...confirmed, { uid: entry.uid, name: entry.name, confirmedAt: new Date().toISOString(), promotedFromWaiting: true }];
    const sess = toArr(game.sessionPlayers);
    if (!sess.find(p => p.name === entry.name)) sess.push(mkPlayer(entry.name));
    await patchGame(game.id, { confirmedPlayers: newConfirmed, sessionPlayers: sess, waitingList: wl });
  };

  return (
    <div className="scroll-region stagger" style={{ paddingTop: 0 }}>
      <div className="card card-gold felt-bg" style={{ padding: 18, marginBottom: 14, position: 'relative', overflow: 'hidden' }}>
        <SuitsCorner pos="tr" opacity={0.08}/>
        <div className="row" style={{ marginBottom: 12 }}>
          <span className="chip chip-neon"><span className="live-dot" style={{ width: 6, height: 6 }}/>EM ABERTO</span>
          <span className="spacer"/>
          <span className="tag">{fmtDateFull(game.date)}</span>
        </div>
        <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 26, color: 'var(--gold-1)', lineHeight: 1.05, marginBottom: 8 }}>
          {game.name}
        </div>
        <div className="col" style={{ gap: 4, fontSize: 12, color: 'var(--ink-2)' }}>
          {game.timeStart && <div className="row"><Icon name="clock" size={12}/>{game.timeStart}{game.timeEnd ? ' — ' + game.timeEnd : ''}</div>}
          {game.location && (
            <a href={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(game.location)}`} target="_blank" rel="noopener"
               className="row" style={{ color: 'var(--cyan)', textDecoration: 'none' }}>
              <Icon name="pin" size={12}/>{game.location}
            </a>
          )}
          <div className="row">
            <Icon name="users" size={12}/>
            <span>{confirmed.length}{maxP > 0 ? ' / ' + maxP : ''} confirmados</span>
            {waiting.length > 0 && <span style={{ color: 'var(--gold-1)' }}>· <Icon name="hourglass" size={11}/> {waiting.length} em espera</span>}
          </div>
          {game.notes && <div style={{ fontStyle: 'italic', color: 'var(--ink-3)', fontSize: 11, marginTop: 4 }}>{game.notes}</div>}
        </div>
      </div>

      {/* My status */}
      <div className="card" style={{
        padding: 16, marginBottom: 16, textAlign: 'center',
        background: me ? 'var(--neon-soft)' : myWait ? 'var(--gold-soft)' : 'var(--surface)',
        borderColor: me ? 'var(--neon)' : myWait ? 'var(--gold)' : 'var(--border)',
      }}>
        {me ? (
          <>
            <Icon name="check" size={32} style={{ color: 'var(--neon)', marginBottom: 6 }}/>
            <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 22, color: 'var(--neon)' }}>
              Você está dentro!
            </div>
            <button className="btn btn-ghost btn-pill" style={{ marginTop: 12 }} onClick={cancelMe}>
              Cancelar presença
            </button>
          </>
        ) : myWait ? (
          <>
            <Icon name="hourglass" size={28} style={{ color: 'var(--gold-1)', marginBottom: 6 }}/>
            <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 20, color: 'var(--gold-1)' }}>
              Lista de espera — posição {waiting.indexOf(myWait) + 1}
            </div>
            <button className="btn btn-ghost btn-pill" style={{ marginTop: 12 }} onClick={leaveWait}>
              Sair da lista
            </button>
          </>
        ) : limitReached ? (
          <>
            <Icon name="hourglass" size={28} style={{ color: 'var(--gold-1)', marginBottom: 6 }}/>
            <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 20, color: 'var(--gold-1)' }}>
              Vagas esgotadas
            </div>
            <button className="btn btn-primary" style={{ marginTop: 12 }} onClick={joinWait}>
              Entrar na lista de espera
            </button>
          </>
        ) : (
          <>
            <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 22, color: 'var(--ink)', marginBottom: 4 }}>
              {iAmMens ? 'Confirmar minha presença?' : 'Visitante — entrar na lista?'}
            </div>
            {!iAmMens && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 10 }}>Mensalistas têm prioridade na mesa.</div>}
            <button className="btn btn-primary" onClick={iAmMens ? confirmMe : joinWait} style={{ width: '100%' }}>
              <Icon name={iAmMens ? 'check' : 'hourglass'} size={16}/> {iAmMens ? 'Estou dentro' : 'Entrar na espera'}
            </button>
          </>
        )}
      </div>

      <div className="section-h">
        <h2>Confirmados</h2>
        <span className="tag">{confirmed.length}{maxP > 0 ? '/' + maxP : ''}</span>
      </div>
      {confirmed.length === 0 && (
        <div className="card" style={{ padding: 18, textAlign: 'center', color: 'var(--ink-3)' }}>
          Nenhuma confirmação ainda.
        </div>
      )}
      <div className="col stagger" style={{ gap: 6 }}>
        {confirmed.map(p => {
          const myEntry = p.uid === s.userUid;
          return (
            <div key={p.uid + p.name} className="card" style={{
              padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10,
              background: myEntry ? 'var(--gold-soft)' : 'var(--surface)',
              borderColor: myEntry ? 'var(--gold)' : 'var(--border)',
            }}>
              <Avatar name={p.name} src={getUserAvatar(p.uid || p.name)} size={32}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: myEntry ? 700 : 500, fontSize: 13, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {getDisplayName(p.name)} {myEntry && <span style={{ color: 'var(--gold-1)', fontSize: 11 }}>· você</span>}
                  {p.promotedFromWaiting && <span style={{ marginLeft: 4 }}>🔼</span>}
                </div>
              </div>
              <Icon name="check" size={16} style={{ color: 'var(--neon)' }}/>
              {isAdmin() && !myEntry && (
                <button className="topbar-icon-btn" style={{ width: 28, height: 28 }} onClick={() => adminRemove(p.uid, p.name)}>
                  <Icon name="close" size={14}/>
                </button>
              )}
            </div>
          );
        })}
      </div>

      {waiting.length > 0 && (
        <>
          <div className="section-h"><h2>Lista de espera</h2><span className="chip chip-gold">{waiting.length}</span></div>
          <div className="col" style={{ gap: 6 }}>
            {waiting.map((p, i) => (
              <div key={p.uid + p.name} className="card" style={{ padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <div className="font-mono" style={{ width: 24, textAlign: 'center', color: 'var(--gold-1)', fontWeight: 700 }}>{i + 1}º</div>
                <Avatar name={p.name} src={getUserAvatar(p.uid)} size={28}/>
                <div style={{ flex: 1, fontSize: 13 }}>{getDisplayName(p.name)}</div>
                {isAdmin() ? (
                  <>
                    <button className="btn btn-pill" style={{ background: 'var(--neon-soft)', color: 'var(--neon)', border: '1px solid var(--neon)' }}
                            onClick={() => adminPromote(p)}>
                      <Icon name="arrow-up" size={12}/>
                    </button>
                    <button className="topbar-icon-btn" style={{ width: 28, height: 28 }}
                            onClick={async () => { await patchGame(game.id, { waitingList: waiting.filter(x => x.uid !== p.uid) }); }}>
                      <Icon name="close" size={14}/>
                    </button>
                  </>
                ) : <Icon name="hourglass" size={14} style={{ color: 'var(--ink-3)' }}/>}
              </div>
            ))}
          </div>
        </>
      )}

      {isAdmin() && <AdminAddPlayer game={game} confirmed={confirmed}/>}
    </div>
  );
};

const AdminAddPlayer = ({ game, confirmed }) => {
  const s = useStore();
  const [name, setName] = useState('');
  const [sel, setSel] = useState('');
  const confirmedNames = confirmed.map(c => c.name);
  const added = new Set();
  const opts = [];
  s.allUsers.slice().sort((a, b) => (a.displayName || a.email).localeCompare(b.displayName || b.email))
    .filter(u => !u.disabled).forEach(u => {
      const disp = u.displayName || ((u.email || '').split('@')[0]);
      if (!confirmedNames.includes(disp) && !added.has(disp)) { added.add(disp); opts.push({ value: disp, label: disp }); }
    });
  s.mensalistasList.forEach(n => {
    if (!confirmedNames.includes(n) && !added.has(n)) { added.add(n); opts.push({ value: n, label: n }); }
  });
  const doAdd = async () => {
    const n = (name.trim() || sel).trim();
    if (!n) { toast('Selecione ou digite um nome', 'error'); return; }
    if (confirmedNames.includes(n)) { toast(n + ' já está confirmado', 'error'); return; }
    const entry = { uid: 'admin_' + genId().slice(0, 6), name: n, confirmedAt: new Date().toISOString(), addedByAdmin: true };
    const sess = toArr(game.sessionPlayers);
    if (!sess.find(p => p.name === n)) sess.push(mkPlayer(n));
    await patchGame(game.id, {
      confirmedPlayers: [...confirmed, entry],
      sessionPlayers: sess,
    });
    setName(''); setSel('');
    toast(n + ' adicionado');
  };
  return (
    <div className="card" style={{ padding: 12, marginTop: 12 }}>
      <div className="eyebrow" style={{ marginBottom: 8 }}>Admin · Adicionar participante</div>
      <select value={sel} onChange={e => { setSel(e.target.value); setName(''); }} className="input" style={{ marginBottom: 6 }}>
        <option value="">— Usuário cadastrado —</option>
        {opts.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      <div className="row" style={{ gap: 6 }}>
        <input className="input" value={name} onChange={e => { setName(e.target.value); setSel(''); }} placeholder="Ou digite um nome"/>
        <button className="btn btn-primary btn-pill" onClick={doAdd}><Icon name="plus" size={12}/></button>
      </div>
    </div>
  );
};

/* ── SESSION (poker table view) ────────── */
const SessionTab = ({ game }) => {
  const s = useStore();
  const players = toArr(game.sessionPlayers);
  const [activeIdx, setActiveIdx] = useState(0);
  const gv = gameValues(game);
  const totalEntries = players.reduce((s, p) => s + (p.buyins || 1), 0);
  const prize = totalEntries * gv.ret;
  const active = players[activeIdx];

  if (players.length === 0) {
    return (
      <div className="scroll-region" style={{ paddingTop: 0 }}>
        <div className="card" style={{ padding: 30, textAlign: 'center' }}>
          <Suit kind="club" size={36} style={{ color: 'var(--ink-3)', opacity: 0.4 }}/>
          <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 16, color: 'var(--ink-3)', marginTop: 10, lineHeight: 1.5 }}>
            Nenhum participante na mesa.<br/>Vá em <b>Mesa</b> para adicionar.
          </div>
          {isAdmin() && (
            <button className="btn btn-primary" onClick={() => update({ gameSubTab: 'confirm' })} style={{ marginTop: 12 }}>
              <Icon name="check" size={14}/> Ir para Mesa
            </button>
          )}
        </div>
      </div>
    );
  }

  const adjustBuyins = async delta => {
    const upd = [...players];
    upd[activeIdx] = { ...upd[activeIdx], buyins: Math.max(1, (upd[activeIdx].buyins || 1) + delta) };
    await debouncedSave(clubPath('/games/' + game.id + '.json'), { ...game, sessionPlayers: upd });
    const idx = findIdx(S.games, x => x.id === game.id);
    if (idx >= 0) S.games[idx].sessionPlayers = upd;
    if (S.currentGame?.id === game.id) S.currentGame.sessionPlayers = upd;
    notify();
  };
  const toggleBust = async () => {
    const upd = [...players];
    const cur = upd[activeIdx];
    if (cur.bustedAt) upd[activeIdx] = { ...cur, bustedAt: null };
    else upd[activeIdx] = { ...cur, bustedAt: (game.bustOrder || 0) + 1 };
    const patch = { sessionPlayers: upd, bustOrder: cur.bustedAt ? (game.bustOrder || 0) : (game.bustOrder || 0) + 1 };
    await patchGame(game.id, patch);
    toast(cur.bustedAt ? `${cur.name} reativado` : `${cur.name} eliminado 💀`);
  };

  return (
    <>
      <div className="row" style={{ padding: '0 16px 12px', gap: 8 }}>
        <div className="card" style={{ padding: '8px 12px', flex: 1, textAlign: 'center' }}>
          <div className="tag" style={{ fontSize: 9 }}>ENTRADAS</div>
          <div className="font-mono" style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink)' }}>
            <Ticker value={totalEntries}/>
          </div>
        </div>
        <div className="card" style={{ padding: '8px 12px', flex: 1, textAlign: 'center' }}>
          <div className="tag" style={{ fontSize: 9 }}>CAIXA</div>
          <div className="font-mono grad-gold" style={{ fontSize: 16, fontWeight: 700 }}>
            <TickerBRL value={prize}/>
          </div>
        </div>
        <div className="card" style={{ padding: '8px 12px', flex: 1, textAlign: 'center' }}>
          <div className="tag" style={{ fontSize: 9 }}>ATIVOS</div>
          <div className="font-mono" style={{ fontSize: 16, fontWeight: 700, color: 'var(--neon)' }}>
            <Ticker value={players.filter(p => !p.bustedAt).length}/>
            <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>/{players.length}</span>
          </div>
        </div>
      </div>

      <PokerTable players={players} gv={gv} onPlayerTap={setActiveIdx} activeIdx={activeIdx}/>

      {active && (
        <div className="card card-gold anim-fade-up" style={{
          margin: '0 16px 14px', padding: 14,
          background: 'linear-gradient(135deg, var(--bg-1) 0%, var(--surface) 100%)',
        }} key={activeIdx}>
          <div className="row" style={{ marginBottom: 14 }}>
            <Avatar name={active.name} src={getUserAvatar(nameToRankKey(active.name))} size={48} ring/>
            <div style={{ flex: 1, marginLeft: 12, minWidth: 0 }}>
              <div className="row" style={{ gap: 6 }}>
                <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{getDisplayName(active.name)}</span>
                {active.bustedAt && <span className="chip chip-red" style={{ padding: '2px 8px' }}>ELIMINADO</span>}
              </div>
              <div className="row" style={{ gap: 6, fontSize: 11, color: 'var(--ink-3)', marginTop: 2, flexWrap: 'wrap' }}>
                <span>Inv:</span>
                <span className="font-mono" style={{ color: 'var(--ink-2)' }}>{fmtBRL((active.buyins || 1) * gv.cv)}</span>
                <span>·</span>
                <span>Pilha:</span>
                <span className="font-mono" style={{ color: 'var(--gold-1)' }}>{fmtBRL(chipValue(active.chips || {}))}</span>
              </div>
            </div>
          </div>
          {isAdmin() && (
            <div className="row" style={{ background: 'var(--bg-2)', padding: 10, borderRadius: 12, gap: 12 }}>
              <div style={{ flex: 1 }}>
                <div className="tag" style={{ fontSize: 9 }}>BUY-INS / REBUYS</div>
                <div className="row" style={{ gap: 8, marginTop: 4 }}>
                  <button onClick={() => adjustBuyins(-1)} style={{
                    width: 32, height: 32, borderRadius: 10,
                    background: 'var(--red-soft)', color: 'var(--red-1)',
                    border: '1px solid var(--red)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}><Icon name="minus" size={16}/></button>
                  <div className="font-mono" style={{ fontSize: 28, fontWeight: 800, color: 'var(--gold-1)', minWidth: 40, textAlign: 'center' }}>
                    {active.buyins || 1}
                  </div>
                  <button onClick={() => adjustBuyins(1)} style={{
                    width: 32, height: 32, borderRadius: 10,
                    background: 'var(--neon-soft)', color: 'var(--neon)',
                    border: '1px solid var(--neon)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}><Icon name="plus" size={16}/></button>
                </div>
              </div>
              <div style={{ width: 1, alignSelf: 'stretch', background: 'var(--border)' }}/>
              <button onClick={toggleBust} className="btn" style={{
                background: active.bustedAt ? 'var(--neon-soft)' : 'var(--red-soft)',
                color: active.bustedAt ? 'var(--neon)' : 'var(--red-1)',
                border: `1px solid ${active.bustedAt ? 'var(--neon)' : 'var(--red)'}`,
                flexDirection: 'column', gap: 2, padding: '10px 16px',
              }}>
                <Icon name={active.bustedAt ? 'arrow-up' : 'skull'} size={18}/>
                <span style={{ fontSize: 10 }}>{active.bustedAt ? 'Reativar' : 'Eliminar'}</span>
              </button>
            </div>
          )}
        </div>
      )}
    </>
  );
};

/* ── Poker table view ──────────────────── */
const PokerTable = ({ players, gv, onPlayerTap, activeIdx }) => {
  const arrangement = players.slice(0, 10);
  const positions = n => {
    const pts = [];
    for (let i = 0; i < n; i++) {
      const angle = (i / n) * Math.PI * 2 - Math.PI / 2;
      const a = 84, b = 78;
      pts.push({ x: 50 + (a * Math.cos(angle)) / 2, y: 50 + (b * Math.sin(angle)) / 2 });
    }
    return pts;
  };
  const slots = positions(arrangement.length);
  const totalChipsInPlay = arrangement.reduce((s, p) => s + chipValue(p.chips || {}), 0);
  return (
    <div style={{ position: 'relative', aspectRatio: '1.25', margin: '0 16px 14px' }}>
      <div style={{
        position: 'absolute', inset: '14% 8% 14% 8%',
        background: 'radial-gradient(ellipse at center, var(--felt) 0%, var(--felt-deep) 70%, #061309 100%)',
        borderRadius: '50%',
        border: '4px solid #2a1810',
        boxShadow: '0 12px 40px rgba(0,0,0,0.7), inset 0 0 60px rgba(0,0,0,0.6)',
      }}>
        <div style={{
          position: 'absolute', inset: 10, borderRadius: '50%',
          border: '1px solid rgba(212,175,55,0.2)',
          background: 'radial-gradient(circle at center, transparent 60%, rgba(0,0,0,0.3) 100%)',
        }}/>
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', textAlign: 'center' }}>
          <div className="tag" style={{ color: 'var(--gold-1)', fontSize: 9, marginBottom: 2 }}>POT</div>
          <div className="font-mono grad-gold" style={{ fontSize: 22, fontWeight: 700 }}>
            <TickerBRL value={totalChipsInPlay}/>
          </div>
          <div style={{ fontSize: 9, color: 'var(--ink-3)' }}>{arrangement.filter(p => !p.bustedAt).length} ativos</div>
          <div className="row" style={{ justifyContent: 'center', gap: 4, marginTop: 6 }}>
            {[0, 1, 2].map(i => (
              <div key={i} style={{
                width: 16, height: 4, borderRadius: 2,
                background: ['#d4af37', '#d63449', '#1a4fa0'][i],
                opacity: 0.8, transform: `translateY(${-i * 2}px)`,
              }}/>
            ))}
          </div>
        </div>
      </div>
      {arrangement.map((p, i) => {
        const slot = slots[i];
        const busted = !!p.bustedAt;
        const stack = chipValue(p.chips || {});
        const active = i === activeIdx;
        return (
          <button key={p.name + i} onClick={() => onPlayerTap(i)} style={{
            position: 'absolute', left: `${slot.x}%`, top: `${slot.y}%`,
            transform: 'translate(-50%, -50%)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            opacity: busted ? 0.4 : 1, transition: 'all 0.2s var(--ease)',
          }}>
            <div style={{ position: 'relative' }}>
              <Avatar name={p.name} src={getUserAvatar(nameToRankKey(p.name))} size={42} ring={active}/>
              {busted && (
                <div style={{
                  position: 'absolute', inset: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  borderRadius: '50%', background: 'rgba(0,0,0,0.6)', color: 'var(--red-1)',
                }}><Icon name="skull" size={20}/></div>
              )}
              {active && !busted && (
                <div style={{
                  position: 'absolute', inset: -4, borderRadius: '50%',
                  border: '2px solid var(--neon)', animation: 'pulseRing 1.8s infinite',
                }}/>
              )}
              {(p.buyins || 1) > 1 && (
                <div style={{
                  position: 'absolute', top: -4, right: -4,
                  background: 'var(--gold)', color: '#0a0a05',
                  fontSize: 9, fontWeight: 800, fontFamily: 'var(--font-mono)',
                  width: 18, height: 18, borderRadius: '50%',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: '2px solid var(--bg)',
                }}>{p.buyins}x</div>
              )}
            </div>
            <div style={{
              background: 'var(--surface-2)', border: '1px solid var(--border)',
              borderRadius: 8, padding: '2px 6px', fontSize: 9, maxWidth: 80,
              textAlign: 'center', backdropFilter: 'blur(6px)',
            }}>
              <div style={{ color: 'var(--ink)', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 9 }}>
                {(p.name || '').split(' ')[0]}
              </div>
              <div className="font-mono" style={{ color: busted ? 'var(--red-1)' : stack > 25 ? 'var(--neon)' : 'var(--gold-1)', fontSize: 10, fontWeight: 700 }}>
                {fmtBRL(stack)}
              </div>
            </div>
          </button>
        );
      })}
    </div>
  );
};

/* ── CAIXA · counting chips ─────────────── */
const CaixaTab = ({ game }) => {
  const players = toArr(game.sessionPlayers);
  const setChip = (idx, key, val) => {
    const upd = [...players];
    const chips = { ...(upd[idx].chips || mkBlankChips()) };
    chips[key] = Math.max(0, Number(val) || 0);
    upd[idx] = { ...upd[idx], chips };
    debouncedSave(clubPath('/games/' + game.id + '.json'), { ...game, sessionPlayers: upd });
    const gidx = findIdx(S.games, x => x.id === game.id);
    if (gidx >= 0) S.games[gidx].sessionPlayers = upd;
    if (S.currentGame?.id === game.id) S.currentGame.sessionPlayers = upd;
    notify();
  };
  return (
    <div className="scroll-region" style={{ paddingTop: 0 }}>
      <div className="card" style={{ padding: 12, marginBottom: 12 }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Valores das fichas</div>
        <div className="row" style={{ flexWrap: 'wrap', gap: 6 }}>
          {CHIP_DEFS.map(c => (
            <div key={c.key} className="row" style={{ gap: 6 }}>
              <div className="poker-chip" style={{ background: c.bg, border: `2px solid ${c.stroke}`, width: 22, height: 22 }}/>
              <span className="font-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{fmtBRL(c.val)}</span>
            </div>
          ))}
        </div>
      </div>
      {players.map((p, i) => {
        const total = chipValue(p.chips || {});
        const gv = gameValues(game);
        const invested = (p.buyins || 1) * gv.cv;
        const profit = total - invested;
        return (
          <div key={p.name + i} className="card" style={{ padding: 14, marginBottom: 10, opacity: p.bustedAt ? 0.6 : 1 }}>
            <div className="row" style={{ marginBottom: 10 }}>
              <Avatar name={p.name} src={getUserAvatar(nameToRankKey(p.name))} size={32}/>
              <div style={{ flex: 1, marginLeft: 10, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {getDisplayName(p.name)} {p.bustedAt && <span style={{ color: 'var(--red-1)', fontSize: 11 }}>💀</span>}
                </div>
                <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{p.buyins || 1}x · {fmtBRL(invested)} inv.</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="font-mono" style={{ color: 'var(--gold-1)', fontSize: 16, fontWeight: 700 }}>
                  <TickerBRL value={total}/>
                </div>
                <div className="font-mono" style={{ fontSize: 10, color: profit >= 0 ? 'var(--neon)' : 'var(--red-1)' }}>
                  {profit >= 0 ? '+' : ''}{fmtBRL(profit)}
                </div>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
              {CHIP_DEFS.map(c => (
                <div key={c.key} style={{ textAlign: 'center' }}>
                  <div className="poker-chip" style={{
                    background: c.bg, border: `2.5px solid ${c.stroke}`,
                    margin: '0 auto 4px', width: 26, height: 26,
                  }}/>
                  <input value={(p.chips || {})[c.key] || ''}
                         onChange={e => setChip(i, c.key, e.target.value)}
                         type="number" min="0" placeholder="0"
                         className="input" style={{
                           padding: '6px 4px', fontSize: 13, textAlign: 'center',
                           fontFamily: 'var(--font-mono)', fontWeight: 600,
                         }}/>
                </div>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
};

/* ── RESULT (open game / preview) ──────── */
const ResultTab = ({ game }) => {
  const s = useStore();
  const [showConfetti, setShowConfetti] = useState(false);
  const [busy, setBusy] = useState(false);
  const [quebra, setQuebra] = useState(game.quebraRetencao);
  const gv = gameValues(game);
  const players = toArr(game.sessionPlayers).map(p => ({
    ...p,
    stack: chipValue(p.chips || {}),
    invested: (p.buyins || 1) * gv.cv,
    lp: chipValue(p.chips || {}) - (p.buyins || 1) * gv.cv,
    pay: chipValue(p.chips || {}) - (p.buyins || 1) * gv.buyin,
  }));
  const active = players.filter(p => !p.bustedAt).sort((a, b) => {
    const roeA = a.invested > 0 ? a.lp / a.invested * 100 : 0;
    const roeB = b.invested > 0 ? b.lp / b.invested * 100 : 0;
    if (Math.abs(roeB - roeA) > 0.01) return roeB - roeA;
    return b.invested - a.invested;
  });
  const busted = players.filter(p => !!p.bustedAt).sort((a, b) => a.bustedAt - b.bustedAt);
  const ranked = active.concat(busted);
  const totalE = players.reduce((s, p) => s + (p.buyins || 1), 0);
  const prize = totalE * gv.ret;
  const prizeRanking = Math.round(prize * s.prizeSplitRanking / 100 * 100) / 100;
  const prizeFinal = Math.round(prize * s.prizeSplitFinal / 100 * 100) / 100;
  const totalChipsIn = players.reduce((s, p) => s + p.invested, 0);
  const totalChipsOut = players.reduce((s, p) => s + p.stack, 0);
  const calcQuebra = Math.round((totalChipsIn - totalChipsOut) * 100) / 100;

  /* settlement */
  const payers = ranked.filter(p => p.pay < -0.01).map(p => ({ name: p.name, amt: -p.pay }));
  const recvs = ranked.filter(p => p.pay > 0.01).map(p => ({ name: p.name, amt: p.pay }));
  const txs = [];
  let pi = 0, ri = 0;
  while (pi < payers.length && ri < recvs.length) {
    const a = Math.min(payers[pi].amt, recvs[ri].amt);
    if (a > 0.01) txs.push({ from: payers[pi].name, to: recvs[ri].name, amt: a });
    payers[pi].amt -= a; recvs[ri].amt -= a;
    if (payers[pi].amt < 0.01) pi++;
    if (recvs[ri].amt < 0.01) ri++;
  }

  const closeAndRegister = async () => {
    if (!confirm('Fechar partida e registrar pontuação no ranking?')) return;
    setBusy(true);
    let totalInv = 0, prz = 0;
    let mensPos = 0;
    const closedPs = ranked.map((p, i) => {
      const rawName = resolveAlias(p.name || '');
      const key = nameToRankKey(rawName);
      const isMens = S.mensalistasList.some(m => {
        const mk = nameToRankKey(m);
        return mk === key || m === rawName || m === p.name || mk === S.allUsers.find(u => u.displayName === p.name)?.uid;
      });
      const pts = isMens ? (mensPos < PTS.length ? PTS[mensPos] : 0) : 0;
      if (isMens) mensPos++;
      totalInv += p.invested;
      prz += (p.buyins || 1) * gv.ret;
      return {
        name: p.name,
        uid: key !== p.name ? key : undefined,
        buyins: p.buyins || 1, position: i + 1,
        profit: p.lp, cashout: p.stack, invested: p.invested,
        points: pts, isMensalista: isMens,
        roe: p.invested > 0 ? p.lp / p.invested * 100 : 0,
        bustedAt: p.bustedAt || null,
      };
    });
    try {
      await closeGame(game, closedPs, prz, totalInv, quebra != null ? Number(quebra) : calcQuebra);
      setShowConfetti(true);
      toast('Partida fechada! Pontuação registrada 🏆');
    } catch (e) { toast('Erro ao fechar: ' + e.message, 'error'); }
    setBusy(false);
  };

  if (ranked.length === 0) {
    return (
      <div className="scroll-region" style={{ paddingTop: 0 }}>
        <div className="card" style={{ padding: 30, textAlign: 'center', color: 'var(--ink-3)' }}>
          Adicione jogadores na Mesa para ver o resultado.
        </div>
      </div>
    );
  }

  const champion = ranked[0];

  return (
    <div className="scroll-region" style={{ paddingTop: 0 }}>
      <Confetti run={showConfetti}/>
      {/* Champion */}
      <div className="card card-gold felt-bg" style={{ padding: 18, marginBottom: 14, position: 'relative', overflow: 'hidden' }}>
        <SuitsCorner pos="tr" opacity={0.1}/>
        <div className="row">
          <Icon name="crown" size={32} style={{ color: 'var(--gold-1)' }}/>
          <div style={{ marginLeft: 10, flex: 1, minWidth: 0 }}>
            <div className="eyebrow" style={{ color: 'var(--gold-1)' }}>Líder atual</div>
            <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 22, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {getDisplayName(champion.name)}
            </div>
          </div>
        </div>
        <div className="grid-3" style={{ marginTop: 14 }}>
          <div>
            <div className="tag" style={{ fontSize: 9 }}>STACK</div>
            <div className="font-mono" style={{ color: 'var(--gold-1)', fontSize: 14, fontWeight: 700 }}>{fmtBRL(champion.stack || 0)}</div>
          </div>
          <div>
            <div className="tag" style={{ fontSize: 9 }}>L/P</div>
            <div className="font-mono" style={{ color: champion.lp >= 0 ? 'var(--neon)' : 'var(--red-1)', fontSize: 14, fontWeight: 700 }}>
              {champion.lp >= 0 ? '+' : ''}{fmtBRL(champion.lp)}
            </div>
          </div>
          <div>
            <div className="tag" style={{ fontSize: 9 }}>PRÊMIO</div>
            <div className="font-mono grad-gold" style={{ fontSize: 14, fontWeight: 700 }}>{fmtBRL(prize)}</div>
          </div>
        </div>
      </div>

      {/* Split */}
      <div className="grid-2" style={{ marginBottom: 14 }}>
        <Stat label={`Jogo · ${s.prizeSplitRanking}%`} value={fmtBRL(prizeRanking)} color="var(--gold-1)"/>
        <Stat label={`Torneio · ${s.prizeSplitFinal}%`} value={fmtBRL(prizeFinal)} color="var(--cyan)"/>
      </div>

      {/* Quebra de retenção */}
      {isAdmin() && (
        <div className="card" style={{ padding: 12, marginBottom: 14 }}>
          <div className="row">
            <div style={{ flex: 1 }}>
              <div className="eyebrow">Quebra de retenção</div>
              <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>
                Distribuído: {fmtBRL(totalChipsIn)} · Recolhido: {fmtBRL(totalChipsOut)}
              </div>
            </div>
            <input className="input" type="number" value={quebra ?? calcQuebra}
                   onChange={e => setQuebra(e.target.value)}
                   style={{ width: 90, padding: '6px 8px', textAlign: 'center' }}/>
          </div>
        </div>
      )}

      {/* Ranking */}
      <div className="section-h"><h2>Classificação</h2></div>
      <div className="col stagger" style={{ gap: 6, marginBottom: 14 }}>
        {(() => {
          let mensIdx = 0;
          return ranked.map((p, i) => {
            const rawName = resolveAlias(p.name || '');
            const key = nameToRankKey(rawName);
            const isMens = S.mensalistasList.some(m => {
              const mk = nameToRankKey(m);
              return mk === key || m === rawName || m === p.name;
            });
            const mr = isMens ? mensIdx++ : -1;
            return <ResultRow key={p.name + i} p={{ ...p, isMensalista: isMens, mensRank: mr }} i={i} gv={gv}/>;
          });
        })()}
      </div>

      {/* Settlements */}
      {txs.length > 0 && (
        <>
          <div className="section-h"><h2>Acertos da mesa</h2><span className="chip">{txs.length}</span></div>
          <div className="col" style={{ gap: 6, marginBottom: 14 }}>
            {txs.map((t, i) => (
              <div key={i} className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
                <Avatar name={t.from} src={getUserAvatar(nameToRankKey(t.from))} size={28}/>
                <Icon name="arrow-right" size={16} style={{ color: 'var(--ink-3)' }}/>
                <Avatar name={t.to} src={getUserAvatar(nameToRankKey(t.to))} size={28}/>
                <span style={{ fontSize: 11, color: 'var(--ink-3)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  <b style={{ color: 'var(--red-1)' }}>{(getDisplayName(t.from) || '').split(' ')[0]}</b>
                  {' -> '}
                  <b style={{ color: 'var(--neon)' }}>{(getDisplayName(t.to) || '').split(' ')[0]}</b>
                </span>
                <span className="font-mono grad-gold" style={{ fontWeight: 700, fontSize: 14 }}>{fmtBRL(t.amt)}</span>
              </div>
            ))}
          </div>
        </>
      )}

      {isAdmin() && (
        <div className="col" style={{ gap: 10, marginBottom: 20 }}>
          <button className="btn btn-primary" style={{ width: '100%' }} disabled={busy} onClick={closeAndRegister}>
            {busy ? 'Fechando...' : <><Icon name="check" size={16}/> Fechar partida e registrar</>}
          </button>
        </div>
      )}
    </div>
  );
};

const ResultRow = ({ p, i, gv }) => {
  const isWin = p.lp > 0.01;
  const isLoss = p.lp < -0.01;
  const top = i < 3 && !p.bustedAt;
  const colors = ['var(--gold-1)', '#c2c2c2', '#c87030'];
  const medal = top ? ['🥇', '🥈', '🥉'][i] : p.bustedAt ? '💀' : `${i + 1}º`;
  // Correct pts: use stored value if available, else compute from mensRank
  const isMens = p.isMensalista != null ? p.isMensalista : (() => {
    const raw = resolveAlias(p.name || ''); const key = nameToRankKey(raw);
    return S.mensalistasList.some(m => { const mk = nameToRankKey(m); return mk === key || m === raw || m === p.name; });
  })();
  const pts = p.points != null ? p.points :
    (isMens && p.mensRank != null && p.mensRank >= 0 && p.mensRank < PTS.length ? PTS[p.mensRank] : 0);
  return (
    <div className="card" style={{
      padding: 12,
      background: isWin ? 'rgba(0,255,157,0.05)' : isLoss ? 'rgba(214,52,73,0.05)' : 'var(--surface)',
      borderLeft: `3px solid ${top ? colors[i] : isWin ? 'var(--neon)' : isLoss ? 'var(--red)' : 'var(--border-strong)'}`,
      opacity: p.bustedAt ? 0.75 : 1,
    }}>
      <div className="row">
        <div style={{ width: 28, textAlign: 'center', fontSize: 16, fontWeight: 700, color: colors[i] || 'var(--ink-3)' }}>
          {medal}
        </div>
        <Avatar name={p.name} src={getUserAvatar(nameToRankKey(resolveAlias(p.name||'')))} size={32}/>
        <div style={{ flex: 1, marginLeft: 8, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--ink)', textDecoration: p.bustedAt ? 'line-through' : 'none', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {getDisplayName(p.name)}
          </div>
          <div className="row" style={{ gap: 8, marginTop: 2, fontSize: 10 }}>
            <span style={{ color: 'var(--ink-3)' }}>{p.buyins || 1}x ent.</span>
            {isMens
              ? <span style={{ color: 'var(--gold-1)', fontWeight: 700, fontFamily: 'var(--font-mono)' }}>{pts} pts</span>
              : <span className="chip" style={{ padding: '1px 6px', fontSize: 9, letterSpacing: '0.03em' }}>CONVIDADO</span>
            }
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="font-mono" style={{ fontSize: 14, fontWeight: 700, color: isWin ? 'var(--neon)' : isLoss ? 'var(--red-1)' : 'var(--ink-2)' }}>
            {p.lp >= 0 ? '+' : ''}{fmtBRL(p.lp)}
          </div>
          <div className="tag" style={{ fontSize: 9 }}>L/P</div>
        </div>
      </div>
    </div>
  );
};

/* ── RESULT (closed game) ──────────────── */
const ResultClosedTab = ({ game }) => {
  const gv = gameValues(game);
  const closed = toArr(game.closedPlayers);
  const active = closed.filter(p => !p.bustedAt);
  const busted = closed.filter(p => !!p.bustedAt).sort((a, b) => a.bustedAt - b.bustedAt);
  const rawPlayers = active.concat(busted);
  const totalEntries = rawPlayers.reduce((s, p) => s + (p.buyins || 1), 0);
  const colors = ['var(--gold-1)', '#c2c2c2', '#c87030'];

  // Recompute mensalista-aware points (fixes games closed before convidado fix)
  let mensIdx = 0;
  const players = rawPlayers.map(p => {
    const rawName = resolveAlias(p.name || '');
    const key = p.uid || nameToRankKey(rawName); // uid stored on close = resilient to name changes
    const isMens = p.isMensalista != null ? p.isMensalista :
      S.mensalistasList.some(m => { const mk = nameToRankKey(m); return mk === key || m === rawName || m === p.name; });
    const pts = isMens ? (mensIdx < PTS.length ? PTS[mensIdx] : 0) : 0;
    if (isMens) mensIdx++;
    return { ...p, _isMens: isMens, _pts: pts };
  });

  return (
    <div className="scroll-region" style={{ paddingTop: 0 }}>
      <div className="grid-2" style={{ marginBottom: 14 }}>
        <Stat label="🎯 Em Fichas" value={fmtBRL(game.totalInvested || 0)} color="var(--ink-2)"/>
        <Stat label="🏆 Retenção" value={fmtBRL(game.prizePool || 0)} color="var(--gold-1)"/>
      </div>
      <div className="grid-2" style={{ marginBottom: 14 }}>
        <Stat label="👥 Entradas" value={totalEntries + 'x'} color="var(--ink-2)"/>
        {game.quebraRetencao != null && (
          <Stat label="⚡ Quebra ret." value={fmtBRL(game.quebraRetencao)} color="var(--ink-2)"/>
        )}
      </div>

      <div className="section-h"><h2>Classificação final</h2></div>
      <div className="col stagger" style={{ gap: 10 }}>
        {players.map((p, i) => {
          const invested = p.invested || (p.buyins || 1) * gv.cv;
          const cashout = p.cashout != null ? p.cashout : (p.profit || 0) + invested;
          const roe = invested > 0 ? (p.profit || 0) / invested * 100 : 0;
          const pay = cashout - (p.buyins || 1) * gv.buyin;
          const top = i < 3 && !p.bustedAt;
          const medal = top ? ['🥇', '🥈', '🥉'][i] : p.bustedAt ? '💀' : `${i + 1}º`;
          // Determine mensalista status
          const isMens = p._isMens;
          const pts = p._pts;
          const rawName = resolveAlias(p.name || '');
          const key = nameToRankKey(rawName);
          const avatarSrc = getUserAvatar(key) || getUserAvatar(p.name);
          return (
            <div key={p.name + i} className="card" style={{
              padding: 14,
              borderLeft: `3px solid ${top ? colors[i] : isMens ? (p.profit >= 0 ? 'var(--neon)' : 'var(--red)') : 'var(--border)'}`,
              opacity: p.bustedAt ? 0.8 : 1,
              background: top && !p.bustedAt ? `${colors[i]}0a` : 'var(--surface)',
            }}>
              {/* Header */}
              <div className="row" style={{ marginBottom: 12 }}>
                <div style={{ width: 28, textAlign: 'center', fontSize: 18, fontWeight: 700, color: colors[i] || 'var(--ink-3)', flexShrink: 0 }}>
                  {medal}
                </div>
                <Avatar name={p.name} src={avatarSrc} size={42} ring={top}/>
                <div style={{ flex: 1, marginLeft: 10, minWidth: 0 }}>
                  <div className="font-display" style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textDecoration: p.bustedAt ? 'line-through' : 'none' }}>
                    {getDisplayName(p.name)}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>
                    {(p.buyins || 1)}x entrada{(p.buyins || 1) > 1 ? 's' : ''} · {fmtBRL(invested)} inv.
                  </div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  {isMens ? (
                    <div className="font-mono" style={{
                      background: 'linear-gradient(135deg, var(--gold) 0%, var(--gold-deep) 100%)',
                      color: '#0d0d08', fontWeight: 800, fontSize: 13,
                      padding: '3px 8px', borderRadius: 8,
                    }}>{pts} pts</div>
                  ) : (
                    <div className="chip" style={{ padding: '3px 8px', fontSize: 9, letterSpacing: '0.05em' }}>CONVIDADO</div>
                  )}
                </div>
              </div>

              {/* Stats grid 2×3 */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
                {[
                  { label: 'FICHAS INV', val: fmtBRL(invested), color: 'var(--ink-2)' },
                  { label: 'CASHOUT', val: fmtBRL(cashout), color: cashout > invested ? 'var(--neon)' : 'var(--red-1)' },
                  { label: 'L/P', val: (p.profit >= 0 ? '+' : '') + fmtBRL(p.profit || 0), color: (p.profit || 0) >= 0 ? 'var(--neon)' : 'var(--red-1)' },
                  { label: 'ROE', val: (roe >= 0 ? '+' : '') + Math.round(roe) + '%', color: roe >= 0 ? 'var(--neon)' : 'var(--red-1)' },
                  { label: 'PAGAR/REC', val: (pay >= 0 ? '+' : '') + fmtBRL(pay), color: pay >= 0 ? 'var(--neon)' : 'var(--red-1)' },
                  { label: 'ENTRADAS', val: (p.buyins || 1) + 'x', color: 'var(--ink-2)' },
                ].map(cell => (
                  <div key={cell.label} style={{ background: 'var(--bg-2)', borderRadius: 8, padding: '7px 8px' }}>
                    <div style={{ fontSize: 8, color: 'var(--ink-3)', fontWeight: 600, letterSpacing: '0.05em', marginBottom: 3 }}>{cell.label}</div>
                    <div className="font-mono" style={{ fontSize: 12, fontWeight: 700, color: cell.color }}>{cell.val}</div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

/* ── Share QR Sheet ───────────────────── */
const ShareQRSheet = () => {
  const s = useStore();
  const club = s.clubInfo;
  if (!club) return null;
  return (
    <Sheet onClose={() => update({ sheet: null })}>
      <div style={{ textAlign: 'center', paddingBottom: 10 }}>
        <div className="eyebrow" style={{ color: 'var(--gold-1)' }}>Convide para o clube</div>
        <div className="font-editorial" style={{ fontStyle: 'italic', fontSize: 24, color: 'var(--ink)', margin: '4px 0 18px' }}>{club.name}</div>
        <div style={{
          display: 'inline-flex', padding: 18,
          background: 'var(--surface-2)', borderRadius: 20,
          border: '1px solid var(--border-strong)',
          boxShadow: 'var(--shadow-glow)',
        }}>
          <QRCode value={`scp://join/${club.clubCode}`} size={200}/>
        </div>
        <div style={{ margin: '20px auto 6px', maxWidth: 240 }}>
          <div className="font-mono" style={{
            fontSize: 28, fontWeight: 700, color: 'var(--gold-1)',
            letterSpacing: '0.4em', padding: '12px 0',
            border: '1px dashed var(--border-strong)', borderRadius: 12,
            background: 'var(--bg-2)',
          }}>{club.clubCode}</div>
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
          Compartilhe esse código com amigos.
        </div>
        <div className="row" style={{ gap: 8, marginTop: 18 }}>
          <button className="btn btn-ghost" style={{ flex: 1 }}
                  onClick={() => {
                    const txt = `Junte-se ao clube ${club.name} no Stack Control Poker!\nCódigo: ${club.clubCode}`;
                    if (navigator.share) navigator.share({ title: club.name, text: txt });
                    else { navigator.clipboard?.writeText(txt); toast('Copiado!'); }
                  }}>
            <Icon name="share" size={16}/> Compartilhar
          </button>
          <button className="btn btn-primary" style={{ flex: 1 }} onClick={() => update({ sheet: null })}>
            <Icon name="check" size={16}/> Pronto
          </button>
        </div>
      </div>
    </Sheet>
  );
};

Object.assign(window, {
  GameScreen, GameTabs, ConfirmTab, SessionTab, CaixaTab, ResultTab, ResultClosedTab,
  PokerTable, AdminAddPlayer, ResultRow, ShareQRSheet,
});
