import { GomokuGame } from '../game/game-instance';

export function renderGameBoardHtml(
  game: GomokuGame,
  isPlayerToPlay: boolean,
): string {
  // Check the last move, so that the stone can be highlighted
  const lastMove = game.history[game.history.length - 1];

  let boardHtml = '<div id="game-board" class="game-board-grid">';
  for (let row = 0; row < game.board.length; row++) {
    for (let col = 0; col < game.board[row].length; col++) {
      const stone = game.board[row][col];
      const intersectionId = `intersection-${row}-${col}`;
      let stoneHtml = '';
      if (stone) {
        const colorClass =
          stone === 'black' ? 'stone-black-heart' : 'stone-white-heart';
        const lastMoveClass =
          col == lastMove.col && row == lastMove.row ? 'last-move' : '';
        stoneHtml = `<div class="${colorClass} ${lastMoveClass}"></div>`;
      }

      // Calculate top and left for absolute positioning, offset by half the intersection div size
      const top = row * 7.142857142857142;
      const left = col * 7.142857142857142;

      // HTMX attributes for making a move
      const wsAttrs = isPlayerToPlay && !stone ? `ws-send="click"` : '';

      boardHtml += `
                <div 
                    id="${intersectionId}" 
                    class="intersection" 
                    data-row="${row}" 
                    data-col="${col}"
                    style="top: ${top}%; left: ${left}%;"
                    ${wsAttrs}
                >
                    ${stoneHtml}
                </div>`;
    }
  }
  boardHtml += `</div>`;
  return boardHtml;
}
