import { WaveManager } from '../support/waveManager.js';
import { TowerManager } from '../support/towerManager.js';

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

        this.allowPan = true;
        this.level = 1;
        this.wave = 1;
        this.gold = 150;
    }

    init(data) {
        console.log('Selected level:', data.level);
        console.log('Player name:', data.playerName);
        this.level = data.level;
        this.playerName = data.playerName;
    }

    preload() {
        this.load.tilemapTiledJSON(`level${this.level}`, `assets/level${this.level}.json`);
        this.load.image('terrain', 'assets/terrain.png');
        this.load.spritesheet('ammo', 'assets/ammo.png', {
            frameWidth: 50,
            frameHeight: 50
        });
        this.load.spritesheet('basic-enemies', 'assets/basic-enemies.png', { 
            frameWidth: 50, 
            frameHeight: 50 
        });
        this.load.spritesheet('medium-enemies', 'assets/medium-enemies.png', { 
            frameWidth: 100, 
            frameHeight: 100 
        });
        this.load.spritesheet('advanced-enemies', 'assets/advanced-enemies.png', { 
            frameWidth: 150, 
            frameHeight: 150 
        });
        this.load.spritesheet('towers', 'assets/towers.png', {
            frameHeight: 150,
            frameWidth: 150
        });

        // Sound FX
        this.load.audio('rocket-launch', 'assets/sounds/rocket-launch.mp3');
        this.load.audio('rocket-explosion', 'assets/sounds/rocket-explosion.mp3');
        this.load.audio('cannon', 'assets/sounds/cannon.mp3');
        this.load.audio('flamethrower', 'assets/sounds/flamethrower.mp3');
        this.load.audio('gatling-gun', 'assets/sounds/gatling-gun.mp3');
        this.load.audio('interfaceOpen', 'assets/sounds/interfaceOpen.mp3');
        this.load.audio('nextWave', 'assets/sounds/nextWave.mp3');
        this.load.audio('towerPlace', 'assets/sounds/towerPlace.mp3');
        this.load.audio('coin', 'assets/sounds/coin.mp3');
        this.load.audio('coinWoosh', 'assets/sounds/coinWoosh.mp3');
        this.load.audio('portal', 'assets/sounds/portal.mp3');
        this.load.audio('laser', 'assets/sounds/laser.mp3');
        this.load.audio('upgrade', 'assets/sounds/upgrade.mp3');
        
        // Music
        this.load.audio('level-bg1', 'assets/music/level-bg1.mp3');
    }

    create() {
        this.levelMap = this.make.tilemap({ key: `level${this.level}` });
        const terrainTiles = this.levelMap.addTilesetImage('terrain', 'terrain');
        this.mainLayer = this.levelMap.createLayer('main', terrainTiles)
            .setCollisionByProperty({ collides: true });
        this.platformsLayer = this.levelMap.createLayer('platforms', terrainTiles);

        // Add camera zoom functionality
        this.cameras.main.setBounds(0, 0, this.mainLayer.width, this.mainLayer.height);
        this.addControls();

        this.waveManager = new WaveManager(this, this.level, this.wave);
        this.towerManager = new TowerManager(this);

        this.scene.launch('UIScene');
        this.UIScene = this.scene.get('UIScene');

        this.enemies = this.physics.add.group();
        this.towers = this.physics.add.group();

        // Fade in camera at the beginning of the scene
        this.cameras.main.fadeIn(1000, 0, 0, 0);

        this.bgMusic = this.sound.add('level-bg1', { volume: 1 });
        this.bgMusic.loop = true;
        this.bgMusic.play();

        this.physics.add.collider(this.enemies, this.mainLayer);
        this.physics.add.collider(this.enemies, this.platformsLayer);
        this.physics.add.collider(this.waveManager.core, this.enemies, (core, enemy) => {
            this.UIScene.interfaceManager.damageCore(enemy);
        });
    }

    gridToLocation(num, offset = 0) {
        return num * 200 + 100 + offset;
    }

    update(time, delta) {
        this.waveManager.update(time, delta);
        this.towerManager.update(time, delta);
    }

    gameOver() {
        console.log('GAME OVER');
    }

    addControls() {
        // this.input.on('wheel', (pointer, gameObjects, deltaX, deltaY) => {
        //     const zoomSpeed = 0.1;
        //     if (deltaY < 0) {
        //         // Zoom in
        //         this.cameras.main.zoom += zoomSpeed;
        //     } else if (deltaY > 0) {
        //         // Zoom out
        //         this.cameras.main.zoom -= zoomSpeed;
        //     }
            
        //     // Limit zoom range to prevent extreme zoom levels
        //     this.cameras.main.zoom = Phaser.Math.Clamp(this.cameras.main.zoom, 0.5, 2);
            
        //     // Zoom toward mouse position
        //     const worldPoint = this.input.activePointer.positionToCamera(this.cameras.main);
        //     this.cameras.main.centerOn(worldPoint.x, worldPoint.y);
        // });

        // Add camera panning functionality
        this.input.on('pointerdown', (pointer) => {
            if (pointer.button === 0 && this.allowPan === true) { // Left mouse button
                this.isPanning = true;
                this.panStartX = pointer.x;
                this.panStartY = pointer.y;
            }
        });

        this.input.on('pointermove', (pointer) => {
            if (this.isPanning && pointer.isDown) {
                const dx = pointer.x - this.panStartX;
                const dy = pointer.y - this.panStartY;
                
                // Pan the camera
                this.cameras.main.scrollX -= dx;
                this.cameras.main.scrollY -= dy;
                
                // Update start position for next move
                this.panStartX = pointer.x;
                this.panStartY = pointer.y;
            }
        });

        this.input.on('pointerup', (pointer) => {
            if (pointer.button === 0) { // Left mouse button
                this.isPanning = false;
            }
        });
    }
}