import { Player } from '../player.js';
import { CycleManager } from '../cycle.js';
import { ObjectManager } from '../objects.js';

export class Game extends Phaser.Scene {
    constructor() {
        super({ key: 'Game' });
        this.cycleManager = null;
        this.objectManager = null;
        this.mainLayer = null;
    }

    preload() {
        // Load player sprite
        this.load.spritesheet('player', 'assets/images/player.png', {
            frameWidth: 100, 
            frameHeight: 100 
        });

        // Load objects sprite
        this.load.spritesheet('objects', 'assets/images/objects.png', {
            frameWidth: 100, 
            frameHeight: 100 
        });
        
        // Load tilemap
        this.load.tilemapTiledJSON('game-map', 'assets/game-map.json');
        // Load tileset image
        this.load.image('terrain-tileset', 'assets/images/terrain.png');
    }

    create() {
        // Create tilemap
        const map = this.make.tilemap({ key: 'game-map' });
        
        // Add tileset to map
        const terrainTileset = map.addTilesetImage('terrain', 'terrain-tileset');
        
        // Create layer named "main"
        this.mainLayer = map.createLayer('main', terrainTileset, 0, 0)
            .setCollisionByProperty({ collides: true });

        // Set world bounds based on tilemap dimensions
        const worldWidth = map.widthInPixels;
        const worldHeight = map.heightInPixels;
        this.physics.world.setBounds(0, 0, worldWidth, worldHeight);

        // Initialize object manager
        this.objects = this.physics.add.group();
        this.objectManager = new ObjectManager(this);
        this.objectManager.init();

        // Create player at center of screen
        this.player = new Player(this, 1600, 3100);

        // Physics Collisions
        this.physics.add.collider(this.player, this.mainLayer);
        this.physics.add.collider(this.player, this.objects);

        // Make camera follow the player
        this.cameras.main.startFollow(this.player);
        this.cameras.main.setBounds(0, 0, worldWidth, worldHeight);

        // Initialize cycle manager
        this.cycleManager = new CycleManager(this);
        this.cycleManager.init();
    }

    update(time, delta) {
        // Update player
        if (this.player) {
            this.player.update();
        }

        // Update cycle manager
        if (this.cycleManager) {
            this.cycleManager.update(delta);
            
            // Apply tint to main layer when needed
            if (this.mainLayer && this.cycleManager.getCurrentCycle() !== 'day') {
                this.cycleManager.applyTint(this.mainLayer);
            }
        }

        // Update object manager
        if (this.objectManager) {
            this.objectManager.update(delta);
        }
    }
}