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 { emoji } from '../../../core/theme.js';
import { t } from '../../../core/i18n.js';

let refreshInterval = null;

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

  if (refreshInterval) clearInterval(refreshInterval);

  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:var(--tap-min);padding:4px 12px;font-size:12px;">←</button>
        <span style="font-size:15px;font-weight:700;color:var(--text-primary);flex:1;">${emoji('live', '🔴', 12)} LIVE — ${tournamentName || t('tournament.title')}</span>
      </div>
      <div id="live-content" style="flex:1;overflow-y:auto;padding:14px;"></div>
    </div>
  `;

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

  loadLiveData(el, tournamentId);
  refreshInterval = setInterval(() => loadLiveData(el, tournamentId), 5000);
}

async function loadLiveData(el, tournamentId) {
  const content = el.querySelector('#live-content');
  if (!content) return;

  try {
    const [roundsData, standingsData] = await Promise.all([
      net.get('swiss.php', { action: 'rounds', tournament_id: tournamentId }),
      net.get('swiss.php', { action: 'standings', tournament_id: tournamentId })
    ]);

    const rounds = roundsData.rounds || [];
    const standings = standingsData.standings || [];
    const currentRound = rounds.find(r => r.status === 'in_progress') || rounds[rounds.length - 1];

    let html = '';

    // Current round info
    if (currentRound) {
      html += `<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
        <span style="font-size:14px;font-weight:700;color:var(--text-primary);">${t('tournament.round_n', { n: currentRound.round_number, total: rounds.length })}</span>
        <span style="font-size:11px;padding:3px 8px;border-radius:99px;background:${currentRound.status === 'in_progress' ? 'var(--gold)' : 'var(--text-muted)'};color:#000;font-weight:600;">${currentRound.status === 'in_progress' ? t('tournament.active') : t('tournament.completed')}</span>
      </div>`;

      // Show pairings for current round
      if (currentRound.pairings) {
        const pairings = typeof currentRound.pairings === 'string'
          ? JSON.parse(currentRound.pairings)
          : currentRound.pairings;

        if (pairings.length > 0) {
          html += `<div style="margin-bottom:16px;">`;
          html += `<div style="font-size:12px;font-weight:700;color:var(--text-secondary);margin-bottom:8px;">${t('tournament.live_matches')}</div>`;
          pairings.forEach(p => {
            const hasResult = !!p.result;
            html += `
              <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 10px;background:var(--bg-card);border-radius:8px;margin-bottom:4px;">
                <span style="flex:1;font-size:12px;color:var(--text-primary);text-align:right;">${p.white_name || p.player_a || '?'}</span>
                <span style="padding:2px 8px;font-size:11px;font-weight:700;color:${hasResult ? 'var(--success)' : 'var(--gold)'};">${p.result || 'vs'}</span>
                <span style="flex:1;font-size:12px;color:var(--text-primary);text-align:left;">${p.black_name || p.player_b || '?'}</span>
                ${!hasResult ? `<button class="spectate-btn" data-white="${p.player_a || p.white_id || ''}" data-black="${p.player_b || p.black_id || ''}" style="margin-right:4px;padding:2px 8px;background:var(--blue);border:none;border-radius:4px;color:#fff;font-size:var(--fs-xs);font-weight:600;cursor:pointer;">${t('spectate.watch')}</button>` : ''}
              </div>
            `;
          });
          html += `</div>`;
        }
      }
    }

    // Standings
    if (standings.length > 0) {
      html += `<div style="font-size:12px;font-weight:700;color:var(--text-secondary);margin-bottom:8px;">${t('tournament.tab_standings')}</div>`;
      html += standings.slice(0, 15).map((p, i) => {
        const medals = ['🥇', '🥈', '🥉'];
        return `
          <div style="display:flex;align-items:center;padding:6px 0;border-bottom:1px solid var(--border);">
            <span style="width:24px;font-size:${i < 3 ? '13px' : '11px'};text-align:center;">${i < 3 ? medals[i] : (i + 1)}</span>
            <span style="flex:1;font-size:12px;color:var(--text-primary);">${p.name || p.player_name || 'Player'}</span>
            <span style="font-size:12px;font-weight:700;color:var(--gold);">${p.score ?? p.points ?? 0}</span>
          </div>
        `;
      }).join('');
    }

    if (!html) {
      html = `<div style="text-align:center;color:var(--text-muted);padding:32px;">${t('common.empty')}</div>`;
    }

    content.innerHTML = html;

    // Spectate buttons — find active match for the player pair
    content.querySelectorAll('.spectate-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        audio.play('click');
        const whiteId = btn.dataset.white;
        const blackId = btn.dataset.black;
        btn.textContent = '...';
        btn.disabled = true;
        try {
          const data = await net.post('game.php', { action: 'find-active-match', player_id: whiteId });
          if (data.match_id) {
            scene.push('chess-spectate', { matchId: data.match_id });
          } else {
            const data2 = await net.post('game.php', { action: 'find-active-match', player_id: blackId });
            if (data2.match_id) {
              scene.push('chess-spectate', { matchId: data2.match_id });
            } else {
              btn.textContent = t('tournament.no_match');
              setTimeout(() => { btn.textContent = t('spectate.watch'); btn.disabled = false; }, 2000);
            }
          }
        } catch (e) {
          btn.textContent = t('common.error');
          setTimeout(() => { btn.textContent = t('spectate.watch'); btn.disabled = false; }, 2000);
        }
      });
    });

  } catch (e) {
    content.innerHTML = '<div style="text-align:center;color:var(--error);">فشل التحميل</div>';
  }
}

export function unmountTournamentLive() {
  if (refreshInterval) { clearInterval(refreshInterval); refreshInterval = null; }
}
