// Doubling Cube logic for Backgammon match play
import { WHITE, BLACK } from './rules.js';

export function createCube() {
  return {
    value: 1,
    owner: null, // null = center (either can double), WHITE or BLACK = only that player can
    offered: false,
    offeredBy: null
  };
}

export function canDouble(cube, playerType) {
  if (cube.offered) return false;
  if (cube.owner === null) return true;
  return cube.owner === playerType;
}

export function offerDouble(cube, playerType) {
  if (!canDouble(cube, playerType)) return false;
  cube.offered = true;
  cube.offeredBy = playerType;
  return true;
}

export function acceptDouble(cube) {
  if (!cube.offered) return false;
  cube.value *= 2;
  cube.owner = cube.offeredBy === WHITE ? BLACK : WHITE;
  cube.offered = false;
  cube.offeredBy = null;
  return true;
}

export function declineDouble(cube) {
  if (!cube.offered) return false;
  cube.offered = false;
  const decliner = cube.offeredBy === WHITE ? BLACK : WHITE;
  cube.offeredBy = null;
  return decliner; // returns who declined (and thus loses)
}

export function getStake(cube, gameScore) {
  return cube.value * gameScore;
}

// Bot doubling decision based on pip count advantage
export function shouldBotDouble(cube, myPips, oppPips, difficulty) {
  if (!canDouble(cube, BLACK)) return false;

  const advantage = (oppPips - myPips) / oppPips;

  if (difficulty === 'easy') return false;
  if (difficulty === 'medium') return advantage > 0.25;
  return advantage > 0.15; // hard bot doubles more aggressively
}

export function shouldBotAccept(cube, myPips, oppPips, difficulty) {
  const disadvantage = (myPips - oppPips) / myPips;

  if (difficulty === 'easy') return true; // easy bot always accepts
  if (difficulty === 'medium') return disadvantage < 0.35;
  return disadvantage < 0.25; // hard bot drops when too far behind
}
