<?php $pageTitle = 'EL3AB - الرئيسية'; ?>
<?php require __DIR__ . '/../includes/header.php'; ?>

<div class="space-y-6" id="home-content">

  <!-- Welcome -->
  <div class="text-center">
    <h2 style="font-size:22px;font-weight:700;" id="home-welcome">اهلا يا لاعب</h2>
    <p class="text-muted text-sm" id="home-subtitle">المستوى 1</p>
  </div>

  <!-- Play Button -->
  <a href="/games" class="btn btn-gold btn-block btn-lg">
    <svg class="icon"><use href="/public/icons/sprite.svg#icon-games"></use></svg>
    العب الان
  </a>

  <!-- Daily Reward + Streak Calendar -->
  <div class="card">
    <div class="card-body" style="display:flex;align-items:center;justify-content:space-between;">
      <div style="display:flex;align-items:center;gap:12px;">
        <svg class="icon-lg" style="color:var(--warning)"><use href="/public/icons/sprite.svg#icon-fire"></use></svg>
        <div>
          <p style="font-size:14px;font-weight:600;" id="home-streak">اليوم 0</p>
          <p class="text-muted text-xs" id="home-streak-reward">+50 عملة</p>
        </div>
      </div>
      <button class="btn btn-cyan btn-sm" id="home-claim-btn">اجمع</button>
    </div>
    <div class="streak-strip" id="streak-strip">
      <div class="streak-day" data-day="1"><span class="streak-day-num">1</span></div>
      <div class="streak-day" data-day="2"><span class="streak-day-num">2</span></div>
      <div class="streak-day" data-day="3"><span class="streak-day-num">3</span></div>
      <div class="streak-day" data-day="4"><span class="streak-day-num">4</span></div>
      <div class="streak-day" data-day="5"><span class="streak-day-num">5</span></div>
      <div class="streak-day" data-day="6"><span class="streak-day-num">6</span></div>
      <div class="streak-day" data-day="7"><span class="streak-day-num">7</span></div>
    </div>
  </div>

  <!-- Recent Games -->
  <section>
    <p class="section-title">اخر المباريات</p>
    <div class="card" id="home-recent-games">
      <div class="empty-state">لم تلعب اي مباراة بعد</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-welcome').textContent = 'اهلا يا ' + (p.display_name || p.username);
    document.getElementById('home-subtitle').textContent = 'المستوى ' + (p.level || 1) + ' • ' + (p.elo_blitz || 1200) + ' بليتز';
    const streak = p.daily_streak || 0;
    document.getElementById('home-streak').textContent = 'اليوم ' + streak;
    // Load reward config from API
    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('home-streak-reward').textContent = '+' + (base + streak * bonus) + ' عملة';
    }).catch(() => {
      document.getElementById('home-streak-reward').textContent = '+' + (50 + streak * 10) + ' عملة';
    });

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

    if (claimedToday) {
      document.getElementById('home-claim-btn').textContent = 'تم';
      document.getElementById('home-claim-btn').disabled = true;
      document.getElementById('home-claim-btn').classList.add('btn-ghost');
      document.getElementById('home-claim-btn').classList.remove('btn-cyan');
    }
  }

  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.split(' ')[0]; });
  }
  if (gamesData && gamesData.games && gamesData.games.length > 0) {
    const container = document.getElementById('home-recent-games');
    container.innerHTML = gamesData.games.slice(0, 5).map(g => {
      const resultClass = g.result === 'win' ? 'color:var(--success)' : g.result === 'loss' ? 'color:var(--error)' : 'color:var(--text-3)';
      const resultText = g.result === 'win' ? 'فوز' : g.result === 'loss' ? 'خسارة' : 'تعادل';
      const resultIcon = g.result === 'win' ? 'check' : g.result === 'loss' ? 'x' : 'clock';
      const botName = botMap[g.bot_id] || g.bot_id || '?';
      return '<div style="display:flex;align-items:center;gap:12px;padding:10px 16px;border-bottom:1px solid var(--border);">' +
        '<svg class="icon" style="' + resultClass + '"><use href="/public/icons/sprite.svg#icon-' + resultIcon + '"></use></svg>' +
        '<div style="flex:1;"><p style="font-size:13px;font-weight:600;">ضد ' + botName + '</p></div>' +
        '<span class="badge" style="' + resultClass + '">' + resultText + '</span>' +
      '</div>';
    }).join('');
  }

  document.getElementById('home-claim-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('home-claim-btn').textContent = 'تم';
      document.getElementById('home-claim-btn').disabled = true;
      document.getElementById('home-streak').textContent = 'اليوم ' + res.streak;
      App.loadProfile();
    } else if (res && res.error === 'already_claimed') {
      App.toast('لقد جمعت المكافأة اليوم', 'error');
    }
  });
});
</script>

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