import * as net from './net.js';
import * as bus from './bus.js';
import * as store from './store.js';
import * as realtime from './realtime.js';
import { emoji } from './theme.js';
import { t } from './i18n.js';

let pendingMatches = [];
let activeTournaments = [];
let subscriptions = [];

export function init() {
  const userId = store.get('auth.userId');
  if (!userId) return;
  fetchPending();
  bus.on('auth:expired', cleanup);
  bus.on('tournament:paired', showPairingToast);
}

function showPairingToast(data) {
  const existing = document.getElementById('tournament-toast');
  if (existing) existing.remove();

  const toast = document.createElement('div');
  toast.id = 'tournament-toast';
  toast.style.cssText = 'position:fixed;top:0;left:0;right:0;z-index:9999;padding:12px 16px;background:linear-gradient(135deg,var(--bg-card),var(--bg-panel));border-bottom:2px solid var(--gold);display:flex;align-items:center;gap:12px;animation:slideDown .3s ease;';
  toast.innerHTML = `
    <span style="font-size:20px;">${emoji('trophy', '🏆', 20)}</span>
    <div style="flex:1;">
      <div style="font-size:13px;font-weight:700;color:var(--text-primary);">${t('tournament.round_ready', { n: data.roundNumber })}</div>
      <div style="font-size:11px;color:var(--text-secondary);">${t('tournament.tap_to_play')}</div>
    </div>
    <button id="toast-play-btn" style="padding:6px 14px;background:var(--gold);border:none;border-radius:8px;color:#000;font-weight:700;font-size:12px;cursor:pointer;">${t('tournament.play')}</button>
  `;
  document.body.appendChild(toast);

  toast.querySelector('#toast-play-btn').addEventListener('click', () => {
    toast.remove();
    import('./scene.js').then(scene => {
      scene.push('tournament-detail', { tournamentId: data.tournamentId });
    });
  });

  setTimeout(() => toast.remove(), 15000);
}

export async function fetchPending() {
  try {
    const data = await net.get('tournament-match.php', { action: 'my-pending' });
    pendingMatches = data.pending || [];

    // Subscribe to realtime for each active tournament
    const tournamentIds = [...new Set(pendingMatches.map(p => p.tournament_id))];
    subscribeToTournaments(tournamentIds);

    if (pendingMatches.length > 0) {
      bus.emit('tournament:pending-updated', pendingMatches);
    }
  } catch (e) {
    console.warn('[tournament-session] fetchPending error:', e);
  }
}

export function getPendingMatches() {
  return pendingMatches;
}

export function getActiveTournaments() {
  return activeTournaments;
}

function subscribeToTournaments(tournamentIds) {
  // Clean up old subscriptions
  subscriptions.forEach(unsub => unsub());
  subscriptions = [];
  activeTournaments = tournamentIds;

  tournamentIds.forEach(tid => {
    const unsub = realtime.subscribeTournamentRounds(tid, (change) => {
      if (change.type === 'UPDATE' || change.type === 'INSERT') {
        const round = change.new;
        if (round.status === 'in_progress') {
          handleNewRound(tid, round);
        }
      }
    });
    subscriptions.push(unsub);
  });
}

function handleNewRound(tournamentId, round) {
  const userId = store.get('auth.userId');
  if (!userId) return;

  const pairings = typeof round.pairings === 'string'
    ? JSON.parse(round.pairings || '[]')
    : (round.pairings || []);

  for (let i = 0; i < pairings.length; i++) {
    const p = pairings[i];
    const playerA = p.player_a || p.white_id;
    const playerB = p.player_b || p.black_id;

    if (userId === playerA || userId === playerB) {
      const opponentId = userId === playerA ? playerB : playerA;
      bus.emit('tournament:paired', {
        tournamentId,
        roundId: round.id,
        roundNumber: round.round_number,
        pairingIndex: i,
        opponentId,
        isBye: !opponentId || opponentId === 'BYE'
      });
      fetchPending();
      return;
    }
  }
}

export function cleanup() {
  subscriptions.forEach(unsub => unsub());
  subscriptions = [];
  pendingMatches = [];
  activeTournaments = [];
}
