// Pre-move system for bullet/blitz chess
// Allows queuing a move during opponent's turn — executes instantly when it's your turn

let premove = null;
let onPremoveExecuted = null;

export function set(from, to, promotion) {
  premove = { from, to, promotion };
}

export function get() {
  return premove;
}

export function clear() {
  premove = null;
}

export function hasPremove() {
  return premove !== null;
}

export function tryExecute(engine, playerColor) {
  if (!premove) return null;
  if (engine.turn() !== playerColor) return null;

  const { from, to, promotion } = premove;
  premove = null;

  // Verify the premove is still legal in the current position
  const legalMoves = engine.legalMoves(from);
  const isLegal = legalMoves.some(m => m.from === from && m.to === to);

  if (isLegal) {
    const m = engine.move(from, to, promotion);
    return m;
  }

  return null; // Premove was illegal in current position — discard silently
}

export function setCallback(fn) {
  onPremoveExecuted = fn;
}

export function isPremoveSquare(square) {
  if (!premove) return false;
  return square === premove.from || square === premove.to;
}
