// Material counting and advantage display

const PIECE_VALUES = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };

export function countMaterial(fen) {
  const board = fen.split(' ')[0];
  let white = 0, black = 0;
  const whitePieces = { p: 0, n: 0, b: 0, r: 0, q: 0 };
  const blackPieces = { p: 0, n: 0, b: 0, r: 0, q: 0 };

  for (const ch of board) {
    if (ch >= 'A' && ch <= 'Z') {
      const piece = ch.toLowerCase();
      if (PIECE_VALUES[piece] !== undefined) {
        white += PIECE_VALUES[piece];
        whitePieces[piece]++;
      }
    } else if (ch >= 'a' && ch <= 'z') {
      if (PIECE_VALUES[ch] !== undefined) {
        black += PIECE_VALUES[ch];
        blackPieces[ch]++;
      }
    }
  }

  return { white, black, diff: white - black, whitePieces, blackPieces };
}

export function getMaterialAdvantage(fen, playerColor) {
  const { diff } = countMaterial(fen);
  const advantage = playerColor === 'w' ? diff : -diff;
  return advantage;
}

export function formatAdvantage(advantage) {
  if (advantage === 0) return '';
  return advantage > 0 ? `+${advantage}` : `${advantage}`;
}

export function getCapturedPieces(startFen, currentFen) {
  const start = countMaterial(startFen || 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1');
  const current = countMaterial(currentFen);

  const whiteCaptured = []; // pieces white lost (black captured)
  const blackCaptured = []; // pieces black lost (white captured)

  const pieceOrder = ['q', 'r', 'b', 'n', 'p'];
  for (const p of pieceOrder) {
    const wLost = start.whitePieces[p] - current.whitePieces[p];
    const bLost = start.blackPieces[p] - current.blackPieces[p];
    for (let i = 0; i < wLost; i++) whiteCaptured.push(p);
    for (let i = 0; i < bLost; i++) blackCaptured.push(p);
  }

  return { whiteCaptured, blackCaptured };
}
