import * as net from '../../../core/net.js';
import * as scene from '../../../core/scene.js';
import * as audio from '../../../core/audio.js';
import * as bus from '../../../core/bus.js';
import { t } from '../../../core/i18n.js';
import { ChessBoard } from '../../chess/canvas/board.js';
import * as engine from '../../chess/logic/engine.js';
import { emoji } from '../../../core/theme.js';

let board, puzzleData, moveIndex, solved;

export async function mountPuzzle(el) {
  scene.enterGameMode();

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:var(--bg-deep);">
      <div style="display:flex;align-items:center;justify-content:space-between;padding:var(--s-2) var(--s-3);background:var(--bg-base);">
        <button class="btn btn-secondary" id="back-btn" style="min-height:32px;padding:var(--s-1) var(--s-3);font-size:12px;">${t('game.back')}</button>
        <span style="font-size:14px;font-weight:600;">${t('puzzle.title')}</span>
        <span id="puzzle-rating" style="font-size:13px;color:var(--gold);font-family:var(--font-lat);"></span>
      </div>
      <div id="puzzle-board" style="flex:1;display:flex;align-items:center;justify-content:center;padding:var(--s-2);"></div>
      <div id="puzzle-status" style="text-align:center;padding:var(--s-3);font-size:15px;font-weight:600;background:var(--bg-base);"></div>
    </div>
  `;

  el.querySelector('#back-btn').addEventListener('click', () => {
    audio.play('click');
    scene.exitGameMode();
    bus.emit('navigate', { world: 'play', scene: 'play-table' });
  });

  await loadPuzzle(el);
}

async function loadPuzzle(el) {
  try {
    const data = await net.get('puzzles.php', { action: 'random' });
    if (data.error) throw new Error(data.error);
    puzzleData = data;
    setupPuzzle(el, data);
  } catch (e) {
    el.querySelector('#puzzle-status').textContent = t('common.error');
  }
}

function setupPuzzle(el, puzzle) {
  const fen = puzzle.fen;
  const moves = (puzzle.moves || '').split(' ').filter(Boolean);
  moveIndex = 0;
  solved = false;

  engine.create(fen);
  const ratingEl = el.querySelector('#puzzle-rating');
  ratingEl.innerHTML = `${emoji('lightning', '⚡', 13)} ${puzzle.rating || '?'}`;

  const playerColor = engine.turn() === 'w' ? 'b' : 'w';

  if (moves.length > 0) {
    engine.moveUci(moves[0]);
    moveIndex = 1;
  }

  const boardContainer = el.querySelector('#puzzle-board');
  boardContainer.innerHTML = '';
  board = new ChessBoard(boardContainer, {
    flipped: playerColor === 'b',
    interactive: true,
    onMove: (from, to) => handlePuzzleMove(el, from, to, moves, playerColor)
  });

  board.canSelect = (piece) => !solved && piece[0] === playerColor;
  board.showLegalMoves = (square) => {
    board.highlights.legalMoves = engine.legalMoves(square);
  };

  board.setPosition(engine.fen());
  el.querySelector('#puzzle-status').textContent = t('game.your_turn');
  el.querySelector('#puzzle-status').style.color = 'var(--text-primary)';
}

function handlePuzzleMove(el, from, to, moves, playerColor) {
  if (solved || moveIndex >= moves.length) return;

  const expectedMove = moves[moveIndex];
  const expectedFrom = expectedMove.substring(0, 2);
  const expectedTo = expectedMove.substring(2, 4);

  if (from === expectedFrom && to === expectedTo) {
    const promo = expectedMove.length > 4 ? expectedMove[4] : undefined;
    engine.move(from, to, promo);
    board.setPosition(engine.fen());
    board.setLastMove(from, to);
    audio.play('move', 'game');
    moveIndex++;

    if (moveIndex >= moves.length) {
      onSolved(el);
      return;
    }

    setTimeout(() => {
      const response = moves[moveIndex];
      const rf = response.substring(0, 2);
      const rt = response.substring(2, 4);
      const rp = response.length > 4 ? response[4] : undefined;
      engine.move(rf, rt, rp);
      board.setPosition(engine.fen());
      board.setLastMove(rf, rt);
      audio.play('move', 'game');
      moveIndex++;

      if (moveIndex >= moves.length) {
        onSolved(el);
      }
    }, 500);
  } else {
    onFailed(el);
  }
}

function onSolved(el) {
  solved = true;
  board.interactive = false;
  audio.play('win', 'reward');
  const status = el.querySelector('#puzzle-status');
  status.innerHTML = `${emoji('checkmark', '✅', 15)} ${t('puzzle.correct')}`;
  status.style.color = 'var(--win)';

  setTimeout(() => {
    loadPuzzle(el);
  }, 2000);
}

function onFailed(el) {
  solved = true;
  board.interactive = false;
  audio.play('lose', 'game');
  const status = el.querySelector('#puzzle-status');
  status.innerHTML = `${emoji('cross', '❌', 15)} ${t('puzzle.wrong')}`;
  status.style.color = 'var(--loss)';

  setTimeout(() => {
    loadPuzzle(el);
  }, 2000);
}
