/**
 * PiranhaPlant.js
 * Enemy that shoots fireballs at Mario when in range
 * Appears starting from level 3+
 */

export class PiranhaPlant {
    /**
     * Generate piranha plants for a level
     * @param {Object} level - Level data
     * @param {number} difficulty - Difficulty level (1-5)
     * @returns {Array} - Array of piranha plant objects
     */
    static generate(level, difficulty) {
        const plants = [];
        const plantCount = Math.min(difficulty - 2, 2); // 0-2 plants for level 3+

        if (plantCount <= 0) return plants;

        for (let i = 0; i < plantCount; i++) {
            // Find a suitable ground platform for the plant
            const groundPlatforms = level.platforms.filter(p => p.type === 'ground');
            if (groundPlatforms.length === 0) continue;

            const platform = groundPlatforms[Math.floor(Math.random() * groundPlatforms.length)];
            const plantX = platform.x + Math.random() * (platform.width - 30);

            plants.push({
                x: plantX,
                y: platform.y - 25, // Plant height above platform
                width: 20,
                height: 25,
                color: '#228B22', // Forest green
                lastShot: 0,
                shootCooldown: 2000 + Math.random() * 1000, // 2-3 second intervals
                type: 'piranha',
                visible: true,
                extended: 0, // For animation (how much plant extends from pipe)
                maxExtension: 25,
                extending: true
            });

            console.log(`🌸 Piranha plant placed at x=${plantX.toFixed(0)}`);
        }

        return plants;
    }

    /**
     * Update all piranha plants
     * @param {Array} plants - Array of piranha plants
     * @param {Object} mario - Mario object
     * @param {Array} projectiles - Projectiles array to add new projectiles
     * @param {Function} playSound - Sound callback
     */
    static update(plants, mario, projectiles, playSound) {
        const currentTime = Date.now();

        plants.forEach(plant => {
            // If plant is flattened, it stays dead permanently
            if (plant.flattened) {
                return; // Don't animate or shoot while flattened
            }

            // Animate plant extension/retraction
            if (plant.extending) {
                plant.extended = Math.min(plant.extended + 1, plant.maxExtension);
                if (plant.extended >= plant.maxExtension) {
                    plant.extending = false;
                }
            } else {
                plant.extended = Math.max(plant.extended - 1, 0);
                if (plant.extended <= 0) {
                    plant.extending = true;
                }
            }

            // Check if it's time to shoot
            if (currentTime - plant.lastShot > plant.shootCooldown) {
                // Check if Mario is in range (within 400 pixels)
                const distanceToMario = Math.abs(plant.x - mario.x);

                if (distanceToMario < 400) {
                    // Shoot projectile towards Mario
                    const direction = mario.x > plant.x ? 1 : -1;

                    projectiles.push({
                        x: plant.x + plant.width / 2,
                        y: plant.y + plant.height / 2,
                        velocityX: direction * 3, // Projectile speed
                        velocityY: 0,
                        radius: 8,
                        color: '#FF4500', // Orange fireball
                        type: 'fireball',
                        life: 200 // 200 frames lifetime
                    });

                    plant.lastShot = currentTime;
                    if (playSound) playSound('enemy_defeat'); // Shooting sound
                    console.log(`🔥 Piranha plant shot fireball towards Mario!`);
                }
            }
        });
    }

    /**
     * Check collision between Mario and piranha plants
     * @param {Object} mario - Mario object
     * @param {Array} plants - Array of piranha plants
     * @returns {Object|null} - Colliding plant or null
     */
    static checkCollision(mario, plants) {
        for (const plant of plants) {
            if (!plant.visible) continue;

            // Only check collision when plant is extended
            if (plant.extended > 10) {
                const headY = plant.y - plant.extended;
                const headRadius = 10;

                // Simple circle-rectangle collision
                const closestX = Math.max(mario.x, Math.min(plant.x + plant.width / 2, mario.x + mario.width));
                const closestY = Math.max(mario.y, Math.min(headY, mario.y + mario.height));

                const distanceX = (plant.x + plant.width / 2) - closestX;
                const distanceY = headY - closestY;
                const distanceSquared = distanceX * distanceX + distanceY * distanceY;

                if (distanceSquared < headRadius * headRadius) {
                    return plant;
                }
            }
        }
        return null;
    }
}

export default PiranhaPlant;
