<?php $pageTitle = 'EL3AB - المتصدرين'; ?>
<?php require __DIR__ . '/../includes/header-v2.php'; ?>

<div class="stack-5">

  <h2 class="t-display" style="text-align:center;">المتصدرين</h2>

  <!-- Game selector -->
  <div class="chip-group" id="lb-games" style="justify-content:center;">
    <button class="chip chip-gold active" data-game="chess">شطرنج</button>
    <button class="chip chip-gold" data-game="backgammon">طاولة</button>
    <button class="chip chip-gold" data-game="domino">دومينو</button>
    <button class="chip chip-gold" data-game="ludo">لودو</button>
  </div>

  <!-- Mode selector (changes per game) -->
  <div class="chip-group" id="lb-modes" style="justify-content:center;"></div>

  <!-- Podium -->
  <div class="lb-podium" id="lb-podium">
    <div class="lb-podium-item lb-podium-item--second" id="podium-2">
      <div class="lb-rank lb-rank--2">2</div>
      <div class="avatar avatar-sm"><svg class="icon"><use href="/public/icons/sprite.svg#icon-profile"></use></svg></div>
      <p class="t-caption">---</p>
      <p class="t-caption" style="color:var(--text-1);font-weight:700;">---</p>
    </div>
    <div class="lb-podium-item lb-podium-item--first" id="podium-1">
      <div class="lb-rank lb-rank--1">1</div>
      <div class="avatar avatar-lg avatar-ring"><svg class="icon-lg"><use href="/public/icons/sprite.svg#icon-profile"></use></svg></div>
      <p style="font-size:14px;font-weight:700;">---</p>
      <p class="t-caption" style="color:var(--gold);font-weight:700;">---</p>
    </div>
    <div class="lb-podium-item lb-podium-item--third" id="podium-3">
      <div class="lb-rank lb-rank--3">3</div>
      <div class="avatar avatar-sm"><svg class="icon"><use href="/public/icons/sprite.svg#icon-profile"></use></svg></div>
      <p class="t-caption">---</p>
      <p class="t-caption" style="color:var(--text-1);font-weight:700;">---</p>
    </div>
  </div>

  <!-- Full List -->
  <div class="card" id="lb-list">
    <div class="empty">جاري التحميل...</div>
  </div>

</div>

<script>
const GAME_MODES = {
  chess: ['bullet', 'blitz', 'rapid', 'classical'],
  backgammon: ['default'],
  domino: ['default'],
  ludo: ['default']
};

const MODE_NAMES = { bullet: 'بوليت', blitz: 'بليتز', rapid: 'رابيد', classical: 'كلاسيك', default: 'عام' };

let currentGame = 'chess';
let currentMode = 'blitz';

document.addEventListener('DOMContentLoaded', () => {
  if (!App.isLoggedIn()) { window.location.href = '/login'; return; }

  // Game selection
  document.querySelectorAll('#lb-games .chip').forEach(chip => {
    chip.addEventListener('click', () => {
      document.querySelectorAll('#lb-games .chip').forEach(c => c.classList.remove('active'));
      chip.classList.add('active');
      currentGame = chip.dataset.game;
      renderModes();
      loadLeaderboard();
    });
  });

  renderModes();
  loadLeaderboard();
});

function renderModes() {
  const modes = GAME_MODES[currentGame];
  const container = document.getElementById('lb-modes');

  if (modes.length <= 1) {
    container.innerHTML = '';
    currentMode = modes[0];
    return;
  }

  container.innerHTML = modes.map((m, i) => {
    const active = (currentGame === 'chess' && m === 'blitz') || (i === 0 && currentGame !== 'chess') ? ' active' : '';
    if (active) currentMode = m;
    return '<button class="chip' + active + '" data-mode="' + m + '">' + MODE_NAMES[m] + '</button>';
  }).join('');

  container.querySelectorAll('.chip').forEach(chip => {
    chip.addEventListener('click', () => {
      container.querySelectorAll('.chip').forEach(c => c.classList.remove('active'));
      chip.classList.add('active');
      currentMode = chip.dataset.mode;
      loadLeaderboard();
    });
  });
}

async function loadLeaderboard() {
  // Try new API first, fallback to legacy
  let players = [];
  try {
    const data = await App.fetch('/api/ratings.php?action=leaderboard&game=' + currentGame + '&mode=' + currentMode);
    if (data && data.leaderboard && data.leaderboard.length > 0) {
      players = data.leaderboard;
    }
  } catch (e) {}

  // Fallback to legacy leaderboard for chess
  if (players.length === 0 && currentGame === 'chess') {
    try {
      const legacy = await App.fetch('/api/leaderboard?mode=' + currentMode);
      if (legacy && legacy.players) {
        players = legacy.players.map((p, i) => ({
          rank: i + 1,
          player_id: p.id,
          username: p.username,
          display_name: p.display_name,
          rating: p['elo_' + currentMode] || 1200,
          games_played: 0,
          wins: 0
        }));
      }
    } catch (e) {}
  }

  // Update podium
  for (let i = 1; i <= 3; i++) {
    const el = document.getElementById('podium-' + i);
    const p = players[i - 1];
    if (p) {
      el.querySelector('p:not(.t-caption), p[style]').textContent = p.display_name || p.username || '---';
      const ratingEl = el.querySelectorAll('p')[el.querySelectorAll('p').length - 1];
      ratingEl.textContent = p.rating;
    }
  }

  // Update list
  const list = document.getElementById('lb-list');
  if (players.length > 3) {
    list.innerHTML = players.slice(3).map(p => {
      const winRate = p.games_played > 0 ? Math.round((p.wins / p.games_played) * 100) + '%' : '--';
      return '<div class="lb-list-item">' +
        '<span class="lb-list-rank">' + p.rank + '</span>' +
        '<div class="avatar avatar-sm"><svg class="icon-sm"><use href="/public/icons/sprite.svg#icon-profile"></use></svg></div>' +
        '<span class="lb-list-name">' + (p.display_name || p.username || '---') + '</span>' +
        '<span class="lb-list-elo">' + p.rating + '</span>' +
      '</div>';
    }).join('');
  } else if (players.length === 0) {
    list.innerHTML = '<div class="empty">لا يوجد لاعبين كافيين بعد (يلزم 5 مباريات)</div>';
  } else {
    list.innerHTML = '';
  }
}
</script>

<?php require __DIR__ . '/../includes/footer-v2.php'; ?>
