// card-games.jsx — blackjack, video poker, baccarat, hilo, war, dragon tiger

// Helper: staggered card-deal sounds
const dealSounds = (count, interval = 80) => {
  try {
    if (typeof sounds === 'undefined') return;
    for (let i = 0; i < count; i++) {
      setTimeout(() => sounds.cardDeal(), i * interval);
    }
  } catch (e) {}
};

// ═════════════════════════════════════════════════════════════
// BLACKJACK
// ═════════════════════════════════════════════════════════════
function Blackjack({ onBack, onHistory, onRules, onTip }) {
  const { balance, settle } = useStore();
  const [bet, setBet] = React.useState(null);
  const [phase, setPhase] = React.useState('bet');
  const [deck, setDeck] = React.useState([]);
  const [hands, setHands] = React.useState([[]]);   // up to 2 hands when split
  const [active, setActive] = React.useState(0);
  const [dealer, setDealer] = React.useState([]);
  const [revealHole, setRevealHole] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [didSplit, setDidSplit] = React.useState(false);

  const dealerShown = React.useMemo(() => handTotal(revealHole ? dealer : dealer.slice(0,1)), [dealer, revealHole]);

  const cardVal = (c) => c.r === 'A' ? 11 : ['J','Q','K'].includes(c.r) ? 10 : parseInt(c.r);
  const canSplit = phase === 'player' && !didSplit
    && hands[active].length === 2
    && cardVal(hands[active][0]) === cardVal(hands[active][1])
    && bet * 2 <= balance + bet; // need enough chips for second bet

  const start = () => {
    if (!bet || bet > balance) return;
    const d = shuffleDeck();
    const p = [d.pop(), d.pop()];
    const dl = [d.pop(), d.pop()];
    setDeck(d); setHands([p]); setActive(0); setDealer(dl); setRevealHole(false);
    setResult(null); setDidSplit(false); setPhase('player');
    dealSounds(4);
    if (handTotal(p) === 21) setTimeout(() => doStand(d, [p], 0, dl, true), 700);
  };

  const hit = () => {
    if (phase !== 'player') return;
    const d = [...deck]; const c = d.pop();
    const newHands = hands.map((h, i) => i === active ? [...h, c] : h);
    setDeck(d); setHands(newHands);
    dealSounds(1);
    const total = handTotal(newHands[active]);
    if (total >= 21) {
      // bust or 21 → auto-advance
      setTimeout(() => advanceFrom(active, d, newHands, dealer), 600);
    }
  };

  const stand = () => {
    advanceFrom(active, deck, hands, dealer);
  };

  const split = () => {
    if (!canSplit) return;
    const [a, b] = hands[active];
    const d = [...deck];
    const h1 = [a, d.pop()];
    const h2 = [b, d.pop()];
    setDeck(d);
    setHands([h1, h2]);
    setActive(0);
    setDidSplit(true);
    dealSounds(2);
  };

  // Advance from `from` hand: if split and from===0, move to hand 1; else dealer plays.
  const advanceFrom = (from, curDeck, curHands, curDealer) => {
    if (didSplit && from === 0) {
      setActive(1);
      // if hand 1 already at 21 or bust (dealt naturally), keep going
      if (handTotal(curHands[1]) >= 21) {
        setTimeout(() => doStand(curDeck, curHands, 1, curDealer, false), 500);
      }
      return;
    }
    doStand(curDeck, curHands, from, curDealer, false);
  };

  // Dealer plays then settle all hands
  const doStand = (curDeck, curHands, fromIdx, curDealer, natural) => {
    setPhase('dealer'); setRevealHole(true);

    // If all player hands busted, dealer doesn't draw
    const allBust = curHands.every(h => handTotal(h) > 21);
    let d = [...curDeck];
    let dl = [...curDealer];

    const settleAll = () => setTimeout(() => finish(curHands, dl, natural), 500);

    if (allBust) {
      settleAll();
      return;
    }

    const tick = () => {
      if (handTotal(dl) < 17) {
        const c = d.pop();
        dl = [...dl, c];
        setDealer(dl); setDeck(d);
        dealSounds(1);
        setTimeout(tick, 600);
      } else {
        settleAll();
      }
    };
    setTimeout(tick, 500);
  };

  const finish = (curHands, dl, natural) => {
    const dt = handTotal(dl);
    let totalDelta = 0;
    const labels = [];
    curHands.forEach((p, i) => {
      const pt = handTotal(p);
      let delta = 0, lbl = '';
      if (pt > 21) { delta = -bet; lbl = `bust ${pt}`; }
      else if (natural && dt !== 21 && curHands.length === 1) { delta = Math.round(bet * 1.5); lbl = 'blackjack'; }
      else if (dt > 21) { delta = bet; lbl = `dealer bust ${dt}`; }
      else if (pt > dt) { delta = bet; lbl = `${pt} vs ${dt}`; }
      else if (pt < dt) { delta = -bet; lbl = `${pt} vs ${dt}`; }
      else { delta = 0; lbl = `push ${pt}`; }
      totalDelta += delta;
      labels.push(curHands.length > 1 ? `${i === 0 ? '①' : '②'} ${lbl}` : lbl);
    });
    if (totalDelta !== 0) settle('Blackjack', totalDelta, labels.join('  ·  '));
    setResult({ delta: totalDelta, label: labels.join('  ·  ') });
    setPhase('done');
    setRevealHole(true);
  };

  const newRound = () => {
    setPhase('bet'); setHands([[]]); setActive(0); setDealer([]);
    setResult(null); setRevealHole(false); setDidSplit(false);
  };

  const renderHand = (cards, idx) => {
    const total = handTotal(cards);
    const isActive = phase === 'player' && idx === active && didSplit;
    return (
      <div key={idx} style={{
        display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4,
        opacity: didSplit && phase === 'player' && idx !== active ? 0.35 : 1,
        transition: 'opacity 200ms',
      }}>
        <div style={{ display: 'flex', gap: 6, minHeight: 92 }}>
          {cards.map((c, i) => (<PlayingCard key={i} card={c} faceDown={false} />))}
        </div>
        {didSplit && (
          <div className="mono" style={{
            fontSize: 9, color: isActive ? 'var(--text)' : 'var(--text-4)',
            letterSpacing: '0.2em', textTransform: 'uppercase',
          }}>{idx === 0 ? '①' : '②'} {total}</div>
        )}
      </div>
    );
  };

  return (
    <>
      <TopBar onBack={onBack} title="BLACKJACK" balance={balance} onRules={onRules} onTip={onTip} />
      <div className="stage">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: '20px 24px 0' }}>
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div className="eyebrow">Dealer</div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--text-2)', fontVariantNumeric: 'tabular-nums' }}>
                {dealer.length > 0 ? dealerShown : '—'}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 12, minHeight: 92 }}>
              {dealer.map((c, i) => (
                <PlayingCard key={i} card={c} faceDown={i === 1 && !revealHole} />
              ))}
            </div>
          </div>

          <div style={{ textAlign: 'center', minHeight: 22 }}>
            {result ? <ResultLine result={{ delta: result.delta, label: result.label }} />
              : phase === 'bet' ? <div className="eyebrow">Choose your stake</div>
              : <div className="eyebrow" style={{ color: 'var(--text-3)' }}>
                  {phase === 'player'
                    ? (didSplit ? `your move · hand ${active + 1}` : 'your move')
                    : 'dealer playing…'}
                </div>}
          </div>

          <div style={{ paddingBottom: 12 }}>
            <div style={{
              display: 'flex', gap: 16, justifyContent: 'flex-end',
              minHeight: 92, alignItems: 'flex-end',
            }}>
              {hands.map((h, i) => renderHand(h, i))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 12 }}>
              <div className="eyebrow">You {didSplit && `· ${bet * 2} staked`}</div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--text-2)', fontVariantNumeric: 'tabular-nums' }}>
                {hands[0].length > 0 ? (didSplit ? `${handTotal(hands[0])} · ${handTotal(hands[1])}` : handTotal(hands[0])) : '—'}
              </div>
            </div>
          </div>
        </div>

        {phase === 'bet' && (
          <>
            <div style={{ padding: '0 0 16px' }}>
              <div className="eyebrow" style={{ padding: '0 24px 12px' }}>Stake</div>
              <BetSelector value={bet} onChange={setBet} />
            </div>
            <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
              <button className="btn" onClick={start} disabled={!bet || bet > balance}
                style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>Deal</button>
            </div>
          </>
        )}

        {phase === 'player' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)', display: 'flex', gap: 8 }}>
            <button className="btn" onClick={hit}>Hit</button>
            <button className="btn" onClick={stand}>Stand</button>
            <button className="btn" onClick={split} disabled={!canSplit}
              style={{ opacity: canSplit ? 1 : 0.35 }}>Split</button>
          </div>
        )}

        {phase === 'dealer' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn" disabled style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>· · ·</button>
          </div>
        )}

        {phase === 'done' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn primary" onClick={newRound}
              style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>New Hand</button>
          </div>
        )}
      </div>
    </>
  );
}

