export default class GameManager extends Phaser.Scene {
    constructor() {
        super({ key: 'GameManager' });
    }

    init(data) {
        this.config = data.config;
        this.level = data.level || 1;
        this.lives = data.lives ?? this.config.lives ?? 3;
        this.queue = [];
        this.queueIndex = 0;
    }

    create() {
        this.announceTween = null;
        this.announceTimer = null;
        this.resultHandled = false;

        // Remove any stale listener from a previous session before adding a fresh one
        this.game.events.off('miniGameResult', this._onResult, this);
        this.game.events.on('miniGameResult', this._onResult, this);

        this._buildQueue();
        this._showAnnouncement();
    }

    shutdown() {
        this.game.events.off('miniGameResult', this._onResult, this);
    }

    _buildQueue() {
        const pool = [...this.config.gamePool];
        const count = this.config.levels[String(this.level)]?.gameCount ?? 3;
        Phaser.Utils.Array.Shuffle(pool);
        this.queue = pool.slice(0, count);
        this.queueIndex = 0;
    }

    _showAnnouncement() {
        // Clean up any in-flight tween/timer from a previous announcement
        if (this.announceTween) { this.announceTween.remove(); this.announceTween = null; }
        if (this.announceTimer) { this.announceTimer.remove(); this.announceTimer = null; }

        this.cameras.main.setBackgroundColor('#000000');

        if (this.announcementGroup) this.announcementGroup.destroy(true);
        this.announcementGroup = this.add.group();

        const cx = 800, cy = 450;
        const gameNum = this.queueIndex + 1;
        const total = this.queue.length;
        const gameName = this._displayName(this.queue[this.queueIndex]);

        const levelText = this.add.text(cx, 320, `LEVEL ${this.level}  —  GAME ${gameNum} OF ${total}`, {
            fontSize: '32px', fontFamily: 'monospace', color: '#888888',
        }).setOrigin(0.5);

        const nameText = this.add.text(cx, 420, gameName, {
            fontSize: '72px', fontFamily: 'monospace', color: '#00ff00',
            stroke: '#005500', strokeThickness: 4,
        }).setOrigin(0.5);

        const livesText = this.add.text(cx, 530, '♥ '.repeat(this.lives).trim(), {
            fontSize: '40px', fontFamily: 'monospace', color: '#ff4444',
        }).setOrigin(0.5);

        const goText = this.add.text(cx, 640, 'GET READY!', {
            fontSize: '48px', fontFamily: 'monospace', color: '#ffff00',
        }).setOrigin(0.5).setAlpha(0);

        this.announcementGroup.addMultiple([levelText, nameText, livesText, goText]);

        this.announceTween = this.tweens.add({
            targets: goText,
            alpha: 1,
            duration: 400,
            delay: 800,
            onComplete: () => {
                this.announceTimer = this.time.delayedCall(1000, () => this._launchCurrent());
            },
        });
    }

    _launchCurrent() {
        this.announceTween = null;
        this.announceTimer = null;
        if (this.announcementGroup) {
            this.announcementGroup.destroy(true);
            this.announcementGroup = null;
        }
        this.cameras.main.setBackgroundColor('#000000');

        this.resultHandled = false;  // ready to accept exactly one result per launch
        const key = this.queue[this.queueIndex];
        this.scene.launch(key, { lives: this.lives, level: this.level });
        this.scene.bringToTop(key);
    }

    _onResult({ success }) {
        if (this.resultHandled) return;  // guard against duplicate events
        this.resultHandled = true;

        const key = this.queue[this.queueIndex];
        if (this.scene.isActive(key)) {
            this.scene.stop(key);
        }

        if (!success) {
            this.lives -= 1;
            if (this.lives <= 0) {
                this.scene.start('GameOver', { level: this.level });
                return;
            }
            // Retry same mini-game
            this._showAnnouncement();
            return;
        }

        this.queueIndex += 1;
        if (this.queueIndex >= this.queue.length) {
            // All games in this level done
            const nextLevel = this.level + 1;
            const hasNext = !!this.config.levels[String(nextLevel)];
            this.scene.start('LevelComplete', {
                config: this.config,
                level: this.level,
                lives: this.lives,
                hasNextLevel: hasNext,
            });
            return;
        }

        this._showAnnouncement();
    }

    _displayName(key) {
        const names = {
            ColoradoDefense: 'COLORADO DEFENSE',
            CodeBugInvaders: 'CODE BUG INVADERS',
            DotDude: 'DOT DUDE',
            SmashOut: 'SMASH OUT',
            Vortex: 'VORTEX',
        };
        return names[key] || key;
    }
}
