<?php $pageTitle = 'EL3AB'; ?>
<?php require __DIR__ . '/../includes/header-v2.php'; ?>

<div class="stack-5" id="home">

  <!-- Hero: Quick Play (inline matchmaking from home) -->
  <div class="hero-play">
    <div class="hero-play-top">
      <div>
        <p class="hero-play-title" id="home-greeting">مرحبا</p>
        <p class="hero-play-subtitle" id="home-rank"></p>
      </div>
      <div class="badge badge-gold" id="home-level">Lv 1</div>
    </div>
    <div class="chip-group" id="home-tc">
      <button class="chip active" data-tc="bullet_1_1" data-time="60000" data-inc="1000">1+1</button>
      <button class="chip" data-tc="blitz_3_0" data-time="180000" data-inc="0">3+0</button>
      <button class="chip" data-tc="blitz_5_0" data-time="300000" data-inc="0">5+0</button>
      <button class="chip" data-tc="rapid_10_0" data-time="600000" data-inc="0">10+0</button>
    </div>
    <button class="hero-play-btn" id="home-play-btn" onclick="quickPlay()">
      <svg class="icon"><use href="/public/icons/sprite.svg#icon-search"></use></svg>
      العب شطرنج الان
    </button>
  </div>

  <!-- Daily Streak -->
  <div class="streak-banner" id="streak-section">
    <div class="streak-banner-icon">🔥</div>
    <div class="streak-banner-text">
      <p class="streak-banner-day" id="streak-day">اليوم 0</p>
      <p class="streak-banner-reward" id="streak-reward">+50 عملة</p>
    </div>
    <button class="streak-banner-btn" id="streak-btn">اجمع</button>
  </div>
  <div class="streak-cal" id="streak-cal">
    <div class="streak-cal-day" data-day="1">1</div>
    <div class="streak-cal-day" data-day="2">2</div>
    <div class="streak-cal-day" data-day="3">3</div>
    <div class="streak-cal-day" data-day="4">4</div>
    <div class="streak-cal-day" data-day="5">5</div>
    <div class="streak-cal-day" data-day="6">6</div>
    <div class="streak-cal-day" data-day="7">7</div>
  </div>

  <!-- All Games Grid -->
  <section>
    <div class="sec-header">
      <h2 class="sec-title">العاب</h2>
      <a href="/games" class="sec-link">الكل</a>
    </div>
    <div class="quick-play-grid" id="home-games">
      <div class="skel" style="height:110px;border-radius:var(--r-lg);"></div>
      <div class="skel" style="height:110px;border-radius:var(--r-lg);"></div>
      <div class="skel" style="height:110px;border-radius:var(--r-lg);"></div>
      <div class="skel" style="height:110px;border-radius:var(--r-lg);"></div>
    </div>
  </section>

  <!-- My Ratings (multi-game) -->
  <section id="ratings-section" style="display:none;">
    <div class="sec-header">
      <h2 class="sec-title">تصنيفاتي</h2>
    </div>
    <div class="stats-row" id="home-ratings"></div>
  </section>

  <!-- Recent Games -->
  <section>
    <div class="sec-header">
      <h2 class="sec-title">اخر المباريات</h2>
    </div>
    <div class="card" id="home-recent">
      <div class="empty">لم تلعب اي مباراة بعد</div>
    </div>
  </section>