// ═════════════════════════════════════════════════════════════
// VIDEO POKER — Jacks or Better
// ═════════════════════════════════════════════════════════════
const POKER_PAYS = {
  'Royal Flush': 250,
  'Straight Flush': 50,
  'Four of a Kind': 25,
  'Full House': 9,
  'Flush': 6,
  'Straight': 4,
  'Three of a Kind': 3,
  'Two Pair': 2,
  'Pair (J+)': 1,
  '—': 0,
};

function evalPoker(hand) {
  const ranks = hand.map(c => RANKS.indexOf(c.r));
  const suits = hand.map(c => c.s);
  const counts = {};
  for (const r of ranks) counts[r] = (counts[r] || 0) + 1;
  const cs = Object.values(counts).sort((a,b) => b - a);
  const flush = suits.every(s => s === suits[0]);
  const sorted = [...new Set(ranks)].sort((a, b) => a - b);
  let straight = false;
  if (sorted.length === 5) {
    if (sorted[4] - sorted[0] === 4) straight = true;
    if (sorted.join(',') === '0,1,2,3,12') straight = true; // wheel A2345
  }
  const royal = flush && straight && [...new Set(ranks)].sort((a,b)=>a-b).join(',') === '0,9,10,11,12';
  if (royal) return 'Royal Flush';
  if (flush && straight) return 'Straight Flush';
  if (cs[0] === 4) return 'Four of a Kind';
  if (cs[0] === 3 && cs[1] === 2) return 'Full House';
  if (flush) return 'Flush';
  if (straight) return 'Straight';
  if (cs[0] === 3) return 'Three of a Kind';
  if (cs[0] === 2 && cs[1] === 2) return 'Two Pair';
  if (cs[0] === 2) {
    const pairRank = parseInt(Object.keys(counts).find(k => counts[k] === 2));
    if (pairRank >= 10 || pairRank === 0) return 'Pair (J+)';
  }
  return '—';
}

