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

let pollInterval = null;
let countdownInterval = null;

export function mountTournamentArena(el, params) {
  const { tournamentId, tournamentName } = params;

  if (pollInterval) clearInterval(pollInterval);
  if (countdownInterval) clearInterval(countdownInterval);

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-deep);">
      <div style="display:flex;align-items:center;gap:12px;padding:10px 14px;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:15px;font-weight:700;color:var(--text-primary);">${emoji('lightning', '⚡', 15)} ${t('tournament.arena')}</span>
      </div>
      <div id="arena-content" style="flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;align-items:center;gap:16px;">
      </div>
    </div>
  `;

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

  startArena(el, tournamentId, tournamentName);
}

async function startArena(el, tournamentId, tournamentName) {
  const content = el.querySelector('#arena-content');
  content.innerHTML = `
    <div style="text-align:center;margin-top:24px;">
      <div class="radar-pulse" style="width:80px;height:80px;margin:0 auto 16px;border-radius:50%;background:radial-gradient(circle,var(--gold) 0%,transparent 70%);animation:pulse 1.5s infinite;"></div>
      <div style="font-size:16px;font-weight:700;color:var(--text-primary);">${t('play.searching')}</div>
      <div style="font-size:12px;color:var(--text-muted);margin-top:4px;">${tournamentName || t('tournament.arena')}</div>
    </div>
    <div id="arena-standings" style="width:100%;max-width:320px;margin-top:16px;"></div>
    <button class="btn btn-secondary" id="leave-arena" style="margin-top:auto;margin-bottom:16px;color:var(--error);border-color:var(--error);">${t('tournament.leave_arena')}</button>
    <style>
      @keyframes pulse { 0%,100% { transform:scale(1);opacity:0.6; } 50% { transform:scale(1.3);opacity:0.2; } }
    </style>
  `;

  el.querySelector('#leave-arena')?.addEventListener('click', () => {
    cleanup();
    audio.play('click');
    scene.pop();
  });

  // Join arena
  try {
    const joinRes = await net.post('swiss.php', { action: 'arena-join', tournament_id: tournamentId });
    if (joinRes.status === 'paired') {
      launchArenaMatch(joinRes, tournamentId, tournamentName);
      return;
    }
  } catch (e) {
    console.warn('[arena] join error:', e);
  }

  // Load standings
  loadArenaStandings(el, tournamentId);

  // Poll for pairing
  pollInterval = setInterval(async () => {
    try {
      const status = await net.get('swiss.php', { action: 'arena-status', tournament_id: tournamentId });
      if (status.status === 'in_game' && status.match_id) {
        cleanup();
        scene.push('chess-game', {
          mode: 'live',
          matchId: status.match_id,
          color: status.color,
          timeControl: status.time_control || 'blitz_3_0',
          opponentId: status.opponent_id,
          tournamentId,
          tournamentRound: status.round_number,
          recovered: true
        });
      } else if (status.status === 'paired') {
        // Re-join to get match details
        const joinRes = await net.post('swiss.php', { action: 'arena-join', tournament_id: tournamentId });
        if (joinRes.status === 'paired') {
          launchArenaMatch(joinRes, tournamentId, tournamentName);
        }
      }
    } catch (e) {}
  }, 3000);

  // Listen for match end to auto-return to arena
  bus.on('tournament:match-ended', (data) => {
    if (data.tournamentId === tournamentId) {
      setTimeout(() => {
        scene.replace('tournament-arena', { tournamentId, tournamentName });
      }, 3000);
    }
  });
}

/**
 * Open the arena game for this player.
 *
 * arena-join only reports *that* we are paired; the match itself is minted by
 * tournament-match.php so there is exactly one place that creates a tournament
 * match and both players end up on the same board with agreed colours.
 */
async function launchArenaMatch(data, tournamentId, tournamentName) {
  cleanup();
  try {
    const match = await net.post('tournament-match.php', {
      action: 'create-or-join',
      tournament_id: tournamentId
    });
    if (match.error || match.waiting) return;
    if (match.bye) { audio.play('reward'); return; }

    audio.play('match_found');
    scene.push('chess-game', {
      mode: 'live',
      matchId: match.match_id,
      color: match.color,
      timeControl: match.time_control || data.time_control || 'blitz_3_0',
      opponentId: match.opponent_id,
      tournamentId,
      tournamentRound: match.round_number,
      recovered: !!match.recovered
    });
  } catch (e) {
    console.warn('[arena] could not open match:', e);
  }
}

async function loadArenaStandings(el, tournamentId) {
  const container = el.querySelector('#arena-standings');
  if (!container) return;

  try {
    const data = await net.get('swiss.php', { action: 'arena-standings', tournament_id: tournamentId });
    const standings = data.standings || [];
    const userId = store.get('auth.userId');

    if (standings.length === 0) {
      container.innerHTML = `<div style="text-align:center;color:var(--text-muted);font-size:12px;">${t('tournament.no_results')}</div>`;
      return;
    }

    container.innerHTML = `
      <div style="font-size:13px;font-weight:700;color:var(--text-secondary);margin-bottom:8px;text-align:center;">${t('tournament.leaderboard')}</div>
      ${standings.slice(0, 10).map((p, i) => {
        const isMe = p.player_id === userId;
        const medals = ['🥇', '🥈', '🥉'];
        return `
          <div style="display:flex;align-items:center;padding:6px 8px;background:${isMe ? '#1a2e1a' : 'var(--bg-card)'};border-radius:6px;margin-bottom:4px;border:${isMe ? '1px solid var(--gold)' : '1px solid transparent'};">
            <span style="width:24px;font-size:${i < 3 ? '14px' : '11px'};text-align:center;">${i < 3 ? medals[i] : (i + 1)}</span>
            <span style="flex:1;font-size:12px;color:var(--text-primary);font-weight:${isMe ? '700' : '400'};">${p.name}${isMe ? ` (${t('common.you')})` : ''}</span>
            <span style="font-size:12px;font-weight:700;color:var(--gold);">${p.points}</span>
            <span style="font-size:10px;color:var(--text-muted);margin-right:4px;width:50px;text-align:left;">${p.wins}W ${p.draws}D ${p.losses}L</span>
          </div>
        `;
      }).join('')}
    `;
  } catch (e) {
    container.innerHTML = '';
  }
}

function cleanup() {
  if (pollInterval) { clearInterval(pollInterval); pollInterval = null; }
  if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
}

export const unmountTournamentArena = cleanup;
