import { world, system, EntityDamageCause } from '@minecraft/server';

export const MythrilFruitSystem = {
    config: {
        // Ancient Mythril Fruit (Green) - Nature and Healing
        ancientMythrilFruit: {
            identifier: 'myw:ancient_mythril_fruit',
            name: 'Ancient Mythril Fruit',
            color: '§a',
            effects: {
                // Primary effects
                regeneration: { duration: 1200, amplifier: 2 }, // 1 minute
                resistance: { duration: 1800, amplifier: 1 },    // 1.5 minutes
                strength: { duration: 1200, amplifier: 1 },     // 1 minute
                
                // Secondary effects
                speed: { duration: 900, amplifier: 1 },         // 45 seconds
                jump_boost: { duration: 900, amplifier: 2 },    // 45 seconds
                water_breathing: { duration: 1800, amplifier: 0 } // 1.5 minutes
            },
            particles: 'myw:mythril_heal_particle',
            sound: 'random.levelup'
        },

        // Golden Ancient Mythril Fruit (Gold) - Power and Ascension
        goldenMythrilFruit: {
            identifier: 'myw:ancient_mythril_fruit_2',
            name: 'Golden Ancient Mythril Fruit',
            color: '§6',
            effects: {
                // Primary effects
                strength: { duration: 1800, amplifier: 3 },     // 1.5 minutes
                resistance: { duration: 1800, amplifier: 2 },   // 1.5 minutes
                regeneration: { duration: 1200, amplifier: 1 }, // 1 minute
                
                // Secondary effects
                speed: { duration: 1200, amplifier: 2 },        // 1 minute
                jump_boost: { duration: 1200, amplifier: 3 },   // 1 minute
                fire_resistance: { duration: 2400, amplifier: 0 }, // 2 minutes
                night_vision: { duration: 1800, amplifier: 0 }  // 1.5 minutes
            },
            particles: 'myw:mythril_flight_particle',
            sound: 'random.levelup'
        }
    },

    // Handle fruit consumption
    handleFruitConsumption(player, itemStack) {
        try {
            const itemId = itemStack.typeId;
            
            if (itemId === this.config.ancientMythrilFruit.identifier) {
                this.consumeAncientMythrilFruit(player);
                return true;
            } else if (itemId === this.config.goldenMythrilFruit.identifier) {
                this.consumeGoldenMythrilFruit(player);
                return true;
            }
            
            return false;
        } catch (error) {
            world.sendMessage(`§c[Mythril Fruit Error] ${error}`);
            return false;
        }
    },

    // Consume Ancient Mythril Fruit (Green)
    consumeAncientMythrilFruit(player) {
        try {
            const config = this.config.ancientMythrilFruit;
            
            this.sendFruitMessage(player, `${config.color}🍃 CONSUMING ANCIENT MYTHRIL FRUIT! 🍃`);
            this.sendFruitMessage(player, '§7Nature\'s power flows through your veins...');

            // Phase 1: Initial effects and particles
            this.createFruitConsumptionEffects(player, config);
            
            // Phase 2: Apply effects with delay
            system.runTimeout(() => {
                this.applyFruitEffects(player, config);
            }, 20);

            // Phase 3: Special nature transformation
            system.runTimeout(() => {
                this.createNatureTransformation(player);
            }, 60);

            // Phase 4: Final blessing
            system.runTimeout(() => {
                this.createNatureBlessing(player);
            }, 120);

        } catch (error) {
            this.sendFruitMessage(player, `§cError consuming fruit: ${error.message}`);
        }
    },

    // Consume Golden Ancient Mythril Fruit (Gold)
    consumeGoldenMythrilFruit(player) {
        try {
            const config = this.config.goldenMythrilFruit;
            
            this.sendFruitMessage(player, `${config.color}✨ CONSUMING GOLDEN ANCIENT MYTHRIL FRUIT! ✨`);
            this.sendFruitMessage(player, '§7Divine power surges through your body...');

            // Phase 1: Initial effects and particles
            this.createFruitConsumptionEffects(player, config);
            
            // Phase 2: Apply effects with delay
            system.runTimeout(() => {
                this.applyFruitEffects(player, config);
            }, 20);

            // Phase 3: Special golden transformation
            system.runTimeout(() => {
                this.createGoldenTransformation(player);
            }, 60);

            // Phase 4: Final divine blessing
            system.runTimeout(() => {
                this.createDivineBlessing(player);
            }, 120);

        } catch (error) {
            this.sendFruitMessage(player, `§cError consuming fruit: ${error.message}`);
        }
    },

    // Create consumption effects
    createFruitConsumptionEffects(player, config) {
        try {
            const playerPos = player.location;
            const dimension = player.dimension;

            // Spiral particle effect around player
            for (let i = 0; i < 30; i++) {
                system.runTimeout(() => {
                    const angle = (i / 30) * Math.PI * 2;
                    const radius = 2 + Math.sin(i * 0.3) * 1;
                    const height = Math.sin(i * 0.2) * 2;
                    
                    const particlePos = {
                        x: playerPos.x + Math.cos(angle) * radius,
                        y: playerPos.y + height,
                        z: playerPos.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle(config.particles, particlePos);
                }, i * 2);
            }

            // Central column of particles
            for (let h = 0; h < 20; h++) {
                system.runTimeout(() => {
                    dimension.spawnParticle(config.particles, {
                        x: playerPos.x + (Math.random() - 0.5) * 0.5,
                        y: playerPos.y + h * 0.3,
                        z: playerPos.z + (Math.random() - 0.5) * 0.5
                    });
                }, h * 1);
            }

        } catch (error) {
            // Error in effects
        }
    },

    // Apply fruit effects to player
    applyFruitEffects(player, config) {
        try {
            const effects = config.effects;
            
            // Apply all effects
            Object.entries(effects).forEach(([effectName, effectData]) => {
                try {
                    player.addEffect(effectName, effectData.duration, {
                        amplifier: effectData.amplifier,
                        showParticles: true
                    });
                } catch (error) {
                    // Error applying effect
                }
            });

            this.sendFruitMessage(player, `${config.color}✨ ${config.name} effects applied!`);
            this.sendFruitMessage(player, '§7You feel the ancient power coursing through you...');

        } catch (error) {
            this.sendFruitMessage(player, `§cError applying effects: ${error.message}`);
        }
    },

    // Create nature transformation (Green Fruit)
    createNatureTransformation(player) {
        try {
            const playerPos = player.location;
            const dimension = player.dimension;

            this.sendFruitMessage(player, '§a🌿 Nature\'s blessing transforms the area around you...');

            // Create nature circle around player
            for (let i = 0; i < 16; i++) {
                system.runTimeout(() => {
                    const angle = (i / 16) * Math.PI * 2;
                    const radius = 5;
                    
                    const particlePos = {
                        x: playerPos.x + Math.cos(angle) * radius,
                        y: playerPos.y,
                        z: playerPos.z + Math.sin(angle) * radius
                    };
                    
                    // Spawn nature particles
                    dimension.spawnParticle('myw:mythril_heal_particle', particlePos);
                    
                    // Spawn additional particles above
                    for (let h = 1; h <= 3; h++) {
                        dimension.spawnParticle('myw:mythril_particle_minimalist', {
                            x: particlePos.x,
                            y: particlePos.y + h,
                            z: particlePos.z
                        });
                    }
                }, i * 3);
            }

            // Heal player
            try {
                if (player.hasComponent('minecraft:health')) {
                    const health = player.getComponent('minecraft:health');
                    health.setCurrentValue(health.effectiveMax);
                }
            } catch (error) {
                // Error healing
            }

        } catch (error) {
            // Error in nature transformation
        }
    },

    // Create golden transformation (Gold Fruit)
    createGoldenTransformation(player) {
        try {
            const playerPos = player.location;
            const dimension = player.dimension;

            this.sendFruitMessage(player, '§6✨ Divine energy radiates from your being...');

            // Create golden aura around player
            for (let ring = 0; ring < 3; ring++) {
                system.runTimeout(() => {
                    const ringRadius = 3 + ring * 2;
                    
                    for (let i = 0; i < 12; i++) {
                        const angle = (i / 12) * Math.PI * 2;
                        
                        const particlePos = {
                            x: playerPos.x + Math.cos(angle) * ringRadius,
                            y: playerPos.y + 1,
                            z: playerPos.z + Math.sin(angle) * ringRadius
                        };
                        
                        // Spawn golden particles
                        dimension.spawnParticle('myw:mythril_flight_particle', particlePos);
                    }
                }, ring * 10);
            }

            // Create upward spiral
            for (let h = 0; h < 15; h++) {
                system.runTimeout(() => {
                    const angle = h * 0.5;
                    const radius = 2;
                    
                    const particlePos = {
                        x: playerPos.x + Math.cos(angle) * radius,
                        y: playerPos.y + h * 0.5,
                        z: playerPos.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_flight_particle', particlePos);
                }, h * 2);
            }

        } catch (error) {
            // Error in golden transformation
        }
    },

    // Create nature blessing (Green Fruit)
    createNatureBlessing(player) {
        try {
            const playerPos = player.location;
            const dimension = player.dimension;

            this.sendFruitMessage(player, '§a🌿 Nature\'s blessing is complete!');
            this.sendFruitMessage(player, '§7You are now one with the ancient forests...');

            // Final nature explosion
            for (let i = 0; i < 25; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const radius = Math.random() * 8;
                    const height = Math.random() * 6;
                    
                    const particlePos = {
                        x: playerPos.x + Math.cos(angle) * radius,
                        y: playerPos.y + height,
                        z: playerPos.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_heal_particle', particlePos);
                }, i * 2);
            }

        } catch (error) {
            // Error in nature blessing
        }
    },

    // Create divine blessing (Gold Fruit)
    createDivineBlessing(player) {
        try {
            const playerPos = player.location;
            const dimension = player.dimension;

            this.sendFruitMessage(player, '§6✨ Divine blessing is complete!');
            this.sendFruitMessage(player, '§7You have been touched by the ancient gods...');

            // Final divine explosion
            for (let i = 0; i < 30; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const radius = Math.random() * 10;
                    const height = Math.random() * 8;
                    
                    const particlePos = {
                        x: playerPos.x + Math.cos(angle) * radius,
                        y: playerPos.y + height,
                        z: playerPos.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_flight_particle', particlePos);
                }, i * 2);
            }

        } catch (error) {
            // Error in divine blessing
        }
    },

    // Send fruit message to player
    sendFruitMessage(player, message) {
        try {
            if (player && player.sendMessage) {
                player.sendMessage(message);
            } else {
                world.sendMessage(message);
            }
        } catch (error) {
            world.sendMessage(message);
        }
    }
};