function VideoPoker({ onBack, onHistory, onRules, onTip }) {
  const { balance, settle } = useStore();
  const [bet, setBet] = React.useState(null);
  const [phase, setPhase] = React.useState('bet');
  const [deck, setDeck] = React.useState([]);
  const [hand, setHand] = React.useState([null, null, null, null, null]);
  const [held, setHeld] = React.useState([false, false, false, false, false]);
  const [result, setResult] = React.useState(null);
  const [flipKey, setFlipKey] = React.useState(0);

  const deal = () => {
    if (!bet || bet > balance) return;
    const d = shuffleDeck();
    const h = [d.pop(), d.pop(), d.pop(), d.pop(), d.pop()];
    setDeck(d); setHand(h); setHeld([false, false, false, false, false]);
    setResult(null); setPhase('hold'); setFlipKey(k => k + 1);
    dealSounds(5, 70);
  };

  const draw = () => {
    const d = [...deck];
    const h = hand.map((c, i) => held[i] ? c : d.pop());
    setDeck(d); setHand(h);
    setFlipKey(k => k + 1);
    const replacedCount = held.filter((v) => !v).length;
    if (replacedCount > 0) dealSounds(replacedCount, 70);
    setTimeout(() => {
      const cat = evalPoker(h);
      const mult = POKER_PAYS[cat];
      const ret = bet * mult;
      const netDelta = ret - bet;
      settle('Video Poker', netDelta, cat);
      setResult({ delta: netDelta, label: cat });
      setPhase('done');
    }, 700);
  };

  const newRound = () => {
    setPhase('bet'); setHand([null,null,null,null,null]); setHeld([false,false,false,false,false]); setResult(null);
  };

  const toggleHold = (i) => {
    if (phase !== 'hold') return;
    setHeld((h) => h.map((v, j) => j === i ? !v : v));
  };

  return (
    <>
      <TopBar onBack={onBack} title="VIDEO POKER" balance={balance} onRules={onRules} onTip={onTip} />
      <div className="stage">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 16px', gap: 24 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {hand.map((c, i) => (
              <div key={`${i}-${flipKey}`} className="press" onClick={() => toggleHold(i)}
                style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, cursor: phase === 'hold' ? 'pointer' : 'default' }}>
                {c ? (
                  <PlayingCard card={c} faceDown={false} held={held[i]} />
                ) : (
                  <div className="pcard face-down" style={{ width: 64, height: 92 }} />
                )}
                <div style={{
                  fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase',
                  color: held[i] ? 'var(--text)' : 'var(--text-4)',
                  fontWeight: 500, transition: 'color 160ms',
                }}>{held[i] ? '· hold ·' : 'tap to hold'}</div>
              </div>
            ))}
          </div>

          <div style={{ minHeight: 22, textAlign: 'center' }}>
            {result ? <ResultLine result={{ delta: result.delta, label: result.label }} />
              : phase === 'hold' ? <div className="eyebrow">Choose cards to hold</div>
              : phase === 'bet' ? <div className="eyebrow">Stake and deal</div>
              : <div className="eyebrow">·</div>}
          </div>

          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 24px',
            fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-3)',
            width: '100%', maxWidth: 320,
          }}>
            {Object.entries(POKER_PAYS).filter(([k]) => k !== '—').map(([k, v]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>{k}</span><span style={{ color: 'var(--text-2)' }}>{v}×</span>
              </div>
            ))}
          </div>
        </div>

        {phase === 'bet' && (
          <>
            <div style={{ padding: '0 0 16px' }}>
              <div className="eyebrow" style={{ padding: '0 24px 12px' }}>Stake</div>
              <BetSelector value={bet} onChange={setBet} />
            </div>
            <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
              <button className="btn" onClick={deal} disabled={!bet || bet > balance}
                style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>Deal</button>
            </div>
          </>
        )}
        {phase === 'hold' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn" onClick={draw}
              style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>Draw</button>
          </div>
        )}
        {phase === 'done' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn primary" onClick={newRound}
              style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>New Hand</button>
          </div>
        )}
      </div>
    </>
  );
}

