import * as scene from '../../../core/scene.js';
import * as bus from '../../../core/bus.js';
import * as net from '../../../core/net.js';
import * as audio from '../../../core/audio.js';
import * as modal from '../../../core/modal.js';
import { t } from '../../../core/i18n.js';

const QUEUE_TIMEOUT_S = 60;
let unsub = null;
let timer = null;
let timeoutId = null;
let activeParams = null;

export function unmountQueue() {
  if (activeParams) {
    leaveQueue(activeParams);
    activeParams = null;
  }
}

export function mountQueue(el, params) {
  activeParams = params;
  let seconds = 0;

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:var(--s-6);">
      <div class="queue-radar" style="width:120px;height:120px;border-radius:50%;border:3px solid var(--gold);position:relative;display:flex;align-items:center;justify-content:center;">
        <div style="width:8px;height:8px;background:var(--gold);border-radius:50%;animation:pulse 1s ease-in-out infinite;"></div>
        <div style="position:absolute;inset:0;border-radius:50%;border:2px solid var(--gold);opacity:0;animation:radarPing 2s ease-out infinite;"></div>
      </div>
      <div>
        <div style="font-size:16px;font-weight:600;text-align:center;">${t('play.searching')}</div>
        <div id="queue-timer" style="font-size:24px;font-weight:700;color:var(--gold);text-align:center;margin-top:var(--s-2);font-family:var(--font-lat);">0:00</div>
      </div>
      <button class="btn btn-secondary" id="cancel-btn">${t('play.cancel')}</button>
    </div>
    <style>
      @keyframes radarPing { 0% { transform:scale(1);opacity:0.6; } 100% { transform:scale(2);opacity:0; } }
    </style>
  `;

  const timerEl = el.querySelector('#queue-timer');
  timer = setInterval(() => {
    seconds++;
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    timerEl.textContent = `${m}:${s.toString().padStart(2, '0')}`;
  }, 1000);

  joinQueue(params);

  timeoutId = setTimeout(() => onQueueTimeout(el, params), QUEUE_TIMEOUT_S * 1000);

  el.querySelector('#cancel-btn').addEventListener('click', () => {
    audio.play('click');
    leaveQueue(params);
    activeParams = null;
    scene.pop();
  });
}

async function onQueueTimeout(el, params) {
  cleanup();
  const retry = await modal.confirm(
    t('play.retry_or_cancel') || 'No opponent found. Keep searching?',
    {
      title: t('play.no_match_found') || 'No match',
      confirmText: t('play.retry') || 'Retry',
      cancelText: t('play.cancel') || 'Cancel'
    }
  );
  if (retry) {
    let seconds = 0;
    const timerEl = el.querySelector('#queue-timer');
    if (timerEl) timerEl.textContent = '0:00';
    timer = setInterval(() => {
      seconds++;
      const m = Math.floor(seconds / 60);
      const s = seconds % 60;
      if (timerEl) timerEl.textContent = `${m}:${s.toString().padStart(2, '0')}`;
    }, 1000);
    joinQueue(params);
    timeoutId = setTimeout(() => onQueueTimeout(el, params), QUEUE_TIMEOUT_S * 1000);
  } else {
    leaveQueue(params);
    activeParams = null;
    scene.pop();
  }
}

async function joinQueue(params) {
  const endpoint = params.game === 'ludo' ? 'ludo-match.php' : params.game === 'domino' ? 'domino-match.php' : params.game === 'backgammon' ? 'backgammon-match.php' : 'matchmaking.php';
  try {
    const data = await net.post(endpoint, {
      action: 'queue',
      game_key: params.game,
      time_control: params.timeControl || 'standard',
      variant: params.variant,
      match_length: params.matchLength,
      player_count: params.playerCount || 4
    });

    if (data.match_id) {
      onMatchFound(data, params);
    } else {
      pollForMatch(params);
    }
  } catch (e) {
    scene.pop();
  }
}

function pollForMatch(params) {
  const endpoint = params.game === 'ludo' ? 'ludo-match.php' : params.game === 'domino' ? 'domino-match.php' : params.game === 'backgammon' ? 'backgammon-match.php' : 'matchmaking.php';
  let polling = false;
  unsub = setInterval(async () => {
    if (polling) return;
    polling = true;
    try {
      const data = await net.post(endpoint, { action: 'status', game_key: params.game });
      if (data.match_id) {
        onMatchFound(data, params);
      }
    } catch (e) {}
    polling = false;
  }, 3000);
}

function onMatchFound(data, params) {
  cleanup();
  activeParams = null;
  audio.play('notification');
  const gameScene = params.game === 'chess' ? 'chess-game' : params.game + '-game';
  scene.replace(gameScene, {
    ...params,
    matchId: data.match_id,
    mode: 'live',
    color: data.color,
    playerIndex: data.player_index,
    playerCount: data.player_count || params.playerCount || 4,
    players: data.players
  });
}

async function leaveQueue(params) {
  cleanup();
  const endpoint = params.game === 'ludo' ? 'ludo-match.php' : params.game === 'domino' ? 'domino-match.php' : params.game === 'backgammon' ? 'backgammon-match.php' : 'matchmaking.php';
  try {
    await net.post(endpoint, { action: 'dequeue', game_key: params.game });
  } catch (e) {}
}

function cleanup() {
  if (timer) { clearInterval(timer); timer = null; }
  if (unsub) { clearInterval(unsub); unsub = null; }
  if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; }
}