// Register the fruit components
export function registerMythrilFruitComponents(itemComponentRegistry) {
    // Register Ancient Mythril Fruit
    itemComponentRegistry.registerCustomComponent('myw:ancient_mythril_fruit', {
        onUseInAir(eventData) {
            const { itemStack, source } = eventData;
            if (source && source.typeId === 'minecraft:player') {
                if (MythrilFruitSystem.handleFruitConsumption(source, itemStack)) {
                    // Remove one fruit from stack
                    try {
                        if (itemStack.amount > 1) {
                            itemStack.amount -= 1;
                        } else {
                            // If only one fruit, remove the item
                            source.getComponent('minecraft:inventory').container.setItem(source.selectedSlotIndex, undefined);
                        }
                    } catch (error) {
                        // Error managing item stack
                    }
                }
            }
        }
    });

    // Register Golden Ancient Mythril Fruit
    itemComponentRegistry.registerCustomComponent('myw:ancient_mythril_fruit_2', {
        onUseInAir(eventData) {
            const { itemStack, source } = eventData;
            if (source && source.typeId === 'minecraft:player') {
                if (MythrilFruitSystem.handleFruitConsumption(source, itemStack)) {
                    // Remove one fruit from stack
                    try {
                        if (itemStack.amount > 1) {
                            itemStack.amount -= 1;
                        } else {
                            // If only one fruit, remove the item
                            source.getComponent('minecraft:inventory').container.setItem(source.selectedSlotIndex, undefined);
                        }
                    } catch (error) {
                        // Error managing item stack
                    }
                }
            }
        }
    });
}

// Initialize mythril fruit system
export function initializeMythrilFruitSystem() {
    world.sendMessage('§a[OK] Mythril Fruit System initialized');
    world.sendMessage('§7Ancient and Golden Mythril Fruits are now consumable!');
}