// ═════════════════════════════════════════════════════════════
// BACCARAT — Punto Banco
// ═════════════════════════════════════════════════════════════
const baccaratValue = (c) => {
  if (c.r === 'A') return 1;
  if (['10', 'J', 'Q', 'K'].includes(c.r)) return 0;
  return parseInt(c.r);
};
const baccaratTotal = (cards) => cards.reduce((a, c) => a + baccaratValue(c), 0) % 10;

const bankerShouldDraw = (bt, playerThirdValue) => {
  const v = playerThirdValue;
  if (bt <= 2) return true;
  if (bt === 3) return v !== 8;
  if (bt === 4) return v >= 2 && v <= 7;
  if (bt === 5) return v >= 4 && v <= 7;
  if (bt === 6) return v === 6 || v === 7;
  return false; // bt = 7
};

function Baccarat({ onBack, onHistory, onRules, onTip }) {
  const { balance, settle } = useStore();
  const [bet, setBet] = React.useState(null);
  const [betType, setBetType] = React.useState(null); // 'player' | 'banker' | 'tie'
  const [phase, setPhase] = React.useState('bet');     // bet | dealing | done
  const [player, setPlayer] = React.useState([]);
  const [banker, setBanker] = React.useState([]);
  const [result, setResult] = React.useState(null);

  const start = () => {
    if (!bet || bet > balance || !betType) return;
    setPhase('dealing'); setResult(null);

    const d = shuffleDeck();
    const p = [d.pop(), d.pop()];
    const b = [d.pop(), d.pop()];

    // Reveal in standard order: P1, B1, P2, B2
    setTimeout(() => { setPlayer([p[0]]); dealSounds(1); }, 200);
    setTimeout(() => { setBanker([b[0]]); dealSounds(1); }, 600);
    setTimeout(() => { setPlayer([...p]); dealSounds(1); }, 1000);
    setTimeout(() => { setBanker([...b]); dealSounds(1); }, 1400);

    setTimeout(() => {
      const pt = baccaratTotal(p);
      const bt = baccaratTotal(b);

      // Naturals
      if (pt >= 8 || bt >= 8) {
        setTimeout(() => finalize(p, b), 500);
        return;
      }

      // Player draws on 0–5, stands on 6–7
      if (pt <= 5) {
        const playerThird = d.pop();
        p.push(playerThird);
        setTimeout(() => {
          setPlayer([...p]); dealSounds(1);
          setTimeout(() => {
            const ptv = baccaratValue(playerThird);
            if (bankerShouldDraw(bt, ptv)) {
              b.push(d.pop());
              setBanker([...b]); dealSounds(1);
              setTimeout(() => finalize(p, b), 700);
            } else {
              finalize(p, b);
            }
          }, 700);
        }, 400);
      } else {
        // Player stood; Banker draws 0–5, stands 6–7
        if (bt <= 5) {
          b.push(d.pop());
          setTimeout(() => {
            setBanker([...b]); dealSounds(1);
            setTimeout(() => finalize(p, b), 700);
          }, 400);
        } else {
          finalize(p, b);
        }
      }
    }, 1900);
  };

  const finalize = (p, b) => {
    const pt = baccaratTotal(p);
    const bt = baccaratTotal(b);
    const winner = pt > bt ? 'player' : pt < bt ? 'banker' : 'tie';

    let delta = -bet;
    if (betType === winner) {
      if (winner === 'player') delta = bet;
      else if (winner === 'banker') delta = Math.floor(bet * 0.95);
      else delta = bet * 8;
    } else if (winner === 'tie' && betType !== 'tie') {
      // Tie pushes Player and Banker bets
      delta = 0;
    }

    const label = `${pt} vs ${bt} · ${winner}`;
    if (delta !== 0) settle('Baccarat', delta, label);
    setResult({ delta, label });
    setPhase('done');
  };

  const newRound = () => {
    setPhase('bet'); setPlayer([]); setBanker([]); setResult(null); setBetType(null);
  };

  return (
    <>
      <TopBar onBack={onBack} title="BACCARAT" balance={balance} onRules={onRules} onTip={onTip} />
      <div className="stage">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: '20px 24px 0' }}>
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div className="eyebrow">Banker</div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--text-2)', fontVariantNumeric: 'tabular-nums' }}>
                {banker.length > 0 ? baccaratTotal(banker) : '—'}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 12, minHeight: 92 }}>
              {banker.map((c, i) => <PlayingCard key={i} card={c} faceDown={false} />)}
            </div>
          </div>

          <div style={{ textAlign: 'center', minHeight: 22 }}>
            {result ? <ResultLine result={{ delta: result.delta, label: result.label }} />
              : phase === 'bet' ? <div className="eyebrow">Choose side and stake</div>
              : <div className="eyebrow" style={{ color: 'var(--text-3)' }}>dealing…</div>}
          </div>

          <div style={{ paddingBottom: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div className="eyebrow">Player</div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--text-2)', fontVariantNumeric: 'tabular-nums' }}>
                {player.length > 0 ? baccaratTotal(player) : '—'}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 12, minHeight: 92 }}>
              {player.map((c, i) => <PlayingCard key={i} card={c} faceDown={false} />)}
            </div>
          </div>
        </div>

        {phase === 'bet' && (
          <>
            <div style={{ padding: '0 24px 16px' }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>Side</div>
              <div style={{ display: 'flex', gap: 6 }}>
                {[
                  { id: 'player', label: 'Player', pay: '1 : 1' },
                  { id: 'tie',    label: 'Tie',    pay: '8 : 1' },
                  { id: 'banker', label: 'Banker', pay: '0.95 : 1' },
                ].map((opt) => (
                  <button
                    key={opt.id}
                    className={'chip press' + (betType === opt.id ? ' active' : '')}
                    onClick={() => setBetType(opt.id)}
                    style={{ flex: 1, height: 56, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 4 }}
                  >
                    <div style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{opt.label}</div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--text-4)', letterSpacing: '0.06em' }}>{opt.pay}</div>
                  </button>
                ))}
              </div>
            </div>
            <div style={{ padding: '0 0 16px' }}>
              <div className="eyebrow" style={{ padding: '0 24px 12px' }}>Stake</div>
              <BetSelector value={bet} onChange={setBet} />
            </div>
            <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
              <button className="btn" onClick={start} disabled={!bet || bet > balance || !betType}
                style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>Deal</button>
            </div>
          </>
        )}

        {phase === 'dealing' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn" disabled style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>· · ·</button>
          </div>
        )}

        {phase === 'done' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn primary" onClick={newRound}
              style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>New Hand</button>
          </div>
        )}
      </div>
    </>
  );
}

