'use strict';
/* admin → gam (gamification) section: stats + top + recent XP + purchases + award XP */
(function () {
  'use strict';
  let inited = false;
  let _gamSearchTimer = null;
  let _gamAwarding = false;

  const XP_REASONS = {
    'daily_activity': ['sun',          '#F59E0B', 'Ежедневная активность'],
    'correct_answers':['check-circle', '#10B981', 'Правильные ответы'],
    'test_complete':  ['file-text',    '#06B6D4', 'Тест завершён'],
    'test_90+':       ['zap',          '#9B5DE5', 'Тест на 90%+'],
    'test_perfect':   ['trophy',       '#F59E0B', 'Идеальный тест (100%)'],
    'lab_experiment': ['atom',         '#06D6A0', 'Лабораторный эксперимент'],
    'daily_goal':     ['target',       '#EF476F', 'Ежедневная цель выполнена'],
    'Admin award':    ['crown',        '#9B5DE5', 'Начисление администратором'],
  };

  function fmtXPReason(reason) {
    if (!reason) return '—';
    const entry = XP_REASONS[reason];
    if (entry) {
      const [icon, color, label] = entry;
      return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:${color};display:inline-flex">${lsIcon(icon,14)}</span>${label}</span>`;
    }
    if (reason.startsWith('achievement:')) {
      return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:#F59E0B;display:inline-flex">${lsIcon('award',14)}</span>Достижение: ${esc(reason.slice(12))}</span>`;
    }
    if (reason.startsWith('Испытание:')) {
      return `<span style="display:inline-flex;align-items:center;gap:5px"><span style="color:#EF476F;display:inline-flex">${lsIcon('swords',14)}</span>${esc(reason)}</span>`;
    }
    return esc(reason);
  }

  async function load() {
    const { fmtDate } = AdminCtx;
    try {
      const stats = await LS.adminGamStats();
      document.getElementById('gam-stats-grid').innerHTML = `
        <div class="stat-card" style="--stat-top:var(--violet)">
          <div class="stat-card-icon" style="background:rgba(155,93,229,0.1)"><i data-lucide="zap" class="stat-icon"></i></div>
          <div class="stat-val violet">${stats.totalXP}</div>
          <div class="stat-label">Суммарный XP</div>
        </div>
        <div class="stat-card" style="--stat-top:var(--cyan)">
          <div class="stat-card-icon" style="background:rgba(6,214,224,0.1)"><i data-lucide="coins" class="stat-icon"></i></div>
          <div class="stat-val cyan">${stats.totalCoins}</div>
          <div class="stat-label">Суммарные монеты</div>
        </div>
        <div class="stat-card" style="--stat-top:var(--green)">
          <div class="stat-card-icon" style="background:rgba(6,214,100,0.1)"><i data-lucide="bar-chart-3" class="stat-icon"></i></div>
          <div class="stat-val green">${(stats.avgLevel ?? 0).toFixed(1)}</div>
          <div class="stat-label">Средний уровень</div>
        </div>
        <div class="stat-card" style="--stat-top:var(--amber, #FFB347)">
          <div class="stat-card-icon" style="background:rgba(255,179,71,0.1)"><i data-lucide="trophy" class="stat-icon"></i></div>
          <div class="stat-val" style="color:var(--amber, #FFB347)">${stats.achievementCount}</div>
          <div class="stat-label">Достижений выдано</div>
        </div>
        <div class="stat-card" style="--stat-top:#FF9F1C">
          <div class="stat-card-icon" style="background:rgba(255,159,28,0.1)"><i data-lucide="shopping-bag" class="stat-icon"></i></div>
          <div class="stat-val" style="color:#FF9F1C">${stats.totalPurchases || 0}</div>
          <div class="stat-label">Покупок</div>
        </div>`;

      // Top-10
      const topBody = document.getElementById('gam-top-body');
      if (stats.topByXP?.length) {
        topBody.innerHTML = stats.topByXP.slice(0, 10).map((u, i) => `<tr>
          <td><strong>${i + 1}</strong></td>
          <td>${esc(u.name || u.email || 'ID:' + (u.id || u.user_id))}</td>
          <td><span style="color:var(--violet);font-weight:700">${u.xp}</span></td>
          <td>${u.level}</td>
          <td>${u.coins} <i data-lucide="coins" style="width:12px;height:12px;vertical-align:-2px;color:var(--amber, #FFB347)"></i></td>
        </tr>`).join('');
      } else {
        topBody.innerHTML = '<tr><td colspan="5" class="empty">Нет данных</td></tr>';
      }

      // Recent XP
      const logBody = document.getElementById('gam-log-body');
      if (stats.recentXP?.length) {
        logBody.innerHTML = stats.recentXP.slice(0, 20).map(e => `<tr>
          <td style="font-size:0.78rem;color:var(--text-3)">${fmtDate(e.created_at || e.date)}</td>
          <td>${esc(e.name || e.user_name || '—')}</td>
          <td><span style="color:var(--violet);font-weight:700">+${e.amount}</span></td>
          <td style="font-size:0.82rem;color:var(--text-2)">${fmtXPReason(e.reason)}</td>
        </tr>`).join('');
      } else {
        logBody.innerHTML = '<tr><td colspan="4" class="empty">Нет данных</td></tr>';
      }

      // Purchases
      const purchBody = document.getElementById('gam-purchases-body');
      if (stats.recentPurchases?.length) {
        purchBody.innerHTML = stats.recentPurchases.slice(0, 20).map(p => `<tr>
          <td style="font-size:0.78rem;color:var(--text-3)">${fmtDate(p.purchased_at)}</td>
          <td>${esc(p.user_name || '—')}</td>
          <td style="font-weight:600">${esc(p.item_name || '—')}</td>
          <td><span class="badge" style="font-size:0.7rem">${esc(p.type || '—')}</span></td>
          <td style="color:var(--amber,#FFB347);font-weight:700">${p.price} <i data-lucide="coins" style="width:12px;height:12px;vertical-align:-2px"></i></td>
        </tr>`).join('');
      } else {
        purchBody.innerHTML = '<tr><td colspan="5" class="empty">Нет покупок</td></tr>';
      }

      if (window.lucide) lucide.createIcons();
    } catch(e) {
      document.getElementById('gam-stats-grid').innerHTML = `<div class="error">Ошибка: ${esc(e.message)}</div>`;
    }
  }

  async function gamSearchUser(q, prefix) {
    clearTimeout(_gamSearchTimer);
    const box = document.getElementById(prefix + '-results');
    if (q.length < 2) { box.classList.remove('open'); return; }
    _gamSearchTimer = setTimeout(async () => {
      try {
        const r = await LS.adminGetUsers({ q, limit: 8 });
        const label = u => u.name || u.email;
        box.innerHTML = (r.users || []).map(u => `<div class="us-item" data-uid="${u.id}" data-name="${esc(label(u))}" data-prefix="${esc(prefix)}" onclick="gamPickUser(this)">
          <span>${esc(label(u))}</span><span class="us-role">${esc(u.role)}</span>
        </div>`).join('') || '<div class="us-item" style="color:var(--text-3)">Не найдено</div>';
        box.classList.add('open');
      } catch(e) { box.classList.remove('open'); }
    }, 300);
  }

  function gamPickUser(el) {
    const prefix = el.dataset.prefix;
    document.getElementById(prefix + '-uid').value = el.dataset.uid;
    document.getElementById(prefix + '-user').value = el.dataset.name || '';
    document.getElementById(prefix + '-results').classList.remove('open');
  }

  async function gamAdminAward() {
    if (_gamAwarding) return;
    const userId = parseInt(document.getElementById('gam-award-uid').value);
    const xp = parseInt(document.getElementById('gam-award-xp').value) || 0;
    const coins = parseInt(document.getElementById('gam-award-coins').value) || 0;
    const reason = document.getElementById('gam-award-reason').value.trim();
    if (!userId) { LS.toast('Выберите пользователя', 'error'); return; }
    if (!xp && !coins) { LS.toast('Введите XP или монеты', 'error'); return; }
    _gamAwarding = true;
    try {
      const r = await LS.adminGamAward({ userId, xp, coins, reason });
      LS.toast(`Начислено! XP: ${r.xp}, Уровень: ${r.level}, Монеты: ${r.coins}`, 'success');
      document.getElementById('gam-award-uid').value = '';
      document.getElementById('gam-award-user').value = '';
      document.getElementById('gam-award-reason').value = '';
      inited = false;
      await load();
      inited = true;
    } catch(e) { LS.toast('Ошибка: ' + e.message, 'error'); }
    finally { _gamAwarding = false; }
  }

  async function gamAdminReset() {
    const userId = parseInt(document.getElementById('gam-reset-uid').value);
    const userName = document.getElementById('gam-reset-user').value;
    if (!userId) { LS.toast('Выберите пользователя', 'error'); return; }
    if (!await LS.confirm(`ВСЕ XP, монеты и достижения «${userName}» будут удалены безвозвратно.`, { title: 'Сбросить прогресс?', confirmText: 'Сбросить', danger: true })) return;
    try {
      await LS.adminGamReset({ userId });
      LS.toast('Прогресс сброшен', 'success');
      document.getElementById('gam-reset-uid').value = '';
      document.getElementById('gam-reset-user').value = '';
      inited = false;
      await load();
      inited = true;
    } catch(e) { LS.toast('Ошибка: ' + e.message, 'error'); }
  }

  window.gamSearchUser = gamSearchUser;
  window.gamPickUser = gamPickUser;
  window.gamAdminAward = gamAdminAward;
  window.gamAdminReset = gamAdminReset;

  window.AdminSections = window.AdminSections || {};
  window.AdminSections.gam = {
    init: async () => { if (inited) return; inited = true; await load(); },
    reload: load,
  };
})();
