// ranking.jsx — leaderboard page (sorted by tipped)

const FAKE_RANKING = [
  { name: 'NocturnaQueen', tipped: 12480, game: 'Roulette',     winrate: 58 },
  { name: 'SilverFox',     tipped:  9420, game: 'Blackjack',    winrate: 54 },
  { name: 'IvoryCard',     tipped:  7110, game: 'Video Poker',  winrate: 51 },
  { name: 'Onyx',          tipped:  6300, game: 'Roulette',     winrate: 49 },
  { name: 'PearlGray',     tipped:  5240, game: 'Blackjack',    winrate: 47 },
  { name: 'Crow',          tipped:  4815, game: 'Dice',         winrate: 46 },
  { name: 'Ash',           tipped:  3920, game: 'Slot Machine', winrate: 44 },
  { name: 'Velvet',        tipped:  3150, game: 'Coin Flip',    winrate: 50 },
  { name: 'NightOwl',      tipped:  2850, game: 'Roulette',     winrate: 42 },
  { name: 'Moth',          tipped:  2210, game: 'Blackjack',    winrate: 41 },
  { name: 'Smoke',         tipped:  1820, game: 'Dice',         winrate: 40 },
  { name: 'Quiet',         tipped:  1340, game: 'Coin Flip',    winrate: 48 },
];

const GAME_LABEL = {
  roulette:  'Roulette',
  blackjack: 'Blackjack',
  slots:     'Slot Machine',
  craps:     'Dice',
  poker:     'Video Poker',
  coin:      'Coin Flip',
};

function Ranking({ user, onBack }) {
  const t = useT();
  const { tipped, history } = useStore();

  // Compute the user's most-played game and winrate from local history
  const stats = React.useMemo(() => {
    if (!history || history.length === 0) return { game: '—', winrate: null };
    const counts = {};
    const wins = {};
    history.forEach((h) => {
      if (h.game === 'tip') return;
      const k = h.game;
      counts[k] = (counts[k] || 0) + 1;
      if (h.delta > 0) wins[k] = (wins[k] || 0) + 1;
    });
    const entries = Object.entries(counts);
    if (entries.length === 0) return { game: '—', winrate: null };
    const top = entries.sort((a, b) => b[1] - a[1])[0];
    const w = wins[top[0]] || 0;
    return {
      game: GAME_LABEL[top[0]] || top[0],
      winrate: Math.round((w / top[1]) * 100),
    };
  }, [history]);

  const userRow = {
    name: user?.name || 'guest',
    tipped,
    game: stats.game,
    winrate: stats.winrate,
    you: true,
  };

  const all = React.useMemo(
    () => [...FAKE_RANKING, userRow].sort((a, b) => b.tipped - a.tipped),
    [userRow]
  );
  const userRank = all.findIndex((r) => r.you) + 1;

  return (
    <>
      <TopBar title="MOST TIPPED" onBack={onBack} />
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {/* Hero — user's standing */}
        <div style={{
          padding: '40px 24px 32px',
          display: 'flex', flexDirection: 'column', gap: 6,
          borderBottom: '1px solid var(--line)',
        }}>
          <div className="eyebrow">Your standing</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
            <span style={{
              fontFamily: 'var(--font-serif)', fontStyle: 'italic',
              fontSize: 16, color: 'var(--text-3)',
            }}>№</span>
            <span className="serif" style={{
              fontSize: 64, fontStyle: 'italic',
              letterSpacing: '-0.02em', lineHeight: 1, color: 'var(--text)',
              fontVariantNumeric: 'tabular-nums',
            }}>
              {String(userRank).padStart(2, '0')}
            </span>
            <span className="mono" style={{
              fontSize: 11, color: 'var(--text-4)', letterSpacing: '0.18em',
              textTransform: 'uppercase', marginLeft: 'auto',
            }}>
              of {all.length}
            </span>
          </div>
          <div className="mono" style={{
            fontSize: 11, color: 'var(--text-3)', marginTop: 10,
            letterSpacing: '0.06em',
          }}>
            Tipped <span style={{ color: 'var(--text-2)' }}>{tipped.toLocaleString('en-US')}</span>
            {stats.winrate !== null
              ? <> · Most played <span style={{ color: 'var(--text-2)' }}>{stats.game}</span></>
              : <> · No rounds yet</>}
          </div>
        </div>

        {/* Table header */}
        <div className="rank-head">
          <div>Rank</div>
          <div>Guest</div>
          <div style={{ textAlign: 'right' }}>Tipped</div>
        </div>

        {/* Rows */}
        {all.map((r, i) => (
          <div
            key={i}
            className={
              'rank-row' +
              (r.you ? ' you' : '') +
              (i < 3 && !r.you ? ' podium' : '')
            }
          >
            <div className="rank-num">{String(i + 1).padStart(2, '0')}</div>
            <div>
              <div className="rank-name">
                {r.name}
                {r.you && <span className="rank-you-tag">you</span>}
              </div>
              <div className="rank-meta">
                {r.game}
                {r.winrate !== null && r.winrate !== undefined ? ` · ${r.winrate}% wins` : ''}
              </div>
            </div>
            <div className="rank-chips">{r.tipped.toLocaleString('en-US')}</div>
          </div>
        ))}

        <div style={{
          padding: '32px 24px',
          textAlign: 'center',
          fontSize: 10,
          color: 'var(--text-4)',
          letterSpacing: '0.22em',
          textTransform: 'uppercase',
        }}>
          {t('rank.disclaimer')}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { Ranking });