// ═════════════════════════════════════════════════════════════
// HI-LO
// ═════════════════════════════════════════════════════════════
function HiLo({ onBack, onHistory, onRules, onTip }) {
  const { balance, settle } = useStore();
  const [bet, setBet] = React.useState(null);
  const [phase, setPhase] = React.useState('bet'); // bet | playing | reveal | done
  const [deck, setDeck] = React.useState([]);
  const [current, setCurrent] = React.useState(null);
  const [next, setNext] = React.useState(null);
  const [multiplier, setMultiplier] = React.useState(1);
  const [streak, setStreak] = React.useState(0);
  const [result, setResult] = React.useState(null);

  const rankIdx = (r) => RANKS.indexOf(r); // A=0 ... K=12
  const probHigher = (cur) => (12 - rankIdx(cur.r)) / 12;
  const probLower  = (cur) => rankIdx(cur.r) / 12;

  const start = () => {
    if (!bet || bet > balance) return;
    const d = shuffleDeck();
    setCurrent(d.pop());
    setDeck(d);
    setNext(null);
    setMultiplier(1);
    setStreak(0);
    setResult(null);
    setPhase('playing');
    dealSounds(1);
  };

  const guess = (direction) => {
    if (phase !== 'playing') return;
    const d = [...deck];
    const card = d.pop();
    setNext(card);
    setPhase('reveal');
    dealSounds(1);

    setTimeout(() => {
      const curIdx = rankIdx(current.r);
      const newIdx = rankIdx(card.r);
      const win = direction === 'higher' ? newIdx > curIdx : newIdx < curIdx;

      if (win) {
        const p = direction === 'higher' ? probHigher(current) : probLower(current);
        const stepMult = 0.97 / Math.max(0.0001, p);
        const newMult = multiplier * stepMult;
        setMultiplier(newMult);
        setStreak((s) => s + 1);
        setTimeout(() => {
          setCurrent(card);
          setNext(null);
          setDeck(d);
          setPhase('playing');
        }, 1000);
      } else {
        const delta = -bet;
        settle('Hi-Lo', delta, `bust on ${card.r}${card.s} after ${streak}`);
        setResult({ delta, label: `bust at ${streak}×` });
        setPhase('done');
      }
    }, 700);
  };

  const cashOut = () => {
    if (streak === 0) return;
    const delta = Math.floor(bet * multiplier - bet);
    settle('Hi-Lo', delta, `cash · ${multiplier.toFixed(2)}× · ${streak} hits`);
    setResult({ delta, label: `${multiplier.toFixed(2)}× · ${streak} hits` });
    setPhase('done');
  };

  const newRound = () => {
    setPhase('bet'); setCurrent(null); setNext(null);
    setMultiplier(1); setStreak(0); setResult(null);
  };

  const canHigher = current ? probHigher(current) > 0 : false;
  const canLower  = current ? probLower(current)  > 0 : false;

  return (
    <>
      <TopBar onBack={onBack} title="HI-LO" balance={balance} onRules={onRules} onTip={onTip} />
      <div className="stage">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 24px', gap: 28 }}>
          {/* Multiplier + streak header (only during play) */}
          {phase !== 'bet' && (
            <div style={{ textAlign: 'center' }}>
              <div className="eyebrow">{streak === 0 ? 'Stake' : 'Streak'}</div>
              <div className="mono" style={{
                fontSize: 28, color: 'var(--text)', fontVariantNumeric: 'tabular-nums',
                letterSpacing: '0.02em', fontWeight: 300, lineHeight: 1.1, marginTop: 6,
              }}>
                {multiplier.toFixed(2)}×
              </div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--text-4)', letterSpacing: '0.18em', marginTop: 6, textTransform: 'uppercase' }}>
                {streak} {streak === 1 ? 'hit' : 'hits'}
              </div>
            </div>
          )}

          {/* Cards */}
          <div style={{ display: 'flex', gap: 20, alignItems: 'center' }}>
            {current ? (
              <PlayingCard card={current} faceDown={false} />
            ) : (
              <div className="pcard face-down" style={{ width: 64, height: 92 }} />
            )}
            <div className="mono" style={{ color: 'var(--text-4)', fontSize: 14 }}>→</div>
            {next ? (
              <PlayingCard card={next} faceDown={false} />
            ) : (
              <div className="pcard face-down" style={{ width: 64, height: 92 }} />
            )}
          </div>

          <div style={{ minHeight: 22, textAlign: 'center' }}>
            {result ? <ResultLine result={{ delta: result.delta, label: result.label }} />
              : phase === 'bet' ? <div className="eyebrow">Stake and reveal</div>
              : phase === 'reveal' ? <div className="eyebrow" style={{ color: 'var(--text-3)' }}>·</div>
              : <div className="eyebrow">Higher or lower?</div>}
          </div>
        </div>

        {phase === 'bet' && (
          <>
            <div style={{ padding: '0 0 16px' }}>
              <div className="eyebrow" style={{ padding: '0 24px 12px' }}>Stake</div>
              <BetSelector value={bet} onChange={setBet} />
            </div>
            <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
              <button className="btn" onClick={start} disabled={!bet || bet > balance}
                style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>Deal</button>
            </div>
          </>
        )}

        {phase === 'playing' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)', display: 'flex', gap: 8 }}>
            <button className="btn" onClick={() => guess('lower')} disabled={!canLower}
              style={{ opacity: canLower ? 1 : 0.35 }}>Lower</button>
            <button className="btn" onClick={cashOut} disabled={streak === 0}
              style={{ opacity: streak === 0 ? 0.35 : 1 }}>Cash</button>
            <button className="btn" onClick={() => guess('higher')} disabled={!canHigher}
              style={{ opacity: canHigher ? 1 : 0.35 }}>Higher</button>
          </div>
        )}

        {phase === 'reveal' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn" disabled style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>· · ·</button>
          </div>
        )}

        {phase === 'done' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn primary" onClick={newRound}
              style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>New Round</button>
          </div>
        )}
      </div>
    </>
  );
}

