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

const CATEGORY_LABELS = {
  gameplay: () => t('achievements.gameplay'),
  social: () => t('achievements.social'),
  progression: () => t('achievements.progression'),
  collection: () => t('achievements.collection'),
};

const TIER_COLORS = {
  1: 'var(--text-secondary)',
  2: 'var(--green)',
  3: 'var(--gold)',
  4: 'var(--purple-light)',
};

export async function mountAchievements(el) {
  el.innerHTML = `<div style="display:flex;align-items:center;justify-content:center;height:100%;background:var(--bg-deep);color:var(--text-muted);">${t('common.loading')}</div>`;

  let achievements = [];
  let stats = { total: 0, completed: 0 };

  try {
    const data = await net.get('achievements.php');
    if (data && !data.error) {
      achievements = data.achievements || [];
      stats = data.stats || stats;
    }
  } catch (e) {}

  net.post('achievements.php', { action: 'check' }).then(res => {
    if (res && res.newly_completed && res.newly_completed.length > 0) {
      juice.hapticSuccess();
      audio.play('reward');
      res.newly_completed.forEach(id => {
        const a = achievements.find(x => x.id === id);
        if (a) { a.completed = true; a.progress = a.target; }
      });
      stats.completed = achievements.filter(a => a.completed).length;
      render(el, achievements, stats);
    }
  }).catch(() => {});

  render(el, achievements, stats);
}

function render(el, achievements, stats) {
  const categories = [...new Set(achievements.map(a => a.category))];
  const progressPct = stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0;

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-deep);">
      <!-- Header -->
      <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;background:var(--bg-panel);border-bottom:1px solid var(--border);">
        <button class="btn btn-secondary" id="back-btn" style="min-height:32px;padding:4px 12px;font-size:12px;">←</button>
        <span style="font-size:16px;font-weight:700;color:var(--text-primary);">${emoji('trophy', '🏆', 16)} ${t('achievements.title')}</span>
        <span style="margin-inline-start:auto;font-size:12px;color:var(--text-muted);">${stats.completed}/${stats.total}</span>
      </div>

      <!-- Progress bar -->
      <div style="padding:12px 16px 0;">
        <div style="background:var(--bg-card);border-radius:99px;height:8px;overflow:hidden;">
          <div style="background:linear-gradient(90deg,var(--gold),var(--gold-soft));height:100%;width:${progressPct}%;border-radius:99px;transition:width 0.5s;"></div>
        </div>
        <div style="display:flex;justify-content:space-between;margin-top:4px;">
          <span style="font-size:10px;color:var(--text-muted);">${progressPct}% ${t('achievements.complete')}</span>
          <span style="font-size:10px;color:var(--gold);">${stats.completed} ${t('achievements.title')}</span>
        </div>
      </div>

      <!-- Category filter -->
      <div style="display:flex;gap:6px;padding:12px 16px;overflow-x:auto;">
        <button class="ach-filter active" data-cat="all">${t('achievements.all')}</button>
        ${categories.map(c => `<button class="ach-filter" data-cat="${c}">${CATEGORY_LABELS[c] ? CATEGORY_LABELS[c]() : c}</button>`).join('')}
      </div>

      <!-- Achievement list -->
      <div id="ach-list" style="flex:1;overflow-y:auto;padding:0 16px 16px;display:flex;flex-direction:column;gap:8px;">
        ${renderList(achievements, 'all')}
      </div>
    </div>

    <style>
      .ach-filter{background:var(--bg-card);border:1px solid var(--border);color:var(--text-secondary);font-size:11px;padding:6px 12px;border-radius:99px;cursor:pointer;white-space:nowrap;font-family:inherit;font-weight:600;}
      .ach-filter.active{background:var(--gold);color:var(--bg-dark);border-color:var(--gold);}
      .ach-card{display:flex;align-items:center;gap:12px;padding:12px;background:var(--bg-panel);border-radius:12px;border:1px solid var(--border);}
      .ach-card.completed{border-color:rgba(34,197,94,0.3);background:#0a1a0a;}
    </style>
  `;

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

  el.querySelectorAll('.ach-filter').forEach(btn => {
    btn.addEventListener('click', () => {
      el.querySelectorAll('.ach-filter').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      el.querySelector('#ach-list').innerHTML = renderList(achievements, btn.dataset.cat);
    });
  });
}

function renderList(achievements, category) {
  const filtered = category === 'all' ? achievements : achievements.filter(a => a.category === category);
  if (filtered.length === 0) {
    return `<div style="text-align:center;padding:32px;color:var(--text-dim);font-size:13px;">${t('achievements.none')}</div>`;
  }

  return filtered.map(a => {
    const pct = a.target > 0 ? Math.min(100, Math.round((a.progress / a.target) * 100)) : 0;
    const tierColor = TIER_COLORS[a.tier] || TIER_COLORS[1];

    return `
      <div class="ach-card ${a.completed ? 'completed' : ''}">
        <div style="width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:20px;
          background:${a.completed ? 'linear-gradient(135deg,#166534,var(--green))' : 'var(--bg-card)'};
          border:2px solid ${a.completed ? 'var(--green)' : tierColor};">
          ${a.completed ? '✓' : tierIcon(a.tier)}
        </div>
        <div style="flex:1;min-width:0;">
          <div style="font-size:13px;font-weight:600;color:${a.completed ? 'var(--success)' : 'var(--text-primary)'};margin-bottom:2px;">${a.name}</div>
          <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px;">${a.description}</div>
          ${!a.completed ? `
            <div style="display:flex;align-items:center;gap:6px;">
              <div style="flex:1;background:var(--bg-card);border-radius:99px;height:4px;overflow:hidden;">
                <div style="background:${tierColor};height:100%;width:${pct}%;border-radius:99px;"></div>
              </div>
              <span style="font-size:10px;color:var(--text-muted);white-space:nowrap;">${a.progress}/${a.target}</span>
            </div>
          ` : `
            <div style="font-size:10px;color:var(--green);">✓ ${t('achievements.complete')}</div>
          `}
        </div>
        <div style="text-align:center;min-width:40px;">
          <div style="font-size:11px;font-weight:700;color:var(--gold);">${a.coins_reward}</div>
          <div style="font-size:9px;color:var(--text-muted);">${t('game.coins')}</div>
        </div>
      </div>
    `;
  }).join('');
}

function tierIcon(tier) {
  const icons = { 1: emoji('star', '⭐', 16), 2: emoji('star_glow', '🌟', 16), 3: emoji('sparkles', '💫', 16), 4: emoji('crown', '👑', 16) };
  return icons[tier] || emoji('star', '⭐', 16);
}
