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 { emoji } from '../../../core/theme.js';

const CATEGORY_LABELS = {
  gameplay: 'اللعب',
  social: 'اجتماعي',
  progression: 'التقدم',
  collection: 'جمع',
};

const TIER_COLORS = {
  1: '#94a3b8',
  2: '#22c55e',
  3: '#E4AC38',
  4: '#a855f7',
};

export async function mountAchievements(el) {
  el.innerHTML = `<div style="display:flex;align-items:center;justify-content:center;height:100%;background:#0a0a1a;color:#64748b;">جاري التحميل...</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) {}

  // Also trigger a check to update progress
  net.post('achievements.php', { action: 'check' }).then(res => {
    if (res && res.newly_completed && res.newly_completed.length > 0) {
      juice.hapticSuccess();
      audio.play('reward');
      // Re-mount to show updated state
      mountAchievements(el);
    }
  }).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:#0a0a1a;">
      <!-- Header -->
      <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;background:#0f0f1e;border-bottom:1px solid rgba(255,255,255,0.06);">
        <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:#f8fafc;">${emoji('trophy', '🏆', 16)} الإنجازات</span>
        <span style="margin-inline-start:auto;font-size:12px;color:#64748b;">${stats.completed}/${stats.total}</span>
      </div>

      <!-- Progress bar -->
      <div style="padding:12px 16px 0;">
        <div style="background:#1a1a2e;border-radius:99px;height:8px;overflow:hidden;">
          <div style="background:linear-gradient(90deg,#E4AC38,#FFCC66);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:#64748b;">${progressPct}% مكتمل</span>
          <span style="font-size:10px;color:#E4AC38;">${stats.completed} إنجاز</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">الكل</button>
        ${categories.map(c => `<button class="ach-filter" data-cat="${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:#1a1a2e;border:1px solid rgba(255,255,255,0.06);color:#94a3b8;font-size:11px;padding:6px 12px;border-radius:99px;cursor:pointer;white-space:nowrap;font-family:inherit;font-weight:600;}
      .ach-filter.active{background:#E4AC38;color:#1a1a1a;border-color:#E4AC38;}
      .ach-card{display:flex;align-items:center;gap:12px;padding:12px;background:#0f0f1e;border-radius:12px;border:1px solid rgba(255,255,255,0.04);}
      .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:#475569;font-size:13px;">لا توجد إنجازات في هذه الفئة</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,#22c55e)' : '#1a1a2e'};
          border:2px solid ${a.completed ? '#22c55e' : 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 ? '#34D399' : '#f8fafc'};margin-bottom:2px;">${a.name}</div>
          <div style="font-size:11px;color:#64748b;margin-bottom:4px;">${a.description}</div>
          ${!a.completed ? `
            <div style="display:flex;align-items:center;gap:6px;">
              <div style="flex:1;background:#1a1a2e;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:#64748b;white-space:nowrap;">${a.progress}/${a.target}</span>
            </div>
          ` : `
            <div style="font-size:10px;color:#22c55e;">✓ مكتمل</div>
          `}
        </div>
        <div style="text-align:center;min-width:40px;">
          <div style="font-size:11px;font-weight:700;color:#E4AC38;">${a.coins_reward}</div>
          <div style="font-size:9px;color:#64748b;">عملة</div>
        </div>
      </div>
    `;
  }).join('');
}

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