/**
 * King.js - King piece implementation
 * Handles one-square movement and castling
 */

import { Piece } from './Piece.js';

export class King extends Piece {
    constructor(color, position) {
        super(color, position);
        this.type = 'king';
    }

    /**
     * Get valid moves for king
     * King moves one square in any direction
     * @param {Board} board - Game board
     * @returns {Position[]} Array of valid positions
     */
    getValidMoves(board) {
        const moves = [];

        // All 8 directions, but only one square
        const directions = [
            [-1, -1], [-1, 0], [-1, 1],
            [0, -1],           [0, 1],
            [1, -1],  [1, 0],  [1, 1]
        ];

        for (const [dRow, dCol] of directions) {
            const targetRow = this.position.row + dRow;
            const targetCol = this.position.col + dCol;

            if (!this.isInBounds(targetRow, targetCol)) {
                continue;
            }

            const targetPiece = board.getPiece(targetRow, targetCol);

            // Can move to empty square or capture opponent piece
            if (!targetPiece || targetPiece.color !== this.color) {
                moves.push({ row: targetRow, col: targetCol });
            }
        }

        // Castling is handled in SpecialMoves.js

        return moves;
    }

    /**
     * Get castling move positions
     * @param {Board} board - Game board
     * @param {GameState} gameState - Game state
     * @returns {Position[]} Castling target positions
     */
    getCastlingMoves(board, gameState) {
        const moves = [];

        // Can't castle if king has moved
        if (this.hasMoved) {
            return moves;
        }

        const row = this.position.row;

        // Kingside castling (king to g-file)
        const kingsideRook = board.getPiece(row, 7);
        if (kingsideRook &&
            kingsideRook.type === 'rook' &&
            kingsideRook.color === this.color &&
            !kingsideRook.hasMoved) {

            // Check if squares between king and rook are empty
            if (this.isEmpty(board, row, 5) &&
                this.isEmpty(board, row, 6)) {
                moves.push({ row, col: 6 }); // King moves to g-file
            }
        }

        // Queenside castling (king to c-file)
        const queensideRook = board.getPiece(row, 0);
        if (queensideRook &&
            queensideRook.type === 'rook' &&
            queensideRook.color === this.color &&
            !queensideRook.hasMoved) {

            // Check if squares between king and rook are empty
            if (this.isEmpty(board, row, 1) &&
                this.isEmpty(board, row, 2) &&
                this.isEmpty(board, row, 3)) {
                moves.push({ row, col: 2 }); // King moves to c-file
            }
        }

        // Additional validation (not in check, doesn't pass through check)
        // is handled in MoveValidator.js

        return moves;
    }
}
