<?php $pageTitle = 'EL3AB - الملف الشخصي'; ?>
<?php require __DIR__ . '/../includes/header-v2.php'; ?>

<div class="stack-5" id="profile-page">

  <!-- Profile Card -->
  <div class="profile-header">
    <div class="avatar avatar-xl avatar-ring">
      <svg class="icon-xl"><use href="/public/icons/sprite.svg#icon-profile"></use></svg>
    </div>
    <h2 class="t-heading" id="profile-name">---</h2>
    <p class="t-caption" id="profile-username">@---</p>
    <div class="flex gap-2">
      <span class="badge badge-gold" id="profile-level">Lv 1</span>
      <span class="badge badge-cyan" id="profile-title">مبتدئ</span>
    </div>
  </div>

  <!-- Account Level (XP progress) -->
  <div class="card card-pad">
    <div class="flex items-center justify-between" style="margin-bottom:var(--sp-2);">
      <span class="t-caption">مستوى الحساب</span>
      <span class="t-caption" id="xp-progress">0 / 100 XP</span>
    </div>
    <div style="width:100%;height:6px;background:var(--bg-3);border-radius:var(--r-full);overflow:hidden;">
      <div id="xp-bar" style="height:100%;width:0%;background:linear-gradient(90deg,var(--cyan),var(--gold));border-radius:var(--r-full);transition:width 0.5s;"></div>
    </div>
  </div>

  <!-- Per-Game Ratings -->
  <section>
    <div class="sec-header">
      <h2 class="sec-title">تصنيفات الالعاب</h2>
    </div>
    <div class="stack-3" id="profile-ratings">
      <div class="skel" style="height:60px;border-radius:var(--r-md);"></div>
    </div>
  </section>

  <!-- Overall Stats -->
  <section>
    <div class="sec-header">
      <h2 class="sec-title">احصائيات شاملة</h2>
    </div>
    <div class="stats-row" id="profile-stats">
      <div class="stat"><div class="stat-val" id="stat-games">0</div><div class="stat-lbl">مباريات</div></div>
      <div class="stat"><div class="stat-val color-success" id="stat-wins">0</div><div class="stat-lbl">فوز</div></div>
      <div class="stat"><div class="stat-val" id="stat-draws">0</div><div class="stat-lbl">تعادل</div></div>
      <div class="stat"><div class="stat-val color-error" id="stat-losses">0</div><div class="stat-lbl">خسارة</div></div>
    </div>
  </section>

  <!-- Economy -->
  <div class="card card-pad">
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <svg class="icon icon-fill" style="color:var(--gold)"><use href="/public/icons/sprite.svg#icon-coin"></use></svg>
        <div>
          <p style="font-size:14px;font-weight:600;" id="stat-coins">0</p>
          <p class="t-caption">عملات</p>
        </div>
      </div>
      <div class="flex items-center gap-3">
        <svg class="icon icon-fill" style="color:var(--purple)"><use href="/public/icons/sprite.svg#icon-gem"></use></svg>
        <div>
          <p style="font-size:14px;font-weight:600;" id="stat-gems">0</p>
          <p class="t-caption">جواهر</p>
        </div>
      </div>
      <div class="flex items-center gap-3">
        <span style="font-size:18px;">🔥</span>
        <div>
          <p style="font-size:14px;font-weight:600;" id="stat-streak">0</p>
          <p class="t-caption">ايام</p>
        </div>
      </div>
    </div>
  </div>

  <!-- Actions -->
  <div class="stack-2">
    <a href="/settings" class="btn btn-ghost btn-block">
      <svg class="icon"><use href="/public/icons/sprite.svg#icon-settings"></use></svg>
      الاعدادات
    </a>
    <button class="btn btn-ghost btn-block" style="color:var(--error);" onclick="App.logout()">
      <svg class="icon"><use href="/public/icons/sprite.svg#icon-logout"></use></svg>
      تسجيل خروج
    </button>
  </div>

