const BOARD_SIZE = 52;
const HOME_STRETCH = 6;
const SAFE_SQUARES = [0, 8, 13, 21, 26, 34, 39, 47];

const START_POSITIONS = [0, 13, 26, 39];
const HOME_ENTRIES = [50, 11, 24, 37];

export const COLORS = ['red', 'blue', 'green', 'yellow'];
export const COLOR_CSS = ['#EF4444', '#3B82F6', '#10B981', '#F59E0B'];

export function createGame(numPlayers = 4) {
  const players = [];
  for (let i = 0; i < numPlayers; i++) {
    players.push({
      color: COLORS[i],
      pieces: [
        { id: `${i}-0`, pos: -1, finished: false },
        { id: `${i}-1`, pos: -1, finished: false },
        { id: `${i}-2`, pos: -1, finished: false },
        { id: `${i}-3`, pos: -1, finished: false }
      ],
      finished: false
    });
  }
  return {
    players,
    currentPlayer: 0,
    diceValue: null,
    rolled: false,
    numPlayers,
    winners: [],
    gameOver: false,
    extraTurn: false
  };
}

export function rollDice() {
  return Math.floor(Math.random() * 6) + 1;
}

export function getValidMoves(game, playerIdx, dice) {
  const player = game.players[playerIdx];
  const moves = [];

  for (const piece of player.pieces) {
    if (piece.finished) continue;

    if (piece.pos === -1) {
      if (dice === 6) {
        moves.push({ pieceId: piece.id, from: -1, to: START_POSITIONS[playerIdx], type: 'enter' });
      }
    } else {
      const globalPos = toGlobalPos(piece.pos, playerIdx);
      const newLocalPos = piece.pos + dice;

      if (newLocalPos === BOARD_SIZE + HOME_STRETCH) {
        moves.push({ pieceId: piece.id, from: piece.pos, to: newLocalPos, type: 'finish' });
      } else if (newLocalPos < BOARD_SIZE + HOME_STRETCH) {
        const isHomeStretch = newLocalPos >= BOARD_SIZE;
        if (!isHomeStretch) {
          const newGlobal = toGlobalPos(newLocalPos, playerIdx);
          const captured = checkCapture(game, playerIdx, newGlobal);
          moves.push({ pieceId: piece.id, from: piece.pos, to: newLocalPos, type: captured ? 'capture' : 'move' });
        } else {
          moves.push({ pieceId: piece.id, from: piece.pos, to: newLocalPos, type: 'home' });
        }
      }
    }
  }

  return moves;
}

export function applyMove(game, playerIdx, move) {
  const player = game.players[playerIdx];
  const piece = player.pieces.find(p => p.id === move.pieceId);
  if (!piece) return game;

  if (move.type === 'enter') {
    piece.pos = 0;
    const globalPos = START_POSITIONS[playerIdx];
    captureAt(game, playerIdx, globalPos);
  } else if (move.type === 'finish') {
    piece.pos = move.to;
    piece.finished = true;
    if (player.pieces.every(p => p.finished)) {
      player.finished = true;
      game.winners.push(playerIdx);
      if (game.winners.length >= game.numPlayers - 1) {
        game.gameOver = true;
      }
    }
  } else if (move.type === 'capture') {
    piece.pos = move.to;
    const globalPos = toGlobalPos(move.to, playerIdx);
    captureAt(game, playerIdx, globalPos);
    game.extraTurn = true;
  } else {
    piece.pos = move.to;
  }

  if (game.diceValue === 6) game.extraTurn = true;

  return game;
}

export function nextTurn(game) {
  if (game.extraTurn) {
    game.extraTurn = false;
    return;
  }
  do {
    game.currentPlayer = (game.currentPlayer + 1) % game.numPlayers;
  } while (game.players[game.currentPlayer].finished && !game.gameOver);
}

function toGlobalPos(localPos, playerIdx) {
  if (localPos >= BOARD_SIZE) return localPos;
  return (localPos + START_POSITIONS[playerIdx]) % BOARD_SIZE;
}

function checkCapture(game, playerIdx, globalPos) {
  if (SAFE_SQUARES.includes(globalPos)) return false;
  for (let i = 0; i < game.numPlayers; i++) {
    if (i === playerIdx) continue;
    for (const piece of game.players[i].pieces) {
      if (piece.pos === -1 || piece.finished) continue;
      const theirGlobal = toGlobalPos(piece.pos, i);
      if (theirGlobal === globalPos) return true;
    }
  }
  return false;
}

function captureAt(game, playerIdx, globalPos) {
  if (SAFE_SQUARES.includes(globalPos)) return;
  for (let i = 0; i < game.numPlayers; i++) {
    if (i === playerIdx) continue;
    for (const piece of game.players[i].pieces) {
      if (piece.pos === -1 || piece.finished) continue;
      const theirGlobal = toGlobalPos(piece.pos, i);
      if (theirGlobal === globalPos) {
        piece.pos = -1;
      }
    }
  }
}

export function getBotMove(game, playerIdx, dice) {
  const moves = getValidMoves(game, playerIdx, dice);
  if (moves.length === 0) return null;
  const captures = moves.filter(m => m.type === 'capture');
  if (captures.length > 0) return captures[0];
  const finishes = moves.filter(m => m.type === 'finish');
  if (finishes.length > 0) return finishes[0];
  const enters = moves.filter(m => m.type === 'enter');
  if (enters.length > 0) return enters[0];
  return moves[Math.floor(Math.random() * moves.length)];
}
