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

export async function mountHistory(el) {
  el.innerHTML = `
    <div style="padding:16px;display:flex;flex-direction:column;gap:12px;">
      <div style="display:flex;align-items:center;gap:12px;">
        <button class="btn btn-secondary" id="back-btn" style="width:36px;height:36px;padding:0;">←</button>
        <h2 style="font-size:18px;font-weight:700;">${t('profile.history')}</h2>
      </div>
      <div id="history-list">
        <div class="skeleton" style="height:60px;margin-bottom:8px;"></div>
        <div class="skeleton" style="height:60px;margin-bottom:8px;"></div>
        <div class="skeleton" style="height:60px;"></div>
      </div>
    </div>
  `;

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

  try {
    const data = await net.get('match-history.php', { limit: 20 });
    const matches = data.matches || [];
    renderHistory(el, matches);
  } catch (e) {
    el.querySelector('#history-list').innerHTML = `<p style="color:#ef4444;text-align:center;">${t('common.error')}</p>`;
  }
}

function renderHistory(el, matches) {
  const list = el.querySelector('#history-list');
  const userId = store.get('auth.userId');

  if (matches.length === 0) {
    list.innerHTML = `
      <div style="text-align:center;padding:40px;">
        <div style="font-size:40px;margin-bottom:8px;opacity:0.4;">${emoji('clipboard', '📋', 40)}</div>
        <div style="font-size:14px;color:#64748b;">لا توجد مباريات بعد — العب لتظهر هنا</div>
      </div>`;
    return;
  }

  list.innerHTML = matches.map(m => {
    const isWhite = m.white_player_id === userId;
    const myResult = getMyResult(m.result, isWhite);
    const resultConfig = {
      win: { label: 'فوز', color: '#34D399', icon: emoji('trophy', '🏆', 20) },
      loss: { label: 'خسارة', color: '#F87171', icon: emoji('skull', '💀', 20) },
      draw: { label: 'تعادل', color: '#E4AC38', icon: emoji('handshake', '🤝', 20) },
      unknown: { label: '—', color: '#64748b', icon: '•' }
    };
    const cfg = resultConfig[myResult] || resultConfig.unknown;
    const ratingChange = isWhite ? m.rating_change_white : m.rating_change_black;
    const ratingStr = ratingChange ? (ratingChange > 0 ? `+${ratingChange}` : `${ratingChange}`) : '';
    const timeAgo = formatTimeAgo(m.created_at);
    const opponent = isWhite ? (m.black_name || m.bot_id || 'خصم') : (m.white_name || m.bot_id || 'خصم');
    const tc = formatTimeControl(m.time_control);

    return `
      <div style="display:flex;align-items:center;gap:12px;padding:12px;background:#1a1a2e;border-radius:12px;border-right:4px solid ${cfg.color};">
        <div style="font-size:20px;">${cfg.icon}</div>
        <div style="flex:1;">
          <div style="display:flex;justify-content:space-between;align-items:center;">
            <span style="font-size:13px;font-weight:600;color:#f8fafc;">${opponent}</span>
            <span style="font-size:12px;font-weight:700;color:${cfg.color};font-family:Inter,monospace;">${ratingStr}</span>
          </div>
          <div style="display:flex;gap:8px;margin-top:3px;">
            <span style="font-size:10px;color:#64748b;">${cfg.label}</span>
            <span style="font-size:10px;color:#475569;">${tc}</span>
            <span style="font-size:10px;color:#475569;">${timeAgo}</span>
          </div>
        </div>
      </div>
    `;
  }).join('');
}

function getMyResult(result, isWhite) {
  if (!result) return 'unknown';
  if (result === 'draw' || result === 'mutual_draw' || result === 'stalemate' ||
      result === 'threefold_repetition' || result === 'fifty_moves' || result === 'insufficient_material') return 'draw';
  if ((result === 'white_wins' && isWhite) || (result === 'black_wins' && !isWhite) ||
      (result === 'black_resign' && isWhite) || (result === 'white_resign' && !isWhite) ||
      (result === 'black_timeout' && isWhite) || (result === 'white_timeout' && !isWhite) ||
      (result === 'black_abandon' && isWhite) || (result === 'white_abandon' && !isWhite)) return 'win';
  if (result === 'aborted') return 'unknown';
  return 'loss';
}

function formatTimeControl(tc) {
  if (!tc) return '';
  const labels = { bullet_1_0: '1+0', bullet_2_1: '2+1', blitz_3_0: '3+0', blitz_5_0: '5+0', blitz_5_3: '5+3', rapid_10_0: '10+0', rapid_15_10: '15+10', rapid_30_0: '30+0' };
  return labels[tc] || tc.replace(/_/g, ' ');
}

function formatTimeAgo(date) {
  if (!date) return '';
  const diff = Date.now() - new Date(date).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'الآن';
  if (mins < 60) return `${mins}د`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}س`;
  const days = Math.floor(hours / 24);
  return `${days}ي`;
}