</div>

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

  const [profileData, ratingsData] = await Promise.all([
    App.fetch('/api/profile'),
    App.fetch('/api/ratings.php?action=player')
  ]);

  if (profileData && profileData.profile) {
    const p = profileData.profile;
    document.getElementById('profile-name').textContent = p.display_name || p.username || '---';
    document.getElementById('profile-username').textContent = '@' + (p.username || '---');
    document.getElementById('profile-level').textContent = 'Lv ' + (p.level || 1);
    document.getElementById('stat-games').textContent = p.total_games_played || p.games_played || 0;
    document.getElementById('stat-wins').textContent = p.total_wins || 0;
    document.getElementById('stat-draws').textContent = p.total_draws || 0;
    document.getElementById('stat-losses').textContent = p.total_losses || 0;
    document.getElementById('stat-coins').textContent = (p.coins || 0).toLocaleString();
    document.getElementById('stat-gems').textContent = p.gems || 0;
    document.getElementById('stat-streak').textContent = p.daily_streak || 0;

    // XP bar
    const xp = p.xp || 0;
    const level = p.level || 1;
    App.cachedFetch('/api/config.php?category=xp_levels', 300000).then(cfg => {
      // Fallback: estimate next level XP
    }).catch(() => {});
    const nextLevelXp = [0, 100, 300, 600, 1000, 1500, 2100, 2800, 3600, 4500, 5500][level] || (level * 500);
    const prevLevelXp = [0, 0, 100, 300, 600, 1000, 1500, 2100, 2800, 3600, 4500][level] || ((level - 1) * 500);
    const progress = Math.min(100, Math.round(((xp - prevLevelXp) / (nextLevelXp - prevLevelXp)) * 100));
    document.getElementById('xp-bar').style.width = progress + '%';
    document.getElementById('xp-progress').textContent = xp + ' / ' + nextLevelXp + ' XP';

    // Level title
    const titles = { 1: 'مبتدئ', 2: 'مستجد', 3: 'مستجد ٢', 4: 'لاعب', 5: 'لاعب ٢', 6: 'ماهر', 7: 'ماهر ٢', 8: 'خبير', 9: 'خبير ٢', 10: 'استاذ' };
    document.getElementById('profile-title').textContent = titles[level] || 'لاعب';
  }

  // Per-game ratings
  const container = document.getElementById('profile-ratings');
  const gameNames = { chess: 'شطرنج', ludo: 'لودو', backgammon: 'طاولة', domino: 'دومينو' };
  const modeNames = { bullet: 'بوليت', blitz: 'بليتز', rapid: 'رابيد', classical: 'كلاسيك', default: '' };
  const gameIcons = { chess: 'icon-play', ludo: 'icon-ludo', backgammon: 'icon-backgammon', domino: 'icon-domino' };

  if (ratingsData && ratingsData.ratings && ratingsData.ratings.length > 0) {
    // Group by game
    const grouped = {};
    ratingsData.ratings.forEach(r => {
      if (!grouped[r.game_key]) grouped[r.game_key] = [];
      grouped[r.game_key].push(r);
    });

    let html = '';
    for (const [gameKey, modes] of Object.entries(grouped)) {
      const gameName = gameNames[gameKey] || gameKey;
      const icon = gameIcons[gameKey] || 'icon-play';
      html += '<div class="card card-pad">';
      html += '<div class="flex items-center gap-3" style="margin-bottom:var(--sp-3);">';
      html += '<svg class="icon" style="color:var(--cyan)"><use href="/public/icons/sprite.svg#' + icon + '"></use></svg>';
      html += '<span class="t-subhead">' + gameName + '</span>';
      html += '</div>';
      html += '<div class="stats-row">';
      modes.forEach(r => {
        const label = modeNames[r.mode] || r.mode;
        const winRate = r.games_played > 0 ? Math.round((r.wins / r.games_played) * 100) : 0;
        html += '<div class="stat">';
        html += '<div class="stat-val">' + r.rating + '</div>';
        html += '<div class="stat-lbl">' + (label || 'عام') + '</div>';
        html += '</div>';
      });
      html += '</div>';
      // Win/loss for this game
      const totalGames = modes.reduce((s, m) => s + m.games_played, 0);
      const totalWins = modes.reduce((s, m) => s + m.wins, 0);
      if (totalGames > 0) {
        html += '<p class="t-caption" style="margin-top:var(--sp-2);">' + totalGames + ' مباراة • ' + Math.round((totalWins/totalGames)*100) + '% فوز</p>';
      }
      html += '</div>';
    }
    container.innerHTML = html;
  } else {
    // Fallback to legacy profile elo fields
    if (profileData && profileData.profile) {
      const p = profileData.profile;
      container.innerHTML = '<div class="card card-pad">' +
        '<div class="flex items-center gap-3" style="margin-bottom:var(--sp-3);">' +
        '<svg class="icon" style="color:var(--cyan)"><use href="/public/icons/sprite.svg#icon-play"></use></svg>' +
        '<span class="t-subhead">شطرنج</span></div>' +
        '<div class="stats-row">' +
        '<div class="stat"><div class="stat-val">' + (p.elo_bullet || 1200) + '</div><div class="stat-lbl">بوليت</div></div>' +
        '<div class="stat"><div class="stat-val">' + (p.elo_blitz || 1200) + '</div><div class="stat-lbl">بليتز</div></div>' +
        '<div class="stat"><div class="stat-val">' + (p.elo_rapid || 1200) + '</div><div class="stat-lbl">رابيد</div></div>' +
        '</div></div>';
    }
  }
});
</script>

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