export class ObjectManager {
    constructor(scene) {
        this.scene = scene;
        this.objects = [];
        this.healthBars = new Map(); // Store references to health bars for cleanup
    }

    init() {
        // Parse main layer for object properties and create objects
        this.parseLayerForObjects();
    }

    parseLayerForObjects() {
        const map = this.scene.mainLayer.tilemap;
        const layerData = this.scene.mainLayer.layer;

        // Iterate through all tiles in the layer
        for (let y = 0; y < layerData.height; y++) {
            for (let x = 0; x < layerData.width; x++) {
                const tile = this.scene.mainLayer.getTileAt(x, y);
                
                if (tile && tile.properties) {
                    // Check for object-related properties
                    this.createObjectFromTile(tile, x*100+50, y*100+50);
                }
            }
        }
    }

    createObjectFromTile(tile, x, y) {
        // Example: Look for a "type" property to determine what object to create
        const objectType = tile.properties;

        Object.keys(objectType).forEach(key => {
            if (key === 'palmTree' && Phaser.Math.Between(1,300) <= objectType[key]) {
                const palmTree = this.scene.physics.add.sprite(x, y, 'objects', 0);
                this.scene.objects.add(palmTree);
                palmTree.setImmovable(true).setSize(60,100);
                palmTree.props = {
                    type: 'palmTree',
                    health: 100,
                    fullHealth: 100,
                    yield: 'wood',
                    amount: [0,1],
                    doneSprite: 10
                };
                this.createHealthBar(palmTree);
            } else if (key === 'forestTree' && Phaser.Math.Between(1,300) <= objectType[key]) {
                const forestRand = Phaser.Math.Between(1,4);
                const forestTree = this.scene.physics.add.sprite(x, y, 'objects', forestRand);
                this.scene.objects.add(forestTree);
                forestTree.setImmovable(true).setSize(50,100);
                forestTree.props = {
                    type: 'forestTree',
                    health: 200,
                    fullHealth: 200,
                    yield: 'wood',
                    amount: [0,3],
                    doneSprite: 11
                };
                this.createHealthBar(forestTree);
            } else if (key === 'boulder' && Phaser.Math.Between(1,300) <= objectType[key]) {
                const boulder = this.scene.physics.add.sprite(x, y, 'objects', 20);
                this.scene.objects.add(boulder);
                boulder.setImmovable(true);
                boulder.props = {
                    type: 'boulder',
                    health: 200,
                    fullHealth: 200,
                    yield: 'rock',
                    amount: [1,3],
                    doneSprite: null
                };
                this.createHealthBar(boulder);
            } else if (key === 'seaShell' && Phaser.Math.Between(1,300) <= objectType[key]) {
                const item = this.scene.physics.add.sprite(x, y, 'objects', 5);
                this.scene.objects.add(item);
                item.setImmovable(true);
                item.props = {
                    type: key,
                    health: 1,
                    fullHealth: 1,
                    yield: 'seaShell',
                    amount: [1,1],
                    doneSprite: null
                };
                this.createHealthBar(item);
            }
        });
        
    }

    createHealthBar(object) {
        // Create a graphics object for the health bar
        const healthBar = this.scene.add.graphics();
        
        // Position the health bar above the object (adjust offset as needed)
        const offsetX = 0;
        const offsetY = -50; // Adjust to position above the object
        
        // Store reference to health bar for updates and cleanup
        object.healthBar = healthBar;
        
        // Add to our map for cleanup
        this.healthBars.set(object, healthBar);
        
        // Draw initial health bar (will be updated in update loop)
        this.updateHealthBar(object, true);
    }

    updateHealthBar(object, justCreated) {
        if (!object.healthBar || !object.props) return;
        
        const health = object.props.health;
        const fullHealth = object.props.fullHealth;
        
        // Calculate health percentage
        const healthPercentage = Math.max(0, Math.min(1, health / fullHealth));
        
        // Clear previous graphics
        object.healthBar.clear();
        
        // Health bar dimensions
        const barWidth = 60;
        const barHeight = 8;
        const offsetX = -barWidth / 2; // Center the bar on object
        const offsetY = -50; // Position above object
        
        // Draw background (red) - full health bar
        object.healthBar.fillStyle(0xff0000, 1);
        object.healthBar.fillRect(object.x + offsetX, object.y + offsetY, barWidth, barHeight).setAlpha(1);
        
        // Draw health fill (green) - current health
        const greenWidth = barWidth * healthPercentage;
        if (greenWidth > 0) {
            object.healthBar.fillStyle(0x00ff00, 1);
            object.healthBar.fillRect(object.x + offsetX, object.y + offsetY, greenWidth, barHeight).setAlpha(1);
        }
        if (justCreated) {
            object.healthBar.setAlpha(0);
        }
        
        if (object.alpha > 0) {
            this.scene.tweens.add({
                targets: object.healthBar,
                alpha: 0,
                delay: 10000
            });
        }

        if (healthPercentage <= 0) {
            object.healthBar.destroy();
        } 
    }

    takeDamage(object, player) {
        const dmg = Phaser.Math.Between(player.dmgMin,player.dmgMax);
        if (player.targetX === object.x && player.targetY === object.y) {
            switch (object.props.type){
                case 'palmTree':
                    object.props.health -= dmg;
                    this.scene.sound.play('chop');
                    break;
                case 'forestTree':
                    object.props.health -= dmg;
                    this.scene.sound.play('chop');
                    break;
                default:
            }
            this.updateHealthBar(object);
            if (object.props.health <= 0) {
                this.destroyObject(object);
            }
        }
    }

    destroyObject(object) {
        // Replace object with doneSprite
        if (object.props.doneSprite !== null) {
            const doneSprite = this.scene.physics.add.sprite(object.x, object.y, 'objects', object.props.doneSprite);
            
        }

        // Drop Resources
        if (object.props.yield) {
            const amount = Phaser.Math.Between(object.props.amount[0], object.props.amount[1]);
            if (amount > 0) {
                let sprite = null;
                switch (object.props.yield) {
                    case 'wood':
                        if (amount === 3) {
                            sprite = 14;
                        } else if (amount === 2) {
                            sprite = 13;
                        } else {
                            sprite = 12;
                        }
                        
                        break;
                    default:
                }
                const drop = this.scene.physics.add.sprite(object.x-5, object.y-50, 'objects', sprite).setScale(.8);
                this.scene.tweens.add({
                    targets: drop,
                    scale: 1,
                    y: object.y,
                    x: object.x,
                    ease: 'Bounce',
                    duration: 800,
                    onComplete: () => {
                        drop.postFX.addGlow(0x00ffc6);
                        this.scene.items.add(drop);
                        drop.props = {
                            type: object.props.yield,
                            amount: amount
                        };
                        drop.setInteractive();
                    }
                });
            }
        }

        // Remove from scene and cleanup
        object.destroy();
        
        // Remove health bar reference
        if (object.healthBar && this.healthBars.has(object)) {
            this.healthBars.delete(object);
        }
    }

    update(delta) {
        // Update all created objects
        this.objects.forEach(object => {
            if (object.update) {
                object.update(delta);
            }
            
            // Update health bars for objects that have them
            if (object.healthBar && object.props) {
                this.updateHealthBar(object);
            }
        });
    }
}