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

let countdownInterval = null;
let unsub = null;

export function mountTournamentLobby(el, params) {
  const { tournamentId, tournamentName, startsAt, timeControl, format, prizePool } = params;

  if (countdownInterval) clearInterval(countdownInterval);
  if (unsub) unsub();

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:#0a0a1a;align-items:center;justify-content:center;padding:24px;gap:20px;">
      <div style="text-align:center;">
        <div style="font-size:20px;font-weight:800;color:#f8fafc;">${tournamentName || 'بطولة'}</div>
        <div id="countdown" style="font-size:42px;font-weight:800;color:#E4AC38;margin-top:12px;font-family:Inter,monospace;">--:--</div>
        <div style="font-size:13px;color:#64748b;margin-top:4px;">تبدأ خلال</div>
      </div>

      <div id="players-grid" style="display:flex;flex-wrap:wrap;gap:8px;justify-content:center;max-width:280px;"></div>

      <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;width:100%;max-width:300px;">
        <div style="background:#1a1a2e;border-radius:8px;padding:10px;text-align:center;">
          <div style="font-size:11px;color:#64748b;">النظام</div>
          <div style="font-size:13px;font-weight:700;color:#f8fafc;">${format || 'swiss'}</div>
        </div>
        <div style="background:#1a1a2e;border-radius:8px;padding:10px;text-align:center;">
          <div style="font-size:11px;color:#64748b;">الوقت</div>
          <div style="font-size:13px;font-weight:700;color:#f8fafc;">${timeControl || '?'}</div>
        </div>
        <div style="background:#1a1a2e;border-radius:8px;padding:10px;text-align:center;">
          <div style="font-size:11px;color:#64748b;">الجوائز</div>
          <div style="font-size:13px;font-weight:700;color:#E4AC38;">${prizePool || '0'} ${emoji('coin', '🪙', 13)}</div>
        </div>
      </div>

      <button class="btn btn-secondary" id="leave-lobby" style="margin-top:auto;color:#ef4444;border-color:#ef4444;font-size:13px;">مغادرة البطولة</button>
    </div>
  `;

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

  // Countdown
  const targetTime = startsAt ? new Date(startsAt).getTime() : null;
  if (targetTime) {
    updateCountdown(el, targetTime);
    countdownInterval = setInterval(() => updateCountdown(el, targetTime), 1000);
  }

  // Load registered players
  loadPlayers(el, tournamentId);

  // Subscribe to tournament status changes
  unsub = realtime.subscribe('el3ab_tournaments', `id=eq.${tournamentId}`, (change) => {
    if (change.type === 'UPDATE' && change.new.status === 'in_progress') {
      cleanup();
      audio.play('match_found');
      scene.replace('tournament-detail', { tournamentId });
    }
  });
}

function updateCountdown(el, targetTime) {
  const now = Date.now();
  const diff = targetTime - now;

  const countdownEl = el.querySelector('#countdown');
  if (!countdownEl) return;

  if (diff <= 0) {
    countdownEl.textContent = '00:00';
    countdownEl.style.color = '#34D399';
    return;
  }

  const mins = Math.floor(diff / 60000);
  const secs = Math.floor((diff % 60000) / 1000);
  countdownEl.textContent = `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
}

async function loadPlayers(el, tournamentId) {
  const grid = el.querySelector('#players-grid');
  if (!grid) return;

  try {
    const data = await net.get('tournaments.php', { action: 'detail', tournament_id: tournamentId });
    const registrations = data.registrations || [];

    if (registrations.length === 0) {
      grid.innerHTML = '<div style="font-size:12px;color:#64748b;">في انتظار اللاعبين...</div>';
      return;
    }

    grid.innerHTML = registrations.slice(0, 20).map(r => {
      const avatar = r.avatar_url
        ? `<img src="${r.avatar_url}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">`
        : `<span style="font-size:14px;">${emoji('person', '👤', 14)}</span>`;
      return `<div style="width:36px;height:36px;border-radius:50%;background:#1a1a2e;border:2px solid #34D399;display:flex;align-items:center;justify-content:center;overflow:hidden;" title="${r.display_name || ''}">${avatar}</div>`;
    }).join('') + (registrations.length > 20 ? `<div style="font-size:11px;color:#64748b;align-self:center;">+${registrations.length - 20}</div>` : '');
  } catch (e) {
    grid.innerHTML = '';
  }
}

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