/* ── Lobby ─────────────────────────────────────────────────────────────
   Hero card (rotating) + 2-up game grid + live wins ticker.
   ────────────────────────────────────────────────────────────────────── */

const LOBBY_GAMES = [
  {
    id: 'slots',     glyph: '♛', name: 'Slots',
    tagline: 'Three symbols, one fortune',
    meta: ['Up to 20×', 'Cabinet', 'Solo'],
    heroTag: 'The Spinning Reels',
    heroSubtitle: 'Align the crown thrice for the grand prize.',
    heroStats: [{ label: 'Top Mult', value: '20×' }, { label: 'House Edge', value: '5%' }, { label: 'Bets', value: '100–5k' }],
  },
  {
    id: 'blackjack', glyph: '♠', name: 'Blackjack',
    tagline: 'Beat the dealer to twenty-one',
    meta: ['1:1 / 3:2', 'Solo', 'Strategy'],
    heroTag: 'The Dealer\'s Hand',
    heroSubtitle: 'Twenty-one or perish. Choose to hit, hold, or double the stake.',
    heroStats: [{ label: 'Blackjack', value: '3:2' }, { label: 'Decks', value: '∞' }, { label: 'Bets', value: '100–5k' }],
  },
  {
    id: 'roulette',  glyph: '◎', name: 'Roulette',
    tagline: 'Pick your fate on the wheel',
    meta: ['Up to 35:1', 'Solo', 'Wheel'],
    heroTag: 'The Wheel of Fates',
    heroSubtitle: '17 Black. Let it ride.',
    heroStats: [{ label: 'Top Odds', value: '35:1' }, { label: 'Wheel', value: 'American' }, { label: 'Bets', value: '100–5k' }],
  },
  {
    id: 'crash',     glyph: '↗', name: 'Crash',
    tagline: 'Cash out before it crashes',
    meta: ['Up to 100×', 'Solo', 'Real-time'],
    heroTag: 'The Rising Star',
    heroSubtitle: 'Watch the comet climb — but pull your stake before it falls.',
    heroStats: [{ label: 'Top Mult', value: '100×' }, { label: 'Auto-out', value: 'Yes' }, { label: 'Bets', value: '100–5k' }],
  },
  {
    id: 'crate',     glyph: '⬢', name: 'Crate Opener',
    tagline: 'Unbox Delphinad treasures',
    meta: ['3 crates', 'Solo', 'Loot drop'],
    heroTag: 'The Sealed Vault',
    heroSubtitle: 'Three crates, ten rarities, one chance at the Mythic gear box.',
    heroStats: [{ label: 'Rarities', value: '10' }, { label: 'Top Drop', value: '40k G' }, { label: 'Crates', value: '500–8k' }],
  },
  {
    id: 'poker',     glyph: '♣', name: 'Group Poker',
    tagline: "Texas Hold'em with the table",
    meta: ['2–8 seats', 'Multiplayer', 'Cards'],
    heroTag: 'The Long Game',
    heroSubtitle: 'Texas Hold\'em at a wooden table. Read the room. Bluff if you must.',
    heroStats: [{ label: 'Seats', value: '2–8' }, { label: 'Format', value: "Hold'em" }, { label: 'Blinds', value: '50/100' }],
  },
  {
    id: 'group_bj',  glyph: '♣', name: 'Group Blackjack',
    tagline: 'Eight seats vs the dealer',
    meta: ['2–8 seats', 'Multiplayer', 'Cards'],
    heroTag: 'The Round Table',
    heroSubtitle: 'Take a seat. The dealer turns the cards for the whole room at once.',
    heroStats: [{ label: 'Seats', value: '2–8' }, { label: 'Blackjack', value: '3:2' }, { label: 'Decks', value: '6' }],
  },
  {
    id: 'minesweeper', glyph: '✦', name: 'Minesweeper',
    tagline: 'Uncover the field, avoid the mines',
    meta: ['1–24 mines', 'Solo', 'Cash out'],
    heroTag: 'The Minefield',
    heroSubtitle: 'Set your mines. Flip the tiles. Walk away before the ground gives.',
    heroStats: [{ label: 'Max Mult', value: '∞' }, { label: 'Grid', value: '5 × 5' }, { label: 'Mines', value: '1–24' }],
  },
  {
    id: 'keno',      glyph: '◉', name: 'Keno',
    tagline: 'Pick your lucky numbers',
    meta: ['Up to 50000×', 'Solo', 'Numbers'],
    heroTag: 'The Numbers Game',
    heroSubtitle: 'Choose up to ten lucky numbers. Twenty are drawn. Fortune favours the bold.',
    heroStats: [{ label: 'Top Mult', value: '50k×' }, { label: 'Draw', value: '20/80' }, { label: 'Bets', value: '100–5k' }],
  },
  {
    id: 'plinko',    glyph: '◈', name: 'Plinko',
    tagline: 'Drop the ball, claim your fate',
    meta: ['Up to 50×', 'Solo', 'Cascade'],
    heroTag: 'The Cascade',
    heroSubtitle: 'Release the golden ball. Watch it find its own path through the pegs.',
    heroStats: [{ label: 'Top Mult', value: '50×' }, { label: 'Rows', value: '12' }, { label: 'Bets', value: '100–1k' }],
  },
];

