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';

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:#0a0a1a;">
      <div style="display:flex;align-items:center;gap:12px;padding:10px 14px;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:15px;font-weight:700;color:#f8fafc;">${emoji('lightning', '⚡', 15)} أرينا</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,#E4AC38 0%,transparent 70%);animation:pulse 1.5s infinite;"></div>
      <div style="font-size:16px;font-weight:700;color:#f8fafc;">جاري البحث عن خصم...</div>
      <div style="font-size:12px;color:#64748b;margin-top:4px;">${tournamentName || 'أرينا'}</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:#ef4444;border-color:#ef4444;">مغادرة الأرينا</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();
        const tc = status.time_control || 'blitz_3_0';
        scene.push('chess-game', {
          mode: 'live',
          matchId: status.match_id,
          color: status.color,
          timeControl: tc,
          opponentId: status.opponent_id,
          tournamentId,
          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);
    }
  });
}

function launchArenaMatch(data, tournamentId, tournamentName) {
  cleanup();
  audio.play('match_found');
  const tc = data.time_control || 'blitz_3_0';
  scene.push('chess-game', {
    mode: 'live',
    matchId: data.match_id,
    color: data.color,
    timeControl: tc,
    opponentId: data.opponent_id,
    tournamentId
  });
}

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:#64748b;font-size:12px;">لا توجد نتائج بعد</div>';
      return;
    }

    container.innerHTML = `
      <div style="font-size:13px;font-weight:700;color:#94a3b8;margin-bottom:8px;text-align:center;">المتصدرون</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' : '#1a1a2e'};border-radius:6px;margin-bottom:4px;border:${isMe ? '1px solid #E4AC38' : '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:#f8fafc;font-weight:${isMe ? '700' : '400'};">${p.name}${isMe ? ' (أنت)' : ''}</span>
            <span style="font-size:12px;font-weight:700;color:#E4AC38;">${p.points}</span>
            <span style="font-size:10px;color:#64748b;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; }
}
