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 { t } from '../../../core/i18n.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:var(--text-primary);flex:1;">${emoji('lightning', '⚡', 18)} ${t('challenges.title')}</h2>
        <div id="streak-badge" style="background:linear-gradient(135deg,var(--gold),var(--gold-soft));color:var(--bg-dark);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:var(--success);">${t('challenges.all_done')}</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:var(--error);">${t('common.error_load')}</div>`;
  }
}

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

  el.querySelector('#streak-badge').innerHTML = `${emoji('fire', '🔥', 12)} ${t('challenges.streak', { n: streak || 0 })}`;

  const list = el.querySelector('#challenges-list');
  list.innerHTML = challenges.map((c, i) => `
    <div class="challenge-card" data-idx="${i}" style="background:var(--bg-card);border-radius:14px;padding:14px;display:flex;align-items:center;gap:12px;border:1px solid var(--border);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:var(--text-primary);">${c.title}</div>
        <div style="display:flex;align-items:center;gap:8px;margin-top:4px;">
          <div style="flex:1;height:5px;background:var(--bg-hover);border-radius:3px;overflow:hidden;">
            <div style="height:100%;width:${Math.min(100, (c.progress / c.target) * 100)}%;background:${c.completed ? 'var(--success)' : 'var(--gold)'};border-radius:3px;transition:width 0.3s;"></div>
          </div>
          <span style="font-size:10px;color:var(--text-muted);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:var(--success);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:var(--gold);color:var(--bg-dark);border:none;border-radius:8px;padding:6px 10px;font-size:11px;font-weight:700;cursor:pointer;">${t('challenges.claim')}</button>` :
          `<span style="font-size:11px;color:var(--gold);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 = 'var(--success)';
      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) {}
    });
  });
}
