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 { t } from '../../../core/i18n.js';

let unsub = null;
let timer = null;

export function mountQueue(el, 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);

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

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

    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' : 'matchmaking.php';
  unsub = setInterval(async () => {
    try {
      const data = await net.post(endpoint, { action: 'status', game_key: params.game });
      if (data.match_id) {
        onMatchFound(data, params);
      }
    } catch (e) {}
  }, 3000);
}

function onMatchFound(data, params) {
  cleanup();
  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,
    players: data.players
  });
}

async function leaveQueue(params) {
  cleanup();
  try {
    await net.post('matchmaking.php', { action: 'dequeue', game_key: params.game });
  } catch (e) {}
}

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