import { DungeonGenerator } from '../dungeon/DungeonGenerator.js';

/**
 * GameEngine for Manual Dungeon Construction with Player Movement
 */
export class GameEngine {
    constructor() {
        this.dungeon = new DungeonGenerator();
        this.player = null;
        this.selectedEntity = null;
        this.isRunning = false;

        // Callbacks
        this.onEntityUpdate = null;
        this.onEntityMove = null;
        this.onEntitySelect = null;
        this.onPathChange = null;
    }

    startMission(missionConfig) {

        this.dungeon.startDungeon(missionConfig);

        // Create player at center of first tile
        this.createPlayer(1.5, 2.5); // Center of 2x6 corridor

        this.isRunning = true;
    }

    createPlayer(x, y) {
        this.player = {
            id: 'p1',
            name: 'Barbarian',
            x: Math.floor(x),
            y: Math.floor(y),
            texturePath: '/assets/images/dungeon1/standees/barbaro.png'
        };

        if (this.onEntityUpdate) {
            this.onEntityUpdate(this.player);
        }


    }

    onCellClick(x, y) {
        // If no player selected, select player on click
        if (!this.selectedEntity && this.player && x === this.player.x && y === this.player.y) {
            this.selectedEntity = this.player;
            if (this.onEntitySelect) {
                this.onEntitySelect(this.player.id, true);
            }

            return;
        }

        // If player selected, move to clicked cell
        if (this.selectedEntity === this.player) {
            if (this.canMoveTo(x, y)) {
                this.movePlayer(x, y);
            } else {

            }
        }
    }

    canMoveTo(x, y) {
        // Check if cell is walkable (occupied by a tile)
        return this.dungeon.grid.isOccupied(x, y);
    }

    movePlayer(x, y) {
        // Simple direct movement (no pathfinding for now)
        const path = [{ x, y }];

        this.player.x = x;
        this.player.y = y;

        if (this.onEntityMove) {
            this.onEntityMove(this.player, path);
        }

        // Deselect after move
        this.selectedEntity = null;
        if (this.onEntitySelect) {
            this.onEntitySelect(this.player.id, false);
        }


    }

    isPlayerAdjacentToDoor(doorCells) {
        if (!this.player) return false;

        // doorCells should be an array of {x, y} objects
        // If it sends a single object, wrap it
        const cells = Array.isArray(doorCells) ? doorCells : [doorCells];

        for (const cell of cells) {
            const dx = Math.abs(this.player.x - cell.x);
            const dy = Math.abs(this.player.y - cell.y);

            // Adjacent means distance of 1 in one direction and 0 in the other
            if ((dx === 1 && dy === 0) || (dx === 0 && dy === 1)) {
                return true;
            }
        }
        return false;
    }

    update(time) {
        // Minimal update loop
    }
}
