export const PHASES = {
    POWER: 'POWER',         // Roll for events
    HERO: 'HERO',           // Player actions
    EXPLORATION: 'EXPLORATION', // Room reveal
    MONSTER: 'MONSTER',     // AI actions
    END: 'END'              // Cleanup
};

class TurnManager extends EventTarget {
    constructor() {
        super();
        this.currentTurn = 1;
        this.currentPhase = PHASES.POWER;
        this.isCombat = false;
    }

    startTurn() {
        this.currentPhase = PHASES.POWER;
        this.dispatchEvent(new CustomEvent('phaseChange', { detail: this.currentPhase }));
        console.log(`--- TURN ${this.currentTurn} START ---`);

        // Simulating Power Phase trigger
        this.processPowerPhase();
    }

    processPowerPhase() {
        // Winds of Magic Roll (1d6)
        const roll = Math.floor(Math.random() * 6) + 1;
        console.log(`Winds of Magic Roll: ${roll}`);

        let message = `Vientos de Magia: ${roll}`;
        this.dispatchEvent(new CustomEvent('message', { detail: message }));

        if (roll === 1) {
            console.log("EVENTO INESPERADO!");
            this.dispatchEvent(new CustomEvent('eventTriggered', {
                detail: {
                    source: 'POWER_PHASE',
                    event: { title: 'Evento Inesperado', description: 'Algo se mueve en la oscuridad...', type: 'MISTERIO' }
                }
            }));
            // In a real game, we'd draw from a specific Event Deck here
        } else {
            console.log("¡Poder obtenido!");
        }

        // Auto-advance to Hero Phase after a brief pause to show the roll
        setTimeout(() => this.setPhase(PHASES.HERO), 2000);
    }

    setPhase(phase) {
        this.currentPhase = phase;
        this.dispatchEvent(new CustomEvent('phaseChange', { detail: this.currentPhase }));
        console.log(`Phase changed to: ${phase}`);

        if (phase === PHASES.END) {
            this.endTurn();
        }
    }

    endTurn() {
        console.log(`--- TURN ${this.currentTurn} END ---`);
        this.currentTurn++;
        this.startTurn();
    }
}

export const turnManager = new TurnManager();