</div>

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

  const data = await App.fetch('/api/profile');
  if (data && data.profile) {
    const p = data.profile;
    document.getElementById('home-greeting').textContent = (p.display_name || p.username) + '، العب!';
    document.getElementById('home-level').textContent = 'Lv ' + (p.level || 1);

    const streak = p.daily_streak || 0;
    document.getElementById('streak-day').textContent = 'اليوم ' + streak;

    App.cachedFetch('/api/config.php?category=economy', 120000).then(cfg => {
      const base = (cfg && cfg.config && cfg.config.daily_reward_base) || 50;
      const bonus = (cfg && cfg.config && cfg.config.daily_reward_streak_bonus) || 10;
      document.getElementById('streak-reward').textContent = '+' + (base + streak * bonus) + ' عملة';
    }).catch(() => {
      document.getElementById('streak-reward').textContent = '+' + (50 + streak * 10) + ' عملة';
    });

    const claimedToday = p.last_daily_reward === new Date().toISOString().slice(0, 10);
    const days = document.querySelectorAll('.streak-cal-day');
    days.forEach((day, i) => {
      const dayNum = i + 1;
      const streakDay = ((streak - 1) % 7) + 1;
      if (dayNum < streakDay || (dayNum === streakDay && claimedToday)) {
        day.classList.add('claimed');
      } else if (dayNum === streakDay + (claimedToday ? 0 : 1) || (streak === 0 && dayNum === 1)) {
        day.classList.add('current');
      }
    });

    if (claimedToday) {
      const btn = document.getElementById('streak-btn');
      btn.textContent = 'تم ✓';
      btn.disabled = true;
    }
  }

  // Load multi-game ratings
  try {
    const ratingsData = await App.fetch('/api/ratings.php?action=player');
    if (ratingsData && ratingsData.ratings && ratingsData.ratings.length > 0) {
      document.getElementById('ratings-section').style.display = '';
      const container = document.getElementById('home-ratings');
      const gameNames = { chess: 'شطرنج', ludo: 'لودو', backgammon: 'طاولة', domino: 'دومينو' };
      const modeNames = { bullet: 'بوليت', blitz: 'بليتز', rapid: 'رابيد', classical: 'كلاسيك', default: '' };

      container.innerHTML = ratingsData.ratings.map(r => {
        const gameName = gameNames[r.game_key] || r.game_key;
        const modeName = modeNames[r.mode] || r.mode;
        const label = modeName ? gameName + ' ' + modeName : gameName;
        return '<div class="stat"><div class="stat-val">' + r.rating + '</div><div class="stat-lbl">' + label + '</div></div>';
      }).join('');

      // Also update home-rank subtitle with best rating
      const best = ratingsData.ratings.reduce((a, b) => a.rating > b.rating ? a : b);
      const bestMode = modeNames[best.mode] || '';
      const bestGame = gameNames[best.game_key] || '';
      document.getElementById('home-rank').textContent = bestGame + ' ' + bestMode + ' ' + best.rating;
    } else {
      // Fallback to legacy profile elo fields
      if (data && data.profile) {
        const p = data.profile;
        document.getElementById('home-rank').textContent = 'بليتز ' + (p.elo_blitz || 1200);
      }
    }
  } catch (e) {
    if (data && data.profile) {
      document.getElementById('home-rank').textContent = 'بليتز ' + (data.profile.elo_blitz || 1200);
    }
  }

  // Games grid
  try {
    const gData = await App.cachedFetch('/api/games.php', 60000);
    if (gData && gData.games) {
      const routes = { chess: '/play', ludo: '/ludo', domino: '/domino', backgammon: '/backgammon' };
      const heroes = { chess: 'qp-card-hero--chess', ludo: 'qp-card-hero--ludo', domino: 'qp-card-hero--domino', backgammon: 'qp-card-hero--backgammon' };
      const icons = { chess: 'icon-play', ludo: 'icon-ludo', domino: 'icon-domino', backgammon: 'icon-backgammon' };
      const grid = document.getElementById('home-games');
      grid.innerHTML = gData.games.filter(g => routes[g.game_key]).map(g => {
        const route = routes[g.game_key];
        const enabled = g.is_enabled && route;
        return '<a href="' + (enabled ? route : '#') + '" class="qp-card">' +
          '<div class="qp-card-hero ' + (heroes[g.game_key] || '') + '">' +
            '<svg class="icon-xl"><use href="/public/icons/sprite.svg#' + (icons[g.game_key] || 'icon-play') + '"></use></svg>' +
            (enabled ? '' : '<span class="qp-card-soon">قريبا</span>') +
          '</div>' +
          '<div class="qp-card-body">' +
            '<span class="qp-card-name">' + g.name_ar + '</span>' +
            (enabled ? '<span class="qp-card-live"><span class="qp-card-live-dot"></span></span>' : '') +
          '</div></a>';
      }).join('');
    }
  } catch (e) {}

  // Recent games
  const [gamesData, botsData] = await Promise.all([
    App.fetch('/api/game?action=recent'),
    App.cachedFetch('/api/bots.php', 60000)
  ]);
  const botMap = {};
  if (botsData && botsData.bots) {
    botsData.bots.forEach(b => { botMap[b.id] = b.name_ar ? b.name_ar.split(' ')[0] : b.name; });
  }
  if (gamesData && gamesData.games && gamesData.games.length > 0) {
    const container = document.getElementById('home-recent');
    container.innerHTML = '<div class="activity-list">' + gamesData.games.slice(0, 5).map(g => {
      const iconClass = g.result === 'win' ? 'activity-icon--win' : g.result === 'loss' ? 'activity-icon--loss' : 'activity-icon--draw';
      const resultText = g.result === 'win' ? 'فوز' : g.result === 'loss' ? 'خسارة' : 'تعادل';
      const resultColor = g.result === 'win' ? 'color-success' : g.result === 'loss' ? 'color-error' : '';
      const iconName = g.result === 'win' ? 'check' : g.result === 'loss' ? 'x' : 'clock';
      const botName = botMap[g.bot_id] || g.bot_id || '?';
      return '<div class="activity-item">' +
        '<div class="activity-icon ' + iconClass + '"><svg class="icon-sm"><use href="/public/icons/sprite.svg#icon-' + iconName + '"></use></svg></div>' +
        '<div class="activity-detail"><p class="activity-opponent">ضد ' + botName + '</p></div>' +
        '<span class="activity-result ' + resultColor + '">' + resultText + '</span>' +
      '</div>';
    }).join('') + '</div>';
  }

  // Streak claim
  document.getElementById('streak-btn').addEventListener('click', async () => {
    const res = await App.fetch('/api/daily-reward', { method: 'POST' });
    if (res && res.ok) {
      App.toast('+' + res.reward + ' عملة!', 'success');
      document.getElementById('streak-btn').textContent = 'تم ✓';
      document.getElementById('streak-btn').disabled = true;
      document.getElementById('streak-day').textContent = 'اليوم ' + res.streak;
      App.loadProfile();
    } else if (res && res.error === 'already_claimed') {
      App.toast('لقد جمعت المكافأة اليوم', 'error');
    }
  });

  // TC chip selection
  document.querySelectorAll('#home-tc .chip').forEach(chip => {
    chip.addEventListener('click', () => {
      document.querySelectorAll('#home-tc .chip').forEach(c => c.classList.remove('active'));
      chip.classList.add('active');
    });
  });
});

function quickPlay() {
  const active = document.querySelector('#home-tc .chip.active');
  const tc = active.dataset.tc;
  const time = active.dataset.time;
  const inc = active.dataset.inc;
  window.location.href = '/matchmaking?tc=' + tc + '&time=' + time + '&inc=' + inc;
}
</script>

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