import * as scene from '../../../core/scene.js';
import * as net from '../../../core/net.js';
import * as audio from '../../../core/audio.js';
import * as realtime from '../../../core/realtime.js';
import { ChessBoard } from '../canvas/board.js';
import * as engine from '../logic/engine.js';
import { ChessClock, parseTimeControl } from '../logic/clock.js';
import { emoji } from '../../../core/theme.js';
import { t } from '../../../core/i18n.js';

let board, clock, unsub;

export async function mountSpectate(el, params = {}) {
  const { matchId } = params;
  if (!matchId) { scene.pop(); return; }

  scene.enterGameMode();

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-panel);justify-content:center;">
      <div style="padding:8px 14px;display:flex;align-items:center;gap:8px;">
        <button class="btn btn-secondary" id="back-btn" style="width:34px;height:34px;padding:0;">←</button>
        <div style="flex:1;display:flex;align-items:center;gap:8px;">
          <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--error);animation:spectatePulse 1.5s infinite;"></span>
          <span style="font-size:13px;font-weight:600;color:var(--error);">${t('spectate.live')}</span>
        </div>
      </div>
      <div class="chess-bar" style="display:flex;align-items:center;justify-content:space-between;padding:8px 14px;">
        <div style="display:flex;align-items:center;gap:8px;">
          <div style="width:32px;height:32px;border-radius:50%;background:var(--bg-hover);display:flex;align-items:center;justify-content:center;">${emoji('person', '👤', 14)}</div>
          <span id="black-name" style="font-size:13px;font-weight:600;color:var(--text-primary);">${t('spectate.black')}</span>
        </div>
        <div id="clock-black" style="font-size:16px;font-weight:700;font-family:'SF Mono',monospace;background:var(--bg-card);padding:4px 10px;border-radius:6px;color:var(--text-secondary);">--:--</div>
      </div>
      <div id="board-container" style="flex:0 0 auto;display:flex;align-items:center;justify-content:center;padding:4px 6px;"></div>
      <div class="chess-bar" style="display:flex;align-items:center;justify-content:space-between;padding:8px 14px;">
        <div style="display:flex;align-items:center;gap:8px;">
          <div style="width:32px;height:32px;border-radius:50%;background:var(--bg-hover);display:flex;align-items:center;justify-content:center;">${emoji('person', '👤', 14)}</div>
          <span id="white-name" style="font-size:13px;font-weight:600;color:var(--text-primary);">${t('spectate.white')}</span>
        </div>
        <div id="clock-white" style="font-size:16px;font-weight:700;font-family:'SF Mono',monospace;background:var(--bg-card);padding:4px 10px;border-radius:6px;color:var(--text-secondary);">--:--</div>
      </div>
      <div id="move-list" style="max-height:40px;overflow-x:auto;white-space:nowrap;padding:4px 14px;font-family:'SF Mono',monospace;font-size:12px;color:var(--text-secondary);display:flex;gap:4px;align-items:center;"></div>
    </div>
    <style>
      @keyframes spectatePulse { 0%,100%{opacity:1}50%{opacity:0.4} }
    </style>
  `;

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

  engine.create();

  const boardContainer = el.querySelector('#board-container');
  board = new ChessBoard(boardContainer, { interactive: false });

  // Fetch initial match state
  let matchData;
  try {
    matchData = await net.post('game.php', { action: 'get', match_id: matchId });
    if (!matchData || matchData.error) {
      el.querySelector('#board-container').innerHTML = `<div style="color:var(--error);padding:24px;">${t('game.not_found')}</div>`;
      return;
    }
  } catch (e) {
    el.querySelector('#board-container').innerHTML = `<div style="color:var(--error);padding:24px;">${t('common.error')}</div>`;
    return;
  }

  // Load player names
  loadPlayerNames(el, matchData.white_player_id, matchData.black_player_id);

  // Set position
  if (matchData.current_fen) {
    engine.load(matchData.current_fen);
    board.setPosition(matchData.current_fen);
  }

  // Set clocks
  const tc = parseTimeControl(matchData.time_control || 'rapid_10_0');
  clock = new ChessClock(tc.time, tc.increment);
  if (matchData.white_time_remaining_ms) clock.white = matchData.white_time_remaining_ms;
  if (matchData.black_time_remaining_ms) clock.black = matchData.black_time_remaining_ms;
  updateClockDisplay(el);

  // Load move list
  if (matchData.moves) {
    const moves = typeof matchData.moves === 'string' ? JSON.parse(matchData.moves) : matchData.moves;
    renderMoveList(el, moves);
  }

  // If game already over
  if (matchData.status === 'completed') {
    showResult(el, matchData.result);
    return;
  }

  // Subscribe to realtime updates
  unsub = realtime.subscribeMatch(matchId, (payload) => {
    if (payload.type !== 'UPDATE') return;
    const data = payload.new;
    if (!data) return;

    if (data.current_fen) {
      engine.load(data.current_fen);
      board.setPosition(data.current_fen);
      audio.play('move', 'game');
    }

    if (data.white_time_remaining_ms != null) clock.white = data.white_time_remaining_ms;
    if (data.black_time_remaining_ms != null) clock.black = data.black_time_remaining_ms;
    updateClockDisplay(el);

    if (data.moves) {
      const moves = typeof data.moves === 'string' ? JSON.parse(data.moves) : data.moves;
      renderMoveList(el, moves);
    }

    if (data.status === 'completed') {
      showResult(el, data.result);
      cleanup();
    }
  });
}

async function loadPlayerNames(el, whiteId, blackId) {
  try {
    const [wp, bp] = await Promise.all([
      net.get('profile.php', { id: whiteId }),
      net.get('profile.php', { id: blackId })
    ]);
    if (wp && !wp.error) el.querySelector('#white-name').textContent = wp.display_name || t('spectate.white');
    if (bp && !bp.error) el.querySelector('#black-name').textContent = bp.display_name || t('spectate.black');
  } catch (e) {}
}

function updateClockDisplay(el) {
  const wEl = el.querySelector('#clock-white');
  const bEl = el.querySelector('#clock-black');
  if (wEl) wEl.textContent = clock.format(clock.white);
  if (bEl) bEl.textContent = clock.format(clock.black);
}

function renderMoveList(el, moves) {
  const container = el.querySelector('#move-list');
  if (!container || !Array.isArray(moves)) return;
  let html = '';
  for (let i = 0; i < moves.length; i += 2) {
    const num = Math.floor(i / 2) + 1;
    html += `<span style="color:var(--text-dim);">${num}.</span> `;
    html += `<span>${moves[i]?.san || moves[i] || ''}</span> `;
    if (moves[i + 1]) html += `<span>${moves[i + 1]?.san || moves[i + 1] || ''}</span> `;
  }
  container.innerHTML = html;
  container.scrollLeft = container.scrollWidth;
}

function showResult(el, result) {
  const text = result === 'white_wins' ? t('spectate.white_wins') :
               result === 'black_wins' ? t('spectate.black_wins') :
               result === 'draw' ? t('game.draw_game') : t('spectate.game_over');
  const overlay = document.createElement('div');
  overlay.style.cssText = 'position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.9);color:var(--text-primary);padding:16px 32px;border-radius:12px;font-size:16px;font-weight:700;z-index:30;text-align:center;';
  overlay.textContent = text;
  el.querySelector('#board-container').style.position = 'relative';
  el.querySelector('#board-container').appendChild(overlay);
}

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