import * as bus from '../../../core/bus.js';
import * as scene from '../../../core/scene.js';
import * as audio from '../../../core/audio.js';
import * as store from '../../../core/store.js';
import { t } from '../../../core/i18n.js';
import { createCanvas, clear } from '../../../core/canvas.js';
import * as rules from '../logic/rules.js';
import * as juice from '../../../core/juice.js';

let game, validMoves, canvasCtx, canvasEl, boardSize;

const COLORS = ['#E53935', '#1E88E5', '#43A047', '#FDD835'];
const COLORS_LIGHT = ['#EF9A9A', '#90CAF9', '#A5D6A7', '#FFF59D'];
const BG_COLOR = '#FAFAFA';
const PATH_COLOR = '#FFFFFF';
const BORDER_COLOR = '#E0E0E0';

export function mountGame(el, params) {
  const { mode = 'bot', numPlayers = 4 } = params;
  scene.enterGameMode();

  game = rules.createGame(numPlayers);
  validMoves = [];

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:#1a2440;">
      <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:#0a1020;border-bottom:1px solid rgba(255,255,255,0.06);">
        <span style="font-size:14px;font-weight:600;color:#f8fafc;">${t('game.ludo')}</span>
        <span id="ludo-turn" style="font-size:13px;color:${COLORS[0]};">${t('game.your_turn')}</span>
      </div>
      <div id="ludo-board" style="flex:1;display:flex;align-items:center;justify-content:center;padding:8px;"></div>
      <div style="display:flex;align-items:center;gap:16px;padding:12px;background:#0a1020;border-top:1px solid rgba(255,255,255,0.06);justify-content:center;">
        <div id="dice-display" style="width:56px;height:56px;background:#1a2440;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:28px;font-weight:800;font-family:Inter,sans-serif;border:2px solid rgba(255,255,255,0.1);color:#f8fafc;"></div>
        <button class="btn btn-primary" id="roll-btn" style="font-size:16px;padding:12px 32px;">🎲 ${t('game.ludo') === 'لودو' ? 'ارمِ النرد' : 'Roll Dice'}</button>
      </div>
    </div>
  `;

  const boardContainer = el.querySelector('#ludo-board');
  boardSize = Math.min(boardContainer.clientWidth || 360, boardContainer.clientHeight || 360, 380);
  const { canvas, ctx } = createCanvas(boardContainer, boardSize, boardSize);
  canvas.style.cssText = 'width:100%;max-width:380px;height:auto;aspect-ratio:1;border-radius:8px;box-shadow:0 4px 20px rgba(0,0,0,0.3);';
  canvasCtx = ctx;
  canvasEl = canvas;

  drawBoard();
  updateTurnDisplay(el);

  el.querySelector('#roll-btn').addEventListener('click', () => handleRoll(el));
  bus.emit('game:started', { gameKey: 'ludo', mode });
}

function handleRoll(el) {
  if (game.rolled || game.gameOver) return;
  if (game.currentPlayer !== 0) return;

  const dice = rules.rollDice();
  game.diceValue = dice;
  game.rolled = true;
  audio.play('dice', 'game');
  juice.hapticMedium();

  const diceEl = el.querySelector('#dice-display');
  diceEl.textContent = dice;
  diceEl.style.color = '#E4AC38';
  juice.slamIn(diceEl, { scale: 1.6, duration: 350 });
  juice.shake(el.querySelector('#ludo-board'), 2, 150);
  if (dice === 6) {
    juice.starBurst(diceEl.getBoundingClientRect().left + 28, diceEl.getBoundingClientRect().top + 28, 5);
  }

  validMoves = rules.getValidMoves(game, 0, dice);

  if (validMoves.length === 0) {
    setTimeout(() => {
      game.rolled = false;
      rules.nextTurn(game);
      diceEl.style.color = '#f8fafc';
      updateTurnDisplay(el);
      drawBoard();
      if (game.currentPlayer !== 0) botSequence(el);
    }, 800);
    return;
  }

  if (validMoves.length === 1) {
    applyPlayerMove(el, validMoves[0]);
    return;
  }

  drawBoard();
  // For multiple moves, auto-pick the best (capture > finish > enter > random)
  const best = validMoves.find(m => m.type === 'capture') ||
               validMoves.find(m => m.type === 'finish') ||
               validMoves.find(m => m.type === 'enter') ||
               validMoves[0];
  setTimeout(() => applyPlayerMove(el, best), 500);
}

function applyPlayerMove(el, move) {
  rules.applyMove(game, 0, move);
  game.rolled = false;
  if (move.type === 'capture') {
    audio.play('capture', 'game');
    juice.shake(el, 4, 250);
    juice.hapticHeavy();
    juice.confetti(window.innerWidth / 2, window.innerHeight / 2, 15);
  } else if (move.type === 'finish') {
    audio.play('win', 'reward');
    juice.starBurst(window.innerWidth / 2, window.innerHeight / 2, 8);
    juice.hapticSuccess();
  } else {
    audio.play('move', 'game');
  }

  if (game.gameOver || game.players[0].finished) { endGame(el); return; }

  rules.nextTurn(game);
  updateTurnDisplay(el);
  drawBoard();

  el.querySelector('#dice-display').style.color = '#f8fafc';

  if (game.currentPlayer !== 0) {
    setTimeout(() => botSequence(el), 600);
  }
}

function botSequence(el) {
  if (game.gameOver || game.currentPlayer === 0) return;

  const dice = rules.rollDice();
  game.diceValue = dice;
  el.querySelector('#dice-display').textContent = dice;
  audio.play('dice', 'game');

  const move = rules.getBotMove(game, game.currentPlayer, dice);
  if (move) {
    rules.applyMove(game, game.currentPlayer, move);
    if (move.type === 'capture') audio.play('capture', 'game');
  }

  if (game.gameOver) { endGame(el); return; }

  rules.nextTurn(game);
  updateTurnDisplay(el);
  drawBoard();

  if (game.currentPlayer !== 0) {
    setTimeout(() => botSequence(el), 400);
  }
}

function drawBoard() {
  const ctx = canvasCtx;
  const s = boardSize;
  const cell = s / 15;

  clear(ctx, s, s);

  // Background
  ctx.fillStyle = BG_COLOR;
  ctx.fillRect(0, 0, s, s);

  // Home zones (4 corners)
  drawHomeZone(ctx, 0, 0, cell * 6, 0); // Red top-left
  drawHomeZone(ctx, cell * 9, 0, cell * 6, 1); // Blue top-right
  drawHomeZone(ctx, cell * 9, cell * 9, cell * 6, 2); // Green bottom-right
  drawHomeZone(ctx, 0, cell * 9, cell * 6, 3); // Yellow bottom-left

  // Cross paths (the playing area)
  ctx.fillStyle = PATH_COLOR;
  ctx.strokeStyle = BORDER_COLOR;
  ctx.lineWidth = 0.5;
  // Top vertical path
  ctx.fillRect(cell * 6, 0, cell * 3, cell * 6);
  // Bottom vertical path
  ctx.fillRect(cell * 6, cell * 9, cell * 3, cell * 6);
  // Left horizontal path
  ctx.fillRect(0, cell * 6, cell * 6, cell * 3);
  // Right horizontal path
  ctx.fillRect(cell * 9, cell * 6, cell * 6, cell * 3);
  // Center
  ctx.fillRect(cell * 6, cell * 6, cell * 3, cell * 3);

  // Draw grid lines on paths
  ctx.strokeStyle = '#E0E0E0';
  ctx.lineWidth = 0.5;
  for (let i = 0; i <= 15; i++) {
    // Vertical lines in cross
    if (i >= 6 && i <= 9) {
      ctx.beginPath(); ctx.moveTo(i * cell, 0); ctx.lineTo(i * cell, s); ctx.stroke();
    }
    if (i >= 6 && i <= 9) {
      ctx.beginPath(); ctx.moveTo(0, i * cell); ctx.lineTo(s, i * cell); ctx.stroke();
    }
  }
  // Cells in paths
  for (let i = 0; i < 6; i++) {
    ctx.beginPath(); ctx.moveTo(cell * 6, i * cell); ctx.lineTo(cell * 9, i * cell); ctx.stroke();
    ctx.beginPath(); ctx.moveTo(cell * 6, (i + 9) * cell); ctx.lineTo(cell * 9, (i + 9) * cell); ctx.stroke();
    ctx.beginPath(); ctx.moveTo(i * cell, cell * 6); ctx.lineTo(i * cell, cell * 9); ctx.stroke();
    ctx.beginPath(); ctx.moveTo((i + 9) * cell, cell * 6); ctx.lineTo((i + 9) * cell, cell * 9); ctx.stroke();
  }

  // Home columns (colored)
  // Red home column (top, column 7 going down)
  for (let i = 1; i <= 5; i++) {
    ctx.fillStyle = COLORS_LIGHT[0];
    ctx.fillRect(cell * 7 + 1, i * cell + 1, cell - 2, cell - 2);
  }
  // Blue home column (right, row 7 going left)
  for (let i = 1; i <= 5; i++) {
    ctx.fillStyle = COLORS_LIGHT[1];
    ctx.fillRect((14 - i) * cell + 1, cell * 7 + 1, cell - 2, cell - 2);
  }
  // Green home column (bottom, column 7 going up)
  for (let i = 1; i <= 5; i++) {
    ctx.fillStyle = COLORS_LIGHT[2];
    ctx.fillRect(cell * 7 + 1, (14 - i) * cell + 1, cell - 2, cell - 2);
  }
  // Yellow home column (left, row 7 going right)
  for (let i = 1; i <= 5; i++) {
    ctx.fillStyle = COLORS_LIGHT[3];
    ctx.fillRect(i * cell + 1, cell * 7 + 1, cell - 2, cell - 2);
  }

  // Center triangle finish
  ctx.fillStyle = COLORS[0]; ctx.beginPath();
  ctx.moveTo(cell * 6, cell * 6); ctx.lineTo(cell * 7.5, cell * 7.5); ctx.lineTo(cell * 6, cell * 9); ctx.fill();
  ctx.fillStyle = COLORS[1]; ctx.beginPath();
  ctx.moveTo(cell * 6, cell * 6); ctx.lineTo(cell * 7.5, cell * 7.5); ctx.lineTo(cell * 9, cell * 6); ctx.fill();
  ctx.fillStyle = COLORS[2]; ctx.beginPath();
  ctx.moveTo(cell * 9, cell * 9); ctx.lineTo(cell * 7.5, cell * 7.5); ctx.lineTo(cell * 9, cell * 6); ctx.fill();
  ctx.fillStyle = COLORS[3]; ctx.beginPath();
  ctx.moveTo(cell * 9, cell * 9); ctx.lineTo(cell * 7.5, cell * 7.5); ctx.lineTo(cell * 6, cell * 9); ctx.fill();

  // Draw pieces
  game.players.forEach((player, pIdx) => {
    player.pieces.forEach((piece) => {
      if (piece.finished) return;
      const color = COLORS[pIdx];
      if (piece.pos === -1) {
        drawPieceInHome(ctx, pIdx, piece, cell, color);
      } else {
        const pos = getBoardPosition(piece.pos, pIdx, cell);
        drawPieceAt(ctx, pos.x, pos.y, cell, color);
      }
    });
  });
}

function drawHomeZone(ctx, x, y, size, colorIdx) {
  ctx.fillStyle = COLORS[colorIdx];
  ctx.fillRect(x, y, size, size);
  ctx.fillStyle = BG_COLOR;
  const inset = size * 0.15;
  ctx.fillRect(x + inset, y + inset, size - inset * 2, size - inset * 2);

  // Draw home circles (starting positions)
  const cx = x + size / 2;
  const cy = y + size / 2;
  const spread = size * 0.22;
  const positions = [[-1,-1],[1,-1],[-1,1],[1,1]];
  positions.forEach(([dx, dy]) => {
    ctx.beginPath();
    ctx.arc(cx + dx * spread, cy + dy * spread, size * 0.08, 0, Math.PI * 2);
    ctx.fillStyle = COLORS_LIGHT[colorIdx];
    ctx.fill();
    ctx.strokeStyle = COLORS[colorIdx];
    ctx.lineWidth = 1.5;
    ctx.stroke();
  });
}

function drawPieceInHome(ctx, playerIdx, piece, cell, color) {
  const zones = [
    { x: 0, y: 0 }, { x: 9, y: 0 }, { x: 9, y: 9 }, { x: 0, y: 9 }
  ];
  const zone = zones[playerIdx];
  const zoneSize = cell * 6;
  const cx = (zone.x * cell) + zoneSize / 2;
  const cy = (zone.y * cell) + zoneSize / 2;
  const spread = zoneSize * 0.22;
  const idx = parseInt(piece.id.split('-')[1]);
  const positions = [[-1,-1],[1,-1],[-1,1],[1,1]];
  const [dx, dy] = positions[idx];

  drawPieceAt(ctx, cx + dx * spread, cy + dy * spread, cell, color);
}

function drawPieceAt(ctx, x, y, cell, color) {
  const r = cell * 0.35;
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
  ctx.strokeStyle = '#fff';
  ctx.lineWidth = 2;
  ctx.stroke();
  // Inner highlight
  ctx.beginPath();
  ctx.arc(x - r * 0.2, y - r * 0.2, r * 0.3, 0, Math.PI * 2);
  ctx.fillStyle = 'rgba(255,255,255,0.4)';
  ctx.fill();
}

function getBoardPosition(localPos, playerIdx, cell) {
  // Simplified position mapping - places pieces around the board
  const startSquares = [
    { x: 6, y: 1 }, { x: 13, y: 6 }, { x: 8, y: 13 }, { x: 1, y: 8 }
  ];
  const start = startSquares[playerIdx];
  // Just place at approximate position for now
  const angle = ((localPos + playerIdx * 13) / 52) * Math.PI * 2;
  const radius = cell * 5.5;
  const centerX = cell * 7.5;
  const centerY = cell * 7.5;
  return {
    x: centerX + Math.cos(angle) * radius,
    y: centerY + Math.sin(angle) * radius
  };
}

function updateTurnDisplay(el) {
  const turnEl = el.querySelector('#ludo-turn');
  if (game.currentPlayer === 0) {
    turnEl.textContent = t('game.your_turn');
    turnEl.style.color = COLORS[0];
  } else {
    turnEl.textContent = `Bot ${game.currentPlayer}`;
    turnEl.style.color = COLORS[game.currentPlayer];
  }
}

function endGame(el) {
  game.gameOver = true;
  const result = game.winners[0] === 0 ? 'win' : 'loss';
  audio.play(result === 'win' ? 'win' : 'lose', 'game');

  setTimeout(() => {
    scene.exitGameMode();
    scene.replace('ludo-result', { result, winners: game.winners });
    bus.emit('game:ended', { gameKey: 'ludo', result });
  }, 1000);
}
