import { playMusic, stopMusic } from '../../audio.js';

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

    preload() {
        this.load.json('cdConfig', 'src/games/colorado-defense/config.json');
        this.load.json('cdCities', 'src/games/colorado-defense/cities.json');
        this.load.audio('cdMusic', 'assets/music/01-colorado-defense.mp3');
        this.load.audio('cdComplete', 'assets/fx/complete.mp3');
        this.load.audio('cdShoot', 'assets/fx/shoot.mp3');
        this.load.audio('cdFireball', 'assets/fx/fireball.mp3');
        this.load.audio('cdDestroy', 'assets/fx/destroy.mp3');
    }

    init(data) {
        this.globalLives = data.lives;
        this.level = data.level || 1;
        this.gameActive = false;
    }

    create() {
        const all = this.cache.json.get('cdConfig');
        const lvl = String(this.level);
        this.cfg = all.levels ? (all.levels[lvl] ?? all.levels['1']) : all;
        this.cities = [];
        this.missiles = [];
        this.interceptors = [];
        this.explosions = [];
        this.wave = 0;
        this.wavesCleared = 0;
        this.spawnTimer = 0;
        this.waveSpawned = 0;
        this.waveCleared = false;
        this.gameActive = true;
        this.mouseX = 800;
        this.mouseY = 400;

        playMusic(this, 'cdMusic');

        this._buildBackground();
        this._buildCities();
        this._assignCityNames();
        this._buildCityLabels();
        this.mainGfx = this.add.graphics();
        this._buildHUD();
        this._setupInput();
        this._nextWave();
    }

    shutdown() {
        stopMusic(this);
        this.interceptors.forEach(i => { if (i.sound) { i.sound.stop(); i.sound.destroy(); } });
        this.input.off('pointerdown');
        this.input.off('pointermove');
    }

    _buildBackground() {
        const bg = this.add.graphics();
        // Starfield
        for (let i = 0; i < 120; i++) {
            const alpha = Math.random() * 0.6 + 0.1;
            bg.fillStyle(0xffffff, alpha);
            bg.fillRect(Phaser.Math.Between(0, 1599), Phaser.Math.Between(0, 860), 2, 2);
        }
        // Ground
        bg.fillStyle(0x003300);
        bg.fillRect(0, 865, 1600, 35);
        bg.lineStyle(2, 0x00bb00);
        bg.lineBetween(0, 865, 1600, 865);
        // Title banner
        this.add.text(800, 15, 'COLORADO DEFENSE', {
            fontSize: '20px', fontFamily: 'monospace', color: '#00ff00', alpha: 0.7,
        }).setOrigin(0.5, 0);
    }

    _buildCities() {
        const xs = [110, 300, 490, 1110, 1300, 1490];
        xs.forEach((x, i) => {
            this.cities.push({ x, y: 865, alive: true, index: i });
        });
    }

    _assignCityNames() {
        const pool = [...this.cache.json.get('cdCities')];
        Phaser.Utils.Array.Shuffle(pool);
        this.cities.forEach((c, i) => { c.name = pool[i]; });
    }

    _buildCityLabels() {
        this.cities.forEach(c => {
            c.label = this.add.text(c.x, 871, c.name, {
                fontSize: '12px', fontFamily: 'monospace', color: '#aaffaa',
            }).setOrigin(0.5, 0).setDepth(5);
        });
    }

    _buildHUD() {
        this.waveText = this.add.text(20, 40, 'WAVE 1', {
            fontSize: '24px', fontFamily: 'monospace', color: '#00ff00',
        });
        this.livesText = this.add.text(800, 40, '♥ '.repeat(this.globalLives).trim(), {
            fontSize: '24px', fontFamily: 'monospace', color: '#ff4444',
        }).setOrigin(0.5, 0);
        this.statusText = this.add.text(1580, 40, `CITIES: 6/6\nWAVES: 0/${this.cfg.wavesToPass}`, {
            fontSize: '22px', fontFamily: 'monospace', color: '#4488ff',
        }).setOrigin(1, 0);
    }

    _setupInput() {
        this.input.on('pointermove', p => { this.mouseX = p.x; this.mouseY = p.y; });
        this.input.on('pointerdown', p => this._fire(p.x, p.y));
        this.keyA = this.input.keyboard.addKey('A');
        this.keyAPressed = false;
    }

    _nextWave() {
        this.wave++;
        if (this.wave > this.cfg.waves.length) {
            this._endGame(true);
            return;
        }
        this.currentWave = this.cfg.waves[this.wave - 1];
        this.waveSpawned = 0;
        this.waveCleared = false;
        this.spawnTimer = 800; // small delay before first spawn
        this.waveText.setText(`WAVE ${this.wave}`);

        const waveLabel = this.add.text(800, 450, `WAVE ${this.wave}`, {
            fontSize: '72px', fontFamily: 'monospace', color: '#ffff00',
            stroke: '#885500', strokeThickness: 4,
        }).setOrigin(0.5).setDepth(10);
        this.time.delayedCall(1200, () => waveLabel.destroy());
    }

    _fire(tx, ty) {
        if (!this.gameActive || ty >= 855) return;
        const sound = this.sound.add('cdShoot', { volume: 0.5, loop: true });
        sound.play();
        this.interceptors.push({
            sx: 800, sy: 855,
            tx, ty,
            dx: tx - 800, dy: ty - 855,
            dist: Math.max(1, Math.hypot(tx - 800, ty - 855)),
            progress: 0,
            speed: this.cfg.interceptorSpeed,
            sound,
        });
    }

    update(time, delta) {
        if (!this.gameActive) return;
        const dt = delta / 1000;

        if (this.keyA.isDown && !this.keyAPressed) {
            this.keyAPressed = true;
            this._fire(this.mouseX, this.mouseY);
        }
        if (!this.keyA.isDown) this.keyAPressed = false;

        // Spawn enemy missiles
        if (this.waveSpawned < this.currentWave.count) {
            this.spawnTimer -= delta;
            if (this.spawnTimer <= 0) {
                this._spawnMissile();
                this.waveSpawned++;
                this.spawnTimer = this.currentWave.spawnInterval;
            }
        }

        // Move interceptors
        this.interceptors = this.interceptors.filter(i => {
            i.progress += (i.speed / i.dist) * dt;
            i.x = i.sx + i.dx * i.progress;
            i.y = i.sy + i.dy * i.progress;
            if (i.progress >= 1) {
                i.sound.stop();
                i.sound.destroy();
                const boom = this.sound.add('cdFireball', { volume: 0.7 });
                boom.once('complete', () => boom.destroy());
                boom.play();
                this.explosions.push({
                    x: i.tx, y: i.ty, r: 0,
                    maxR: this.cfg.explosionRadius,
                    growing: true,
                });
                return false;
            }
            return true;
        });

        // Move enemy missiles
        this.missiles = this.missiles.filter(m => {
            if (m.dead) return false;
            m.progress += (m.speed / m.dist) * dt;
            m.x = m.sx + m.dx * m.progress;
            m.y = m.sy + m.dy * m.progress;
            if (m.y >= 865) {
                this._cityHit(m.x);
                return false;
            }
            return true;
        });

        // Update explosions + kill missiles inside
        this.explosions = this.explosions.filter(e => {
            if (e.growing) {
                e.r += e.maxR * 2.8 * dt;
                if (e.r >= e.maxR) e.growing = false;
            } else {
                e.r -= e.maxR * 2.2 * dt;
            }
            this.missiles.forEach(m => {
                if (!m.dead && Math.hypot(m.x - e.x, m.y - e.y) < e.r) m.dead = true;
            });
            return e.r > 0;
        });

        // Check wave clear
        if (!this.waveCleared &&
            this.waveSpawned >= this.currentWave.count &&
            this.missiles.length === 0 &&
            this.interceptors.length === 0) {
            this.waveCleared = true;
            this.wavesCleared++;
            if (this.wavesCleared >= this.cfg.wavesToPass) {
                this.time.delayedCall(1800, () => this._endGame(true));
            } else {
                this.time.delayedCall(1800, () => this._nextWave());
            }
        }

        // Check city deaths
        const dead = this.cities.filter(c => !c.alive).length;
        if (dead >= this.cfg.maxCityDeaths) this._endGame(false);

        this.statusText.setText(`CITIES: ${6 - dead}/6\nWAVES: ${this.wavesCleared}/${this.cfg.wavesToPass}`);
        this._draw();
    }

    _spawnMissile() {
        const target = this._pickTarget();
        const sx = Phaser.Math.Between(80, 1520);
        const sy = -10;
        const dist = Math.max(1, Math.hypot(target.x - sx, target.y - sy));
        this.missiles.push({
            sx, sy, dx: target.x - sx, dy: target.y - sy,
            dist, speed: this.currentWave.speed,
            progress: 0, x: sx, y: sy, dead: false,
        });
    }

    _pickTarget() {
        const alive = this.cities.filter(c => c.alive);
        if (alive.length > 0 && Math.random() < 0.65) {
            return Phaser.Utils.Array.GetRandom(alive);
        }
        return { x: Phaser.Math.Between(100, 1500), y: 865 };
    }

    _cityHit(mx) {
        for (const c of this.cities) {
            if (c.alive && Math.abs(c.x - mx) < 70) {
                c.alive = false;
                if (c.label) c.label.setColor('#664422');
                this.explosions.push({ x: c.x, y: c.y - 15, r: 5, maxR: 50, growing: true });
                const snd = this.sound.add('cdDestroy', { volume: 0.8 });
                snd.once('complete', () => snd.destroy());
                snd.play();
                break;
            }
        }
    }

    _endGame(success) {
        if (!this.gameActive) return;
        this.gameActive = false;
        if (success) {
            const snd = this.sound.add('cdComplete', { volume: 0.8 });
            snd.once('complete', () => snd.destroy());
            snd.play();
        }
        const msg = success ? 'COLORADO DEFENDED!' : 'CITIES DESTROYED!';
        const color = success ? '#00ff00' : '#ff2200';
        this.add.text(800, 440, msg, {
            fontSize: '64px', fontFamily: 'monospace',
            color, stroke: '#000000', strokeThickness: 5,
        }).setOrigin(0.5).setDepth(20);
        this.time.delayedCall(2200, () => {
            this.game.events.emit('miniGameResult', { success });
        });
    }

    _draw() {
        const g = this.mainGfx;
        g.clear();

        // Turret
        g.fillStyle(0x00ff00);
        g.fillTriangle(785, 865, 815, 865, 800, 840);
        g.fillStyle(0x00aa00);
        g.fillRect(794, 850, 12, 15);

        // Crosshair
        g.lineStyle(1, 0x00ff00, 0.6);
        g.strokeCircle(this.mouseX, this.mouseY, 16);
        g.lineBetween(this.mouseX - 22, this.mouseY, this.mouseX + 22, this.mouseY);
        g.lineBetween(this.mouseX, this.mouseY - 22, this.mouseX, this.mouseY + 22);

        // Cities
        this.cities.forEach(c => {
            if (c.alive) {
                g.fillStyle(0x0055ff);
                g.fillRect(c.x - 30, c.y - 30, 60, 30);
                g.fillStyle(0x3388ff);
                g.fillRect(c.x - 22, c.y - 50, 14, 22);
                g.fillRect(c.x + 6, c.y - 44, 12, 16);
                g.fillRect(c.x - 5, c.y - 56, 10, 8);
            } else {
                g.fillStyle(0x553311);
                g.fillRect(c.x - 30, c.y - 8, 60, 8);
                g.fillStyle(0x884422);
                for (let i = 0; i < 4; i++) {
                    g.fillRect(c.x - 25 + i * 14, c.y - 16, 10, 10);
                }
            }
        });

        // Enemy missiles
        this.missiles.forEach(m => {
            if (m.dead) return;
            g.lineStyle(2, 0xff4400, 0.9);
            g.lineBetween(m.sx, m.sy, m.x, m.y);
            g.fillStyle(0xff6600);
            g.fillCircle(m.x, m.y, 5);
        });

        // Interceptors
        this.interceptors.forEach(i => {
            g.lineStyle(2, 0x00ffff, 0.9);
            g.lineBetween(800, 855, i.x, i.y);
            g.fillStyle(0xffffff);
            g.fillCircle(i.x, i.y, 4);
        });

        // Explosions
        this.explosions.forEach(e => {
            const alpha = e.growing ? 0.9 : e.r / e.maxR * 0.9;
            g.lineStyle(3, 0xffff00, alpha);
            g.strokeCircle(e.x, e.y, e.r);
            g.lineStyle(2, 0xff8800, alpha * 0.7);
            g.strokeCircle(e.x, e.y, e.r * 0.65);
        });
    }
}
