
import { GameEngine } from './engine/game/GameEngine.js';
import { GameRenderer } from './view/GameRenderer.js';
import { CameraManager } from './view/CameraManager.js';
import { UIManager } from './view/UIManager.js';
import { DoorModal } from './view/DoorModal.js';
import { MissionConfig, MISSION_TYPES } from './engine/dungeon/MissionConfig.js';

console.log("Initializing Warhammer Quest Engine... SYSTEM: MANUAL_PLACEMENT_V2");
window.TEXTURE_DEBUG = true;

// 1. Setup Mission
const mission = new MissionConfig({
    id: 'mission_1',
    name: 'The First Dive',
    type: MISSION_TYPES.ESCAPE,
    minTiles: 6
});

// 2. Initialize Core Systems
const renderer = new GameRenderer('app');
const cameraManager = new CameraManager(renderer);
const game = new GameEngine();

// 3. Initialize UI
const ui = new UIManager(cameraManager, game);
const doorModal = new DoorModal();

// Global Access for Debugging
window.GAME = game;
window.RENDERER = renderer;

// 4. Bridge Logic & View
const generator = game.dungeon;
const originalPlaceTile = generator.grid.placeTile.bind(generator.grid);

// Override placeTile to trigger rendering
generator.grid.placeTile = (instance, variant, def) => {
    originalPlaceTile(instance, variant);

    const cells = generator.grid.calculateCells(variant, instance.x, instance.y);
    renderer.addTile(cells, def.type, def, instance);

    // Update exits visualization
    setTimeout(() => {
        renderer.renderExits(generator.availableExits);
    }, 50);
};

// 5. Connect Generator State Changes to UI
generator.onStateChange = (state) => {
    console.log(`[Main] Generator state: ${state}`);

    if (state === 'PLACING_TILE') {
        ui.showPlacementControls(true);
    } else {
        ui.showPlacementControls(false);
    }

    if (state === 'WAITING_DOOR') {
        // Enable door selection mode
        renderer.enableDoorSelection(true);
    } else {
        renderer.enableDoorSelection(false);
    }
};

// 6. Connect Placement Updates to Renderer
generator.onPlacementUpdate = (preview) => {
    if (preview) {
        renderer.showPlacementPreview(preview);
        ui.updatePlacementStatus(preview.isValid);
    } else {
        renderer.hidePlacementPreview();
    }
};

// 7. Handle Door Selection
renderer.onDoorSelected = (exitPoint) => {
    console.log('[Main] Door selected:', exitPoint);
    generator.selectDoor(exitPoint);
};

// 8. Bridge Game Interactions (Player movement, etc.)
game.onEntityUpdate = (entity) => {
    renderer.addEntity(entity);
    renderer.updateEntityPosition(entity);

    if (entity.id === 'p1' && !entity._centered) {
        cameraManager.centerOn(entity.x, entity.y);
        entity._centered = true;
    }
};

game.onEntityMove = (entity, path) => {
    renderer.moveEntityAlongPath(entity, path);
};

game.onEntitySelect = (entityId, isSelected) => {
    renderer.toggleEntitySelection(entityId, isSelected);
};

renderer.onHeroFinishedMove = (x, y) => {
    cameraManager.centerOn(x, y);
};

game.onPathChange = (path) => {
    renderer.highlightCells(path);
};

// 9. Custom click handler
const handleCellClick = async (x, y, doorMesh) => {
    // PRIORITY 1: Check if we're in door selection mode (dungeon building)
    if (generator.state === 'WAITING_DOOR') {
        if (doorMesh && doorMesh.userData.isExit) {
            // This is an exit door that can be selected for expansion
            const exitData = doorMesh.userData.exitData;
            if (exitData) {
                console.log('[Main] Door selected for expansion:', exitData);
                generator.selectDoor(exitData);
            }
            return; // Don't process any other click logic
        }
        // If not clicking on a door in WAITING_DOOR mode, ignore the click
        console.log('[Main] Click ignored - waiting for door selection');
        return;
    }

    // PRIORITY 2: Normal door interaction (during gameplay with player)
    if (doorMesh && doorMesh.userData.isDoor && !doorMesh.userData.isOpen) {
        const player = game.player;
        if (!player) {
            console.log('[Main] Player not found');
            return;
        }

        if (renderer.isPlayerAdjacentToDoor(player.x, player.y, doorMesh)) {
            const confirmed = await doorModal.show('¿Quieres abrir la puerta?');

            if (confirmed) {
                renderer.openDoor(doorMesh);
                const exitCell = doorMesh.userData.cells[0];
                console.log('[Main] Opening door at exit:', exitCell);
                game.exploreExit(exitCell);
            }
        } else {
            console.log('[Main] Player is not adjacent to the door. Move closer first.');
        }
    } else if (x !== null && y !== null) {
        game.onCellClick(x, y);
    }
};

renderer.setupInteraction(
    () => cameraManager.getCamera(),
    handleCellClick,
    (x, y) => game.onCellRightClick(x, y)
);

console.log("--- Starting Game Session ---");
game.startMission(mission);

// 10. Render Loop
const animate = (time) => {
    requestAnimationFrame(animate);

    game.update(time);
    cameraManager.update(time);
    renderer.updateAnimations(time);
    renderer.render(cameraManager.getCamera());
};
animate(0);