const TICKER_NAMES = [
  'Kyprosa', 'Lucius', 'Aranzeb', 'Daru', 'Tahyang', 'Eanna', 'Salphira',
  'Inoch', 'Anthalon', 'Orchidna', 'Morpheus', 'Nui', 'Hila', 'Vakarian',
];

const GAME_DISPLAY = {
  slots: 'Slots', plinko: 'Plinko', minesweeper: 'Minesweeper',
  keno: 'Keno', roulette: 'Roulette', crash: 'Crash',
  blackjack: 'Blackjack', crate: 'Crate Opener',
  poker: 'Group Poker', group_blackjack: 'Group Blackjack',
};

function makeTickerLine() {
  const name = TICKER_NAMES[Math.floor(Math.random() * TICKER_NAMES.length)];
  const game = LOBBY_GAMES[Math.floor(Math.random() * LOBBY_GAMES.length)];
  const amt  = game.id === 'crate'
    ? Math.floor(30  + Math.random() * 3720)
    : Math.floor(200 + Math.random() * 4800);
  return { name, game: game.name, amt };
}

function Lobby({ onSelect, token }) {
  const { useState, useEffect, useMemo } = React;
  const [heroIdx, setHeroIdx] = useState(0);

  const heroes = useMemo(() => {
    const featured = ['slots', 'crash', 'roulette', 'crate'];
    return featured.map(id => LOBBY_GAMES.find(g => g.id === id));
  }, []);
  const hero = heroes[heroIdx];

  useEffect(() => {
    const t = setInterval(() => setHeroIdx(i => (i + 1) % heroes.length), 7000);
    return () => clearInterval(t);
  }, [heroes.length]);

  const [tickerItems, setTickerItems] = useState(() => {
    const lines = [];
    for (let i = 0; i < 14; i++) lines.push(makeTickerLine());
    return lines;
  });

  useEffect(() => {
    function fetchWins() {
      fetch('/api/wins/recent')
        .then(r => r.json())
        .then(wins => {
          if (!Array.isArray(wins) || wins.length === 0) return;
          const mapped = wins.map(w => ({
            name: w.username,
            game: GAME_DISPLAY[w.game] || w.game,
            amt: w.amt,
          }));
          while (mapped.length < 14) mapped.push(makeTickerLine());
          setTickerItems(mapped);
        })
        .catch(() => {});
    }
    fetchWins();
    const t = setInterval(fetchWins, 30000);
    return () => clearInterval(t);
  }, []);

  // Live win events — socket pushes each win the moment it's recorded
  useEffect(() => {
    if (!token) return;
    let sock;
    function connect() {
      sock = window.io({ auth: { token } });
      sock.on('win:new', (win) => {
        setTickerItems(prev => {
          const item = { name: win.username, game: GAME_DISPLAY[win.game] || win.game, amt: win.amt };
          const next = [item, ...prev];
          return next.slice(0, 50);
        });
      });
    }
    if (window.io) {
      connect();
    } else {
      const s = document.createElement('script');
      s.src = '/socket.io/socket.io.js';
      s.onload = connect;
      document.head.appendChild(s);
    }
    return () => { if (sock) sock.disconnect(); };
  }, [token]);

  return (
    <div className="lobby">
      <div className="lobby-header">
        <div className="lobby-overline">A Codex of Fortune</div>
        <h1 className="lobby-title">The <em>Games</em></h1>
        <div className="lobby-sub">Place your wagers — the house is always watching.</div>
      </div>

      <div
        className="lobby-hero"
        data-hero={hero.id}
        onClick={() => { window.SoundFX?.chip(); onSelect(hero.id); }}
      >
        <FiligreeCorners />
        <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <div className="lobby-hero-eyebrow">Featured · {hero.heroTag}</div>
          <div className="lobby-hero-name">{hero.name}</div>
          <div className="lobby-hero-tagline">{hero.heroSubtitle}</div>
          <div className="lobby-hero-meta">
            {hero.heroStats.map((s, i) => (
              <div key={i}>
                <div className="lobby-hero-stat-label">{s.label}</div>
                <div className={`lobby-hero-stat-value ${i === 0 ? '' : 'gold'}`}>{s.value}</div>
              </div>
            ))}
          </div>
          <div className="lobby-hero-cta">
            <button className="btn btn-primary btn-lg" onClick={(e) => { e.stopPropagation(); onSelect(hero.id); }}>
              Enter — Play
            </button>
            <span className="fleuron">·❦·</span>
            <span style={{ fontSize: 11, color: 'var(--parch-mute)', fontStyle: 'italic', fontFamily: 'Cormorant Garamond, serif', letterSpacing: '0.08em' }}>
              Featured rotates every seven seconds
            </span>
          </div>
        </div>

        <div className="lobby-hero-visual">
          <div className="lobby-hero-sigil">
            <HeroSigilRings />
            <div className="lobby-hero-sigil-glyph">{hero.glyph}</div>
          </div>
        </div>

        <div className="lobby-hero-dots" onClick={(e) => e.stopPropagation()}>
          {heroes.map((h, i) => (
            <div
              key={h.id}
              className={`lobby-hero-dot ${i === heroIdx ? 'active' : ''}`}
              onClick={() => setHeroIdx(i)}
            />
          ))}
        </div>
      </div>

      <OrnamentSection />

      <div className="game-grid">
        {LOBBY_GAMES.map(g => (
          <div
            key={g.id}
            className="game-card"
            data-game={g.id}
            onClick={() => { window.SoundFX?.chip(); onSelect(g.id); }}
          >
            <div className="game-card-sigil">
              <SigilFrame>
                <span className="sigil-glyph">{g.glyph}</span>
              </SigilFrame>
            </div>
            <div className="game-card-body">
              <div className="game-card-name">{g.name}</div>
              <div className="game-card-desc">{g.tagline}</div>
              <div className="game-card-meta">
                {g.meta.map((m, i) => <span key={i}>{m}</span>)}
              </div>
            </div>
            <div className="game-card-arrow">→</div>
          </div>
        ))}
      </div>

      <div className="wins-ticker">
        <div className="wins-ticker-label">Recent Wins</div>
        <div className="wins-ticker-track">
          <div className="wins-ticker-strip">
            {[...tickerItems, ...tickerItems].map((it, i) => (
              <span key={i} className="wins-ticker-item">
                <span className="wins-ticker-name">{it.name}</span>
                <span>won</span>
                <span className="wins-ticker-amt">+{it.amt.toLocaleString()} G</span>
                <span>at</span>
                <span className="wins-ticker-game">{it.game}</span>
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Lobby = Lobby;
