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 { t } from '../../../core/i18n.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:var(--bg-deep);align-items:center;justify-content:center;padding:24px;gap:20px;">
      <div style="text-align:center;">
        <div style="font-size:20px;font-weight:800;color:var(--text-primary);">${tournamentName || t('tournament.title')}</div>
        <div id="countdown" style="font-size:42px;font-weight:800;color:var(--gold);margin-top:12px;font-family:Inter,monospace;">--:--</div>
        <div style="font-size:13px;color:var(--text-muted);margin-top:4px;">${t('tournament.starts_in', { n: '' })}</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:var(--bg-card);border-radius:8px;padding:10px;text-align:center;">
          <div style="font-size:11px;color:var(--text-muted);">${t('tournament.format_label')}</div>
          <div style="font-size:13px;font-weight:700;color:var(--text-primary);">${format || 'swiss'}</div>
        </div>
        <div style="background:var(--bg-card);border-radius:8px;padding:10px;text-align:center;">
          <div style="font-size:11px;color:var(--text-muted);">${t('tournament.time_label')}</div>
          <div style="font-size:13px;font-weight:700;color:var(--text-primary);">${timeControl || '?'}</div>
        </div>
        <div style="background:var(--bg-card);border-radius:8px;padding:10px;text-align:center;">
          <div style="font-size:11px;color:var(--text-muted);">${t('tournament.prizes_label')}</div>
          <div style="font-size:13px;font-weight:700;color:var(--gold);">${prizePool || '0'} ${emoji('coin', '🪙', 13)}</div>
        </div>
      </div>

      <button class="btn btn-secondary" id="leave-lobby" style="margin-top:auto;color:var(--error);border-color:var(--error);font-size:13px;">${t('tournament.leave')}</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 = 'var(--success)';
    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:var(--text-muted);">${t('tournament.waiting')}</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:var(--bg-card);border:2px solid var(--success);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:var(--text-muted);align-self:center;">+${registrations.length - 20}</div>` : '');
  } catch (e) {
    grid.innerHTML = '';
  }
}

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

export const unmountTournamentLobby = cleanup;
