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, params = {}) {
  const gameKey = params.game || 'chess';
  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, game_key: gameKey });
    const matches = data.matches || [];
    renderHistory(el, matches);
  } catch (e) {
    el.querySelector('#history-list').innerHTML = `<p style="color:var(--error);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:var(--text-muted);">${t('history.no_matches')}</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: t('history.win'), color: 'var(--success)', icon: emoji('trophy', '🏆', 20) },
      loss: { label: t('history.loss'), color: 'var(--red-light)', icon: emoji('skull', '💀', 20) },
      draw: { label: t('history.draw'), color: 'var(--gold)', icon: emoji('handshake', '🤝', 20) },
      unknown: { label: '—', color: 'var(--text-muted)', 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 || t('common.opponent')) : (m.white_name || m.bot_id || t('common.opponent'));
    const tc = formatTimeControl(m.time_control);

    return `
      <div style="display:flex;align-items:center;gap:12px;padding:12px;background:var(--bg-card);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:var(--text-primary);">${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:var(--fs-xs);color:var(--text-muted);">${cfg.label}</span>
            <span style="font-size:var(--fs-xs);color:var(--text-dim);">${tc}</span>
            <span style="font-size:var(--fs-xs);color:var(--text-dim);">${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 t('common.now');
  if (mins < 60) return t('common.minutes_ago', { n: mins });
  const hours = Math.floor(mins / 60);
  if (hours < 24) return t('common.hours_ago', { n: hours });
  const days = Math.floor(hours / 24);
  return t('common.days_ago', { n: days });
}
