import * as net from '../../../core/net.js';
import * as scene from '../../../core/scene.js';
import * as audio from '../../../core/audio.js';
import * as store from '../../../core/store.js';
import * as juice from '../../../core/juice.js';
import { t } from '../../../core/i18n.js';
import { emoji } from '../../../core/theme.js';

let pollTimer = null;
let matchId = null;
let currentGameKey = 'chess';
let lobbyState = 'waiting'; // waiting | ready | starting
let gameStarted = false;
let mounted = false;
let pollInFlight = false;
let startTimeout = null;

export function mountLobby(el, params = {}) {
  matchId = params.matchId;
  currentGameKey = params.gameKey || 'chess';
  const color = params.color;
  const gameKey = currentGameKey;
  const timeControl = params.timeControl || 'rapid_10_0';
  const friendProfile = params.friendProfile || {};
  const isHost = params.isHost ?? true;
  lobbyState = isHost ? 'waiting' : 'ready';
  gameStarted = false;
  mounted = true;
  pollInFlight = false;

  if (pollTimer) clearInterval(pollTimer);
  if (startTimeout) { clearTimeout(startTimeout); startTimeout = null; }

  const myName = store.get('player.display_name') || store.get('player.username') || t('common.you');
  const myAvatar = store.get('player.avatar_url');
  const friendName = friendProfile?.display_name || friendProfile?.username || t('common.opponent');
  const friendAvatar = friendProfile?.avatar_url;

  const tcLabel = formatTimeControl(timeControl);
  const gameLabel = gameKey === 'ludo' ? t('game.ludo') : gameKey === 'domino' ? t('game.domino') : gameKey === 'backgammon' ? t('game.backgammon') : t('game.chess');
  const gameIcon = gameKey === 'ludo' ? emoji('dice', '🎲', 20) : gameKey === 'domino' ? emoji('domino_tile', '🁣', 20) : gameKey === 'backgammon' ? emoji('backgammon', '🎯', 20) : emoji('chess_pawn', '♟', 20);

  el.innerHTML = `
    <div class="lobby-layout">
      <!-- Header -->
      <div class="lobby-header">
        <button id="lobby-back" class="lobby-back-btn">←</button>
        <div class="lobby-title">${emoji('challenge_swords', '⚔️', 18)} ${t('lobby.title')}</div>
      </div>

      <!-- Match Info -->
      <div class="lobby-match-info">
        <div class="lobby-game-badge" style="background:${gameKey === 'chess' ? 'var(--chess-primary)' : gameKey === 'ludo' ? 'var(--purple)' : gameKey === 'backgammon' ? 'var(--amber)' : 'var(--emerald)'};">
          <span style="font-size:20px;">${gameIcon}</span>
          <span style="font-size:13px;font-weight:600;">${gameLabel}</span>
        </div>
        ${gameKey === 'chess' ? `<div class="lobby-time-badge">${emoji('clock', '⏱️', 13)} ${tcLabel}</div>` : ''}
      </div>

      <!-- Players -->
      <div class="lobby-players">
        <!-- Host / You -->
        <div class="lobby-player-card">
          <div class="lobby-avatar ${isHost ? 'host' : ''}">
            ${myAvatar ? `<img src="${myAvatar}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">` : emoji('person', '👤', 28)}
          </div>
          <div class="lobby-player-name">${myName}</div>
          <div class="lobby-player-status ready">${emoji('check', '✓', 11)} ${t('lobby.ready')}</div>
          ${color ? `<div class="lobby-color" style="background:${color === 'w' ? '#fff' : 'var(--bg-dark)'};border:2px solid ${color === 'w' ? 'var(--text-light)' : 'var(--text-dim)'};width:20px;height:20px;border-radius:50%;margin-top:6px;"></div>` : ''}
        </div>

        <!-- VS divider -->
        <div class="lobby-vs">
          <div class="lobby-vs-circle">VS</div>
        </div>

        <!-- Opponent -->
        <div class="lobby-player-card">
          <div class="lobby-avatar opponent" id="lobby-opponent-avatar">
            ${friendAvatar ? `<img src="${friendAvatar}" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">` : `<div class="lobby-waiting-pulse">${emoji('hourglass', '⏳', 28)}</div>`}
          </div>
          <div class="lobby-player-name" id="lobby-opponent-name">${isHost ? (friendName || t('lobby.waiting')) : friendName}</div>
          <div class="lobby-player-status" id="lobby-opponent-status">${isHost ? t('lobby.waiting_accept') : `${emoji('check', '✓', 11)} ${t('lobby.ready')}`}</div>
          ${color ? `<div class="lobby-color" style="background:${color === 'w' ? 'var(--bg-dark)' : '#fff'};border:2px solid ${color === 'w' ? 'var(--text-dim)' : 'var(--text-light)'};width:20px;height:20px;border-radius:50%;margin-top:6px;"></div>` : ''}
        </div>
      </div>

      <!-- Status -->
      <div class="lobby-status" id="lobby-status">
        ${isHost ? `<div class="lobby-status-text">${emoji('hourglass', '⏳', 14)} ${t('lobby.waiting_opponent')}</div><div class="lobby-status-sub">${t('lobby.auto_start')}</div>` : `<div class="lobby-status-text" style="color:var(--success);">${emoji('check', '✓', 14)} ${t('lobby.ready_start')}</div>`}
      </div>

      <!-- Actions -->
      <div class="lobby-actions">
        ${!isHost ? `<button class="btn btn-primary lobby-btn" id="lobby-start" style="background:var(--success);">${emoji('play', '▶', 14)} ${t('lobby.start')}</button>` : ''}
        <button class="btn btn-secondary lobby-btn" id="lobby-cancel">${emoji('exit', '✕', 12)} ${t('common.cancel')}</button>
      </div>
    </div>
    <style>
      .lobby-layout { display:flex;flex-direction:column;align-items:center;height:100%;background:var(--bg-deep);padding:0; }
      .lobby-header { display:flex;align-items:center;gap:12px;padding:12px 16px;width:100%;background:var(--bg-panel);border-bottom:1px solid var(--border); }
      .lobby-back-btn { background:none;border:none;color:var(--text-secondary);font-size:20px;cursor:pointer;padding:4px 8px; }
      .lobby-title { font-size:16px;font-weight:700;color:var(--text-primary); }
      .lobby-match-info { display:flex;gap:10px;align-items:center;justify-content:center;padding:16px;width:100%; }
      .lobby-game-badge { display:flex;align-items:center;gap:6px;padding:8px 16px;border-radius:12px;color:#fff; }
      .lobby-time-badge { display:flex;align-items:center;gap:4px;padding:8px 14px;border-radius:10px;background:var(--bg-card);border:1px solid var(--border);color:var(--text-light);font-size:13px;font-weight:600; }
      .lobby-players { display:flex;align-items:center;justify-content:center;gap:16px;padding:20px 16px;width:100%; }
      .lobby-player-card { display:flex;flex-direction:column;align-items:center;gap:8px;flex:1;max-width:140px; }
      .lobby-avatar { width:72px;height:72px;border-radius:50%;background:var(--bg-hover);display:flex;align-items:center;justify-content:center;overflow:hidden;border:3px solid rgba(255,255,255,0.1); }
      .lobby-avatar.host { border-color:var(--gold); }
      .lobby-avatar.opponent { border-color:var(--blue); }
      .lobby-player-name { font-size:14px;font-weight:600;color:var(--text-primary);text-align:center;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
      .lobby-player-status { font-size:11px;color:var(--text-muted);text-align:center; }
      .lobby-player-status.ready { color:var(--success); }
      .lobby-vs { display:flex;align-items:center; }
      .lobby-vs-circle { width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,var(--gold),var(--warning));display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;color:var(--bg-dark); }
      .lobby-status { text-align:center;padding:16px 24px;width:100%; }
      .lobby-status-text { font-size:14px;font-weight:600;color:var(--gold);margin-bottom:4px; }
      .lobby-status-sub { font-size:12px;color:var(--text-muted); }
      .lobby-actions { display:flex;flex-direction:column;gap:10px;padding:16px 24px;width:100%;max-width:320px;margin-top:auto;padding-bottom:max(16px, env(safe-area-inset-bottom, 0px)); }
      .lobby-btn { width:100%;min-height:48px;font-size:14px;font-weight:600;border-radius:12px; }
      .lobby-waiting-pulse { animation:lobbyPulse 2s infinite; }
      @keyframes lobbyPulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:0.5;transform:scale(0.9)} }
    </style>
  `;

  // Bind events
  el.querySelector('#lobby-back').addEventListener('click', () => cancelAndLeave(el));
  el.querySelector('#lobby-cancel').addEventListener('click', () => cancelAndLeave(el));

  const startBtn = el.querySelector('#lobby-start');
  if (startBtn) {
    startBtn.addEventListener('click', () => startGame(el, params));
  }

  // If host, poll for opponent acceptance
  if (isHost) {
    pollTimer = setInterval(() => pollMatchStatus(el, params), 2000);
  } else {
    // Guest: wait briefly so host can detect acceptance, then start
    const statusEl = el.querySelector('#lobby-status');
    if (statusEl) {
      statusEl.innerHTML = `<div class="lobby-status-text" style="color:var(--success);">${emoji('check', '✓', 14)} ${t('lobby.accepted_preparing')}</div>`;
    }
    startTimeout = setTimeout(() => startGame(el, params), 2500);
  }
}

async function pollMatchStatus(el, params) {
  if (!matchId) return;
  if (pollInFlight) return; // prevent overlapping poll requests
  pollInFlight = true;

  const gameKey = params.gameKey || 'chess';
  const endpoint = gameKey === 'ludo' ? 'ludo-match.php' : gameKey === 'domino' ? 'domino-match.php' : gameKey === 'backgammon' ? 'backgammon-match.php' : 'game.php';

  try {
    const res = await net.post(endpoint, { action: 'get', match_id: matchId });
    if (!res || res.error) return;

    if (res.status === 'in_progress') {
      // Opponent accepted!
      clearInterval(pollTimer);
      pollTimer = null;
      lobbyState = 'starting';

      const statusEl = el.querySelector('#lobby-status');
      const oppStatus = el.querySelector('#lobby-opponent-status');
      if (statusEl) {
        statusEl.innerHTML = `<div class="lobby-status-text" style="color:var(--success);">${emoji('check', '✓', 14)} ${t('lobby.opponent_accepted')}</div>`;
      }
      if (oppStatus) {
        oppStatus.innerHTML = `<span style="color:var(--success);">${emoji('check', '✓', 11)} ${t('lobby.ready')}</span>`;
        oppStatus.classList.add('ready');
      }

      audio.play('reward');
      juice.hapticSuccess();

      // Bug 2 fix: resolve color from match data if params.color is undefined
      if (!params.color && res.white_player_id) {
        const userId = store.get('player.id');
        params.color = (res.white_player_id == userId) ? 'w' : 'b';
      }

      startTimeout = setTimeout(() => startGame(el, params), 1500);
    }
  } catch (e) {
  } finally {
    pollInFlight = false;
  }
}

function startGame(el, params) {
  // Concurrency guard: prevent multiple startGame calls
  if (gameStarted) return;
  // Ensure lobby scene is still mounted (not navigated away)
  if (!mounted) return;

  gameStarted = true;

  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  if (startTimeout) { clearTimeout(startTimeout); startTimeout = null; }

  const gameKey = params.gameKey || 'chess';

  // Colour is deliberately NOT guessed here. Deriving it from isHost was wrong
  // whenever both clients believed they were the host, and both then became
  // White. When we have not been told, chess-game asks the server.
  const color = (params.color === 'w' || params.color === 'b') ? params.color : undefined;

  if (gameKey === 'chess') {
    scene.replace('chess-game', {
      mode: 'live',
      matchId: params.matchId,
      color,
      timeControl: params.timeControl,
      isFriendly: true
    });
  } else if (gameKey === 'ludo') {
    scene.replace('ludo-game', {
      mode: 'live',
      matchId: params.matchId,
      isFriendly: true
    });
  } else if (gameKey === 'domino') {
    scene.replace('domino-game', {
      mode: 'live',
      matchId: params.matchId,
      playerIndex: params.playerIndex ?? (params.isHost ? 0 : 1),
      isFriendly: true
    });
  } else if (gameKey === 'backgammon') {
    scene.replace('backgammon-game', {
      mode: 'live',
      matchId: params.matchId,
      color: color,
      isFriendly: true
    });
  }
}

async function cancelAndLeave(el) {
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }

  if (matchId && lobbyState === 'waiting') {
    try {
      await net.post('friends.php', { action: 'decline-invite', match_id: matchId, game_key: currentGameKey });
    } catch (e) {}
  }

  audio.play('click');
  scene.pop();
}

function formatTimeControl(tc) {
  if (tc.includes('bullet_1')) return t('time.1min');
  if (tc.includes('blitz_3')) return t('time.3min');
  if (tc.includes('blitz_5')) return t('time.5min');
  if (tc.includes('rapid_10')) return t('time.10min');
  if (tc.includes('rapid_15')) return t('time.15min');
  if (tc.includes('classical')) return t('time.30min');
  return tc;
}

export function unmountLobby() {
  mounted = false;
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  if (startTimeout) { clearTimeout(startTimeout); startTimeout = null; }
  matchId = null;
}
