import * as net from '../../../core/net.js';
import * as audio from '../../../core/audio.js';
import * as juice from '../../../core/juice.js';
import * as bus from '../../../core/bus.js';
import * as store from '../../../core/store.js';
import * as scene from '../../../core/scene.js';
import { emoji } from '../../../core/theme.js';

export async function mountChallenges(el) {
  el.innerHTML = `
    <div style="padding:16px;display:flex;flex-direction:column;gap:14px;">
      <div style="display:flex;align-items:center;gap:12px;">
        <button class="btn btn-secondary" id="back-btn" style="min-height:32px;padding:4px 12px;font-size:12px;">←</button>
        <h2 style="font-size:18px;font-weight:800;color:#f8fafc;flex:1;">${emoji('lightning', '⚡', 18)} التحديات اليومية</h2>
        <div id="streak-badge" style="background:linear-gradient(135deg,#E4AC38,#FFCC66);color:#1a1a1a;font-size:12px;font-weight:800;padding:5px 12px;border-radius:99px;"></div>
      </div>
      <div id="challenges-list"></div>
      <div id="all-done" style="display:none;text-align:center;padding:20px;">
        <div style="font-size:40px;margin-bottom:8px;">${emoji('checkmark', '✅', 40)}</div>
        <div style="font-size:15px;font-weight:700;color:#34D399;">أنجزت كل التحديات اليوم!</div>
      </div>
    </div>
  `;

  el.querySelector('#back-btn').addEventListener('click', () => { audio.play('click'); scene.pop(); });

  try {
    const data = await net.get('challenges.php');
    renderChallenges(el, data);
  } catch (e) {
    el.querySelector('#challenges-list').innerHTML = '<div style="text-align:center;color:#ef4444;">فشل التحميل</div>';
  }
}

function renderChallenges(el, data) {
  const { challenges, streak, streak_bonus } = data;

  el.querySelector('#streak-badge').textContent = `🔥 ${streak || 0} يوم`;

  const list = el.querySelector('#challenges-list');
  list.innerHTML = challenges.map((c, i) => `
    <div class="challenge-card" data-idx="${i}" style="background:#1a1a2e;border-radius:14px;padding:14px;display:flex;align-items:center;gap:12px;border:1px solid rgba(255,255,255,0.05);transition:transform 0.1s;">
      <div style="width:44px;height:44px;border-radius:10px;background:rgba(228,172,56,0.1);display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0;">${c.icon}</div>
      <div style="flex:1;">
        <div style="font-size:13px;font-weight:700;color:#f8fafc;">${c.title}</div>
        <div style="display:flex;align-items:center;gap:8px;margin-top:4px;">
          <div style="flex:1;height:5px;background:#2a2a4a;border-radius:3px;overflow:hidden;">
            <div style="height:100%;width:${Math.min(100, (c.progress / c.target) * 100)}%;background:${c.completed ? '#34D399' : '#E4AC38'};border-radius:3px;transition:width 0.3s;"></div>
          </div>
          <span style="font-size:10px;color:#64748b;min-width:30px;text-align:left;">${c.progress}/${c.target}</span>
        </div>
      </div>
      <div style="text-align:center;min-width:50px;">
        ${c.claimed ? '<span style="color:#34D399;font-size:16px;">✓</span>' :
          c.completed ? `<button class="claim-btn" data-id="${c.id}" data-coins="${c.reward_coins}" data-xp="${c.reward_xp}" style="background:#E4AC38;color:#1a1a1a;border:none;border-radius:8px;padding:6px 10px;font-size:11px;font-weight:700;cursor:pointer;">اجمع</button>` :
          `<span style="font-size:11px;color:#E4AC38;font-weight:600;">${c.reward_coins}${emoji('coin', '🪙', 14)}</span>`}
      </div>
    </div>
  `).join('');

  // Stagger animation
  const cards = list.querySelectorAll('.challenge-card');
  juice.stagger(Array.from(cards), juice.slideUpBounce, 0, 80);

  // Claim buttons
  list.querySelectorAll('.claim-btn').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      audio.play('coin', 'reward');
      juice.hapticSuccess();

      const id = btn.dataset.id;
      const coins = parseInt(btn.dataset.coins);
      const xp = parseInt(btn.dataset.xp);

      btn.textContent = '✓';
      btn.style.background = '#34D399';
      btn.disabled = true;

      // Coin burst from button position
      const rect = btn.getBoundingClientRect();
      juice.coinBurst(rect.left + rect.width/2, rect.top, 6);
      juice.coinFlyTo(rect.left, rect.top, '#hud-coins', 4);

      try {
        await net.post('challenges.php', { action: 'claim', challenge_id: id, coins, xp });
        bus.emit('coins:earned', { amount: coins });
        bus.emit('xp:earned', { amount: xp });
      } catch (e) {}
    });
  });
}
