import { state } from '../core/state.js';
import { api, cachedApi } from '../core/api.js';
import { haptics } from '../core/haptics.js';
import { audio } from '../core/audio.js';
import { coinBurst } from '../core/particles.js';
import { tickNumber, pop } from '../core/animate.js';

export default {
  render() {
    return `
      <!-- Daily Streak -->
      <div class="streak" id="streak">
        <span class="streak-fire">🔥</span>
        <div class="streak-text">
          <p class="streak-day" id="streak-day">اليوم 0</p>
          <p class="streak-reward" id="streak-reward">+50 عملة</p>
        </div>
        <button class="streak-btn" id="streak-btn">اجمع</button>
      </div>

      <!-- Games Grid -->
      <section>
        <div class="sec-hdr">
          <h2 class="sec-title">العب</h2>
        </div>
        <div class="game-grid" id="games-grid">
          <div class="skeleton" style="height:120px;border-radius:var(--r-xl)"></div>
          <div class="skeleton" style="height:120px;border-radius:var(--r-xl)"></div>
          <div class="skeleton" style="height:120px;border-radius:var(--r-xl)"></div>
          <div class="skeleton" style="height:120px;border-radius:var(--r-xl)"></div>
        </div>
      </section>

      <!-- Ratings -->
      <section id="ratings-sec" style="display:none">
        <div class="sec-hdr">
          <h2 class="sec-title">تصنيفاتي</h2>
          <a href="/profile" class="sec-link">الكل</a>
        </div>
        <div class="stats-row" id="ratings-grid"></div>
      </section>

      <!-- Recent Games -->
      <section>
        <div class="sec-hdr">
          <h2 class="sec-title">اخر المباريات</h2>
        </div>
        <div class="card" id="recent-games">
          <div class="empty">لم تلعب اي مباراة بعد</div>
        </div>
      </section>
    `;
  },

  async mount(el) {
    const profile = state.get('user');

    // Streak
    if (profile) {
      const streak = profile.daily_streak || 0;
      el.querySelector('#streak-day').textContent = `اليوم ${streak}`;

      const cfgData = await cachedApi('/api/config.php?category=economy', 120000);
      const base = cfgData?.config?.daily_reward_base || 50;
      const bonus = cfgData?.config?.daily_reward_streak_bonus || 10;
      el.querySelector('#streak-reward').textContent = `+${base + streak * bonus} عملة`;

      const today = new Date().toISOString().slice(0, 10);
      const claimed = profile.last_daily_reward === today;
      if (claimed) {
        const btn = el.querySelector('#streak-btn');
        btn.textContent = 'تم ✓';
        btn.disabled = true;
      }
    }

    // Streak claim
    el.querySelector('#streak-btn').addEventListener('click', async (e) => {
      haptics.tap();
      const btn = e.target;
      btn.disabled = true;
      const res = await api('/api/daily-reward', { method: 'POST' });
      if (res?.ok) {
        audio.coin();
        haptics.success();
        const rect = btn.getBoundingClientRect();
        coinBurst(rect.left + rect.width / 2, rect.top);
        btn.textContent = 'تم ✓';
        el.querySelector('#streak-day').textContent = `اليوم ${res.streak}`;
        const coinsEl = document.getElementById('hdr-coins');
        if (coinsEl) tickNumber(coinsEl, parseInt(coinsEl.textContent.replace(/,/g, '')) || 0, res.coins, 800);
      } else if (res?.error === 'already_claimed') {
        btn.textContent = 'تم ✓';
      } else {
        btn.disabled = false;
        audio.error();
        haptics.error();
      }
    });

    // Games grid
    const gamesData = await cachedApi('/api/games.php', 60000);
    if (gamesData?.games) {
      const routes = { chess: '/play', ludo: '/ludo', domino: '/domino', backgammon: '/backgammon' };
      const heroes = { chess: 'game-card-hero--chess', ludo: 'game-card-hero--ludo', domino: 'game-card-hero--domino', backgammon: 'game-card-hero--backgammon' };
      const icons = { chess: 'icon-play', ludo: 'icon-ludo', domino: 'icon-domino', backgammon: 'icon-backgammon' };

      const grid = el.querySelector('#games-grid');
      grid.innerHTML = gamesData.games.filter(g => routes[g.game_key]).map(g => {
        const route = routes[g.game_key];
        const enabled = g.is_enabled;
        return `<a href="${enabled ? route : '#'}" class="game-card" ${!enabled ? 'style="opacity:0.5;pointer-events:none"' : ''}>
          <div class="game-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="game-card-soon">قريبا</span>' : ''}
          </div>
          <div class="game-card-body">
            <span class="game-card-name">${g.name_ar}</span>
            ${enabled ? '<span class="game-card-live"><span class="game-card-live-dot"></span></span>' : ''}
          </div>
        </a>`;
      }).join('');

      grid.querySelectorAll('.game-card').forEach((card, i) => {
        card.style.animationDelay = `${i * 80}ms`;
        card.classList.add('anim-pop');
      });
    }

    // Ratings
    try {
      const ratingsData = await api('/api/ratings.php?action=player');
      if (ratingsData?.ratings?.length) {
        el.querySelector('#ratings-sec').style.display = '';
        const names = { chess: 'شطرنج', ludo: 'لودو', backgammon: 'طاولة', domino: 'دومينو' };
        const modes = { bullet: 'بوليت', blitz: 'بليتز', rapid: 'رابيد', classical: 'كلاسيك', default: '' };
        el.querySelector('#ratings-grid').innerHTML = ratingsData.ratings.map(r => {
          const label = (modes[r.mode] || '') ? `${names[r.game_key] || r.game_key} ${modes[r.mode]}` : (names[r.game_key] || r.game_key);
          return `<div class="stat"><div class="stat-val">${r.rating}</div><div class="stat-lbl">${label}</div></div>`;
        }).join('');
      }
    } catch {}

    // Recent games
    const [gamesRes, botsRes] = await Promise.all([
      api('/api/game?action=recent'),
      cachedApi('/api/bots.php', 60000)
    ]);
    const botMap = {};
    if (botsRes?.bots) botsRes.bots.forEach(b => { botMap[b.id] = b.name_ar?.split(' ')[0] || b.name; });

    if (gamesRes?.games?.length) {
      el.querySelector('#recent-games').innerHTML = `<div class="activity-list">${gamesRes.games.slice(0, 5).map(g => {
        const cls = g.result === 'win' ? 'activity-icon--win' : g.result === 'loss' ? 'activity-icon--loss' : 'activity-icon--draw';
        const text = g.result === 'win' ? 'فوز' : g.result === 'loss' ? 'خسارة' : 'تعادل';
        const color = g.result === 'win' ? 'color:var(--win)' : g.result === 'loss' ? 'color:var(--loss)' : '';
        const icon = g.result === 'win' ? 'check' : g.result === 'loss' ? 'x' : 'clock';
        const name = botMap[g.bot_id] || g.bot_id || '?';
        return `<div class="activity-item">
          <div class="activity-icon ${cls}"><svg class="icon-sm"><use href="/public/icons/sprite.svg#icon-${icon}"></use></svg></div>
          <div class="activity-detail"><p class="activity-name">ضد ${name}</p></div>
          <span class="activity-result" style="${color}">${text}</span>
        </div>`;
      }).join('')}</div>`;
    }
  },

  destroy() {}
};