// ═════════════════════════════════════════════════════════════
// CASINO WAR — one card vs one card, higher wins
// ═════════════════════════════════════════════════════════════
const warValue = (c) => c.r === 'A' ? 13 : RANKS.indexOf(c.r);

function CasinoWar({ onBack, onHistory, onRules, onTip }) {
  const { balance, settle } = useStore();
  const [bet, setBet] = React.useState(null);
  const [phase, setPhase] = React.useState('bet'); // bet | reveal | done
  const [player, setPlayer] = React.useState(null);
  const [dealer, setDealer] = React.useState(null);
  const [result, setResult] = React.useState(null);

  const start = () => {
    if (!bet || bet > balance) return;
    setPhase('reveal'); setResult(null);
    const d = shuffleDeck();
    const p = d.pop();
    const dl = d.pop();
    setTimeout(() => { setPlayer(p); dealSounds(1); }, 250);
    setTimeout(() => { setDealer(dl); dealSounds(1); }, 700);
    setTimeout(() => {
      const pv = warValue(p);
      const dv = warValue(dl);
      let delta = 0, label = '';
      if (pv > dv) { delta = bet; label = `${p.r} vs ${dl.r} · win`; }
      else if (pv < dv) { delta = -bet; label = `${p.r} vs ${dl.r} · loss`; }
      else { delta = 0; label = `tie · ${p.r}`; }
      if (delta !== 0) settle('Casino War', delta, label);
      setResult({ delta, label });
      setPhase('done');
    }, 1300);
  };

  const newRound = () => {
    setPhase('bet'); setPlayer(null); setDealer(null); setResult(null);
  };

  return (
    <>
      <TopBar onBack={onBack} title="WAR" balance={balance} onRules={onRules} onTip={onTip} />
      <div className="stage">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 24px', gap: 32 }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
            <div className="eyebrow">Dealer</div>
            {dealer ? <PlayingCard card={dealer} faceDown={false} /> : <div className="pcard face-down" style={{ width: 64, height: 92 }} />}
          </div>

          <div style={{ minHeight: 22, textAlign: 'center' }}>
            {result ? <ResultLine result={{ delta: result.delta, label: result.label }} />
              : phase === 'reveal' ? <div className="eyebrow" style={{ color: 'var(--text-3)' }}>·</div>
              : <div className="eyebrow">Highest card wins</div>}
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
            {player ? <PlayingCard card={player} faceDown={false} /> : <div className="pcard face-down" style={{ width: 64, height: 92 }} />}
            <div className="eyebrow">You</div>
          </div>
        </div>

        {phase === 'bet' && (
          <>
            <div style={{ padding: '0 0 16px' }}>
              <div className="eyebrow" style={{ padding: '0 24px 12px' }}>Stake</div>
              <BetSelector value={bet} onChange={setBet} />
            </div>
            <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
              <button className="btn" onClick={start} disabled={!bet || bet > balance}
                style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>Deal</button>
            </div>
          </>
        )}

        {phase === 'reveal' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn" disabled style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>· · ·</button>
          </div>
        )}

        {phase === 'done' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn primary" onClick={newRound}
              style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>New Round</button>
          </div>
        )}
      </div>
    </>
  );
}

