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

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:#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;flex:1;">${emoji('live', '🔴', 12)} LIVE — ${tournamentName || 'بطولة'}</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:#f8fafc;">الجولة ${currentRound.round_number}/${rounds.length}</span>
        <span style="font-size:11px;padding:3px 8px;border-radius:99px;background:${currentRound.status === 'in_progress' ? '#E4AC38' : '#64748b'};color:#000;font-weight:600;">${currentRound.status === 'in_progress' ? 'جارية' : 'منتهية'}</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:#94a3b8;margin-bottom:8px;">مباريات جارية</div>`;
          pairings.forEach(p => {
            const hasResult = !!p.result;
            html += `
              <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 10px;background:#1a1a2e;border-radius:8px;margin-bottom:4px;">
                <span style="flex:1;font-size:12px;color:#f8fafc;text-align:right;">${p.white_name || p.player_a || '?'}</span>
                <span style="padding:2px 8px;font-size:11px;font-weight:700;color:${hasResult ? '#34D399' : '#E4AC38'};">${p.result || 'vs'}</span>
                <span style="flex:1;font-size:12px;color:#f8fafc;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:#3B82F6;border:none;border-radius:4px;color:#fff;font-size:10px;font-weight:600;cursor:pointer;">شاهد</button>` : ''}
              </div>
            `;
          });
          html += `</div>`;
        }
      }
    }

    // Standings
    if (standings.length > 0) {
      html += `<div style="font-size:12px;font-weight:700;color:#94a3b8;margin-bottom:8px;">الترتيب</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 rgba(255,255,255,0.04);">
            <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:#f8fafc;">${p.name || p.player_name || 'Player'}</span>
            <span style="font-size:12px;font-weight:700;color:#E4AC38;">${p.score ?? p.points ?? 0}</span>
          </div>
        `;
      }).join('');
    }

    if (!html) {
      html = '<div style="text-align:center;color:#64748b;padding:32px;">لا توجد بيانات بعد</div>';
    }

    content.innerHTML = html;

    // Spectate buttons — find match for spectating
    content.querySelectorAll('.spectate-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        audio.play('click');
        const whiteId = btn.dataset.white;
        const blackId = btn.dataset.black;
        try {
          const matches = await net.get('swiss.php', { action: 'my-games', tournament_id: tournamentId });
          // For spectating, we'd need to find the match between these two players
          // For now, push a message
          btn.textContent = '...';
          btn.disabled = true;
        } catch (e) {}
      });
    });

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