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

let pollTimer = null;
let matchId = null;
let lobbyState = 'waiting'; // waiting | ready | starting

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

  if (pollTimer) clearInterval(pollTimer);

  const myName = store.get('player.display_name') || store.get('player.username') || 'أنت';
  const myAvatar = store.get('player.avatar_url');
  const friendName = friendProfile?.display_name || friendProfile?.username || 'الخصم';
  const friendAvatar = friendProfile?.avatar_url;

  const tcLabel = formatTimeControl(timeControl);
  const gameLabel = gameKey === 'ludo' ? 'لودو' : gameKey === 'domino' ? 'دومينو' : 'شطرنج';
  const gameIcon = gameKey === 'ludo' ? '🎲' : gameKey === 'domino' ? '🁣' : '♟';

  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)} غرفة التحدي</div>
      </div>

      <!-- Match Info -->
      <div class="lobby-match-info">
        <div class="lobby-game-badge" style="background:${gameKey === 'chess' ? '#2563EB' : gameKey === 'ludo' ? '#8B5CF6' : '#10B981'};">
          <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)} جاهز</div>
          ${color ? `<div class="lobby-color" style="background:${color === 'w' ? '#fff' : '#1a1a1a'};border:2px solid ${color === 'w' ? '#e2e8f0' : '#475569'};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 || 'في الانتظار...') : friendName}</div>
          <div class="lobby-player-status" id="lobby-opponent-status">${isHost ? 'في انتظار القبول...' : `${emoji('check', '✓', 11)} جاهز`}</div>
          ${color ? `<div class="lobby-color" style="background:${color === 'w' ? '#1a1a1a' : '#fff'};border:2px solid ${color === 'w' ? '#475569' : '#e2e8f0'};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)} في انتظار الخصم...</div><div class="lobby-status-sub">سيتم بدء المباراة تلقائياً عند قبول التحدي</div>` : `<div class="lobby-status-text" style="color:#34D399;">${emoji('check', '✓', 14)} جاهز للبدء!</div>`}
      </div>

      <!-- Actions -->
      <div class="lobby-actions">
        ${!isHost ? `<button class="btn btn-primary lobby-btn" id="lobby-start" style="background:#34D399;">${emoji('play', '▶', 14)} ابدأ المباراة</button>` : ''}
        <button class="btn btn-secondary lobby-btn" id="lobby-cancel">${emoji('exit', '✕', 12)} إلغاء</button>
      </div>
    </div>
    <style>
      .lobby-layout { display:flex;flex-direction:column;align-items:center;height:100%;background:#0a0a14;padding:0; }
      .lobby-header { display:flex;align-items:center;gap:12px;padding:12px 16px;width:100%;background:#0f0f1e;border-bottom:1px solid rgba(255,255,255,0.06); }
      .lobby-back-btn { background:none;border:none;color:#94a3b8;font-size:20px;cursor:pointer;padding:4px 8px; }
      .lobby-title { font-size:16px;font-weight:700;color:#f8fafc; }
      .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:#1a1a2e;border:1px solid rgba(255,255,255,0.08);color:#e2e8f0;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:#2a2a4a;display:flex;align-items:center;justify-content:center;overflow:hidden;border:3px solid rgba(255,255,255,0.1); }
      .lobby-avatar.host { border-color:#E4AC38; }
      .lobby-avatar.opponent { border-color:#3B82F6; }
      .lobby-player-name { font-size:14px;font-weight:600;color:#f8fafc;text-align:center;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
      .lobby-player-status { font-size:11px;color:#64748b;text-align:center; }
      .lobby-player-status.ready { color:#34D399; }
      .lobby-vs { display:flex;align-items:center; }
      .lobby-vs-circle { width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,#E4AC38,#F59E0B);display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;color:#1a1a1a; }
      .lobby-status { text-align:center;padding:16px 24px;width:100%; }
      .lobby-status-text { font-size:14px;font-weight:600;color:#E4AC38;margin-bottom:4px; }
      .lobby-status-sub { font-size:12px;color:#64748b; }
      .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 already accepted — can start immediately
    startGame(el, params);
  }
}

async function pollMatchStatus(el, params) {
  if (!matchId) return;
  const gameKey = params.gameKey || 'chess';
  const endpoint = gameKey === 'ludo' ? 'ludo-match.php' : gameKey === 'domino' ? 'domino-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:#34D399;">${emoji('check', '✓', 14)} الخصم قبل! جاري البدء...</div>`;
      }
      if (oppStatus) {
        oppStatus.innerHTML = `<span style="color:#34D399;">${emoji('check', '✓', 11)} جاهز</span>`;
        oppStatus.classList.add('ready');
      }

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

      setTimeout(() => startGame(el, params), 1500);
    }
  } catch (e) {}
}

function startGame(el, params) {
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }

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

  if (gameKey === 'chess') {
    scene.replace('chess-game', {
      mode: 'live',
      matchId: params.matchId,
      color: params.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.isHost ? 0 : 1,
      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 });
    } catch (e) {}
  }

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

function formatTimeControl(tc) {
  if (tc.includes('bullet_1')) return '1 دقيقة';
  if (tc.includes('blitz_3')) return '3 دقائق';
  if (tc.includes('blitz_5')) return '5 دقائق';
  if (tc.includes('rapid_10')) return '10 دقائق';
  if (tc.includes('rapid_15')) return '15 دقيقة';
  if (tc.includes('classical')) return '30 دقيقة';
  return tc;
}

export function unmountLobby() {
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  matchId = null;
}