// ═════════════════════════════════════════════════════════════
// DRAGON TIGER — bet on which side draws the higher card
// ═════════════════════════════════════════════════════════════
const dtValue = (c) => {
  if (c.r === 'A') return 1;
  if (c.r === 'K') return 13;
  if (c.r === 'Q') return 12;
  if (c.r === 'J') return 11;
  return parseInt(c.r);
};

function DragonTiger({ onBack, onHistory, onRules, onTip }) {
  const { balance, settle } = useStore();
  const [bet, setBet] = React.useState(null);
  const [betSide, setBetSide] = React.useState(null); // 'dragon' | 'tiger' | 'tie'
  const [phase, setPhase] = React.useState('bet'); // bet | reveal | done
  const [dragon, setDragon] = React.useState(null);
  const [tiger, setTiger] = React.useState(null);
  const [result, setResult] = React.useState(null);

  const start = () => {
    if (!bet || bet > balance || !betSide) return;
    setPhase('reveal'); setResult(null);
    const d = shuffleDeck();
    const dr = d.pop();
    const tg = d.pop();
    setTimeout(() => { setDragon(dr); dealSounds(1); }, 250);
    setTimeout(() => { setTiger(tg); dealSounds(1); }, 700);
    setTimeout(() => {
      const dv = dtValue(dr);
      const tv = dtValue(tg);
      const winner = dv > tv ? 'dragon' : dv < tv ? 'tiger' : 'tie';
      let delta = -bet;
      if (betSide === winner) {
        if (winner === 'tie') delta = bet * 8;
        else delta = bet;
      } else if (winner === 'tie' && (betSide === 'dragon' || betSide === 'tiger')) {
        // Standard: half loss on tie when betting dragon/tiger; here we lose full for simplicity
        delta = -Math.floor(bet / 2);
      }
      const label = `${dr.r} vs ${tg.r} · ${winner}`;
      if (delta !== 0) settle('Dragon Tiger', delta, label);
      setResult({ delta, label });
      setPhase('done');
    }, 1300);
  };

  const newRound = () => {
    setPhase('bet'); setDragon(null); setTiger(null); setResult(null); setBetSide(null);
  };

  return (
    <>
      <TopBar onBack={onBack} title="DRAGON · TIGER" balance={balance} onRules={onRules} onTip={onTip} />
      <div className="stage">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 24px', gap: 24 }}>
          <div style={{ display: 'flex', gap: 28, alignItems: 'center' }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
              <div className="eyebrow">Dragon</div>
              {dragon ? <PlayingCard card={dragon} faceDown={false} /> : <div className="pcard face-down" style={{ width: 64, height: 92 }} />}
            </div>
            <div style={{
              fontFamily: 'var(--font-serif)', fontStyle: 'italic',
              fontSize: 20, color: 'var(--text-4)',
            }}>·</div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
              <div className="eyebrow">Tiger</div>
              {tiger ? <PlayingCard card={tiger} faceDown={false} /> : <div className="pcard face-down" style={{ width: 64, height: 92 }} />}
            </div>
          </div>

          <div style={{ minHeight: 22, textAlign: 'center' }}>
            {result ? <ResultLine result={{ delta: result.delta, label: result.label }} />
              : phase === 'reveal' ? <div className="eyebrow" style={{ color: 'var(--text-3)' }}>·</div>
              : <div className="eyebrow">Pick a side</div>}
          </div>
        </div>

        {phase === 'bet' && (
          <>
            <div style={{ padding: '0 24px 14px' }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Side</div>
              <div style={{ display: 'flex', gap: 6 }}>
                {[
                  { id: 'dragon', label: 'Dragon', pay: '1 : 1' },
                  { id: 'tie',    label: 'Tie',    pay: '8 : 1' },
                  { id: 'tiger',  label: 'Tiger',  pay: '1 : 1' },
                ].map((opt) => (
                  <button key={opt.id}
                    className={'chip press' + (betSide === opt.id ? ' active' : '')}
                    onClick={() => setBetSide(opt.id)}
                    style={{ flex: 1, height: 56, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 4 }}>
                    <div style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{opt.label}</div>
                    <div className="mono" style={{ fontSize: 9, color: 'var(--text-4)', letterSpacing: '0.06em' }}>{opt.pay}</div>
                  </button>
                ))}
              </div>
            </div>
            <div style={{ padding: '0 0 16px' }}>
              <div className="eyebrow" style={{ padding: '0 24px 12px' }}>Stake</div>
              <BetSelector value={bet} onChange={setBet} />
            </div>
            <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
              <button className="btn" onClick={start} disabled={!bet || bet > balance || !betSide}
                style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>Deal</button>
            </div>
          </>
        )}

        {phase === 'reveal' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn" disabled style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>· · ·</button>
          </div>
        )}

        {phase === 'done' && (
          <div style={{ padding: '8px 24px 24px', borderTop: '1px solid var(--line)' }}>
            <button className="btn primary" onClick={newRound}
              style={{ width: '100%', height: 56, letterSpacing: '0.3em' }}>New Round</button>
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { Blackjack, VideoPoker, Baccarat, HiLo, CasinoWar, DragonTiger });
