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

export const AncientEssenceSystem = {
    // ==================== CONFIGURATION ====================
    config: {
        // Ancient Mythril Essence effects
        essence: {
            healAmount: 4, // 2 hearts
            cooldown: 40, // 2 seconds
            range: 8,
            duration: 200, // 10 seconds
            speedBoost: 1.2, // 20% speed boost
            jumpBoost: 1.1, // 10% jump boost
            resistance: 0.8 // 20% damage reduction
        },
        
        // Crystallized Ancient Mythril Essence effects
        crystallized: {
            healAmount: 8, // 4 hearts
            cooldown: 80, // 4 seconds
            range: 12,
            duration: 400, // 20 seconds
            speedBoost: 1.4, // 40% speed boost
            jumpBoost: 1.3, // 30% jump boost
            resistance: 0.6, // 40% damage reduction
            regeneration: 1, // 1 heart per second
            nightVision: true,
            waterBreathing: true
        },
        
        // Ancient Mythril Charge effects
        charge: {
            explosionRadius: 5,
            damage: 15,
            cooldown: 100, // 5 seconds
            knockback: 2.0,
            fireDamage: 5,
            lightning: true
        }
    },

    // ==================== SYSTEM STATE ====================
    state: {
        playerCooldowns: new Map(),
        activeEffects: new Map()
    },

    // ==================== ANCIENT MYTHRIL ESSENCE ====================
    handleEssenceUse(player, itemStack) {
        try {
            const playerId = player.id;
            const currentTick = system.currentTick;

            // Check cooldown
            const lastUse = this.state.playerCooldowns.get(playerId) || 0;
            if (currentTick - lastUse < this.config.essence.cooldown) {
                const remaining = Math.ceil((this.config.essence.cooldown - (currentTick - lastUse)) / 20);
                this.sendEssenceMessage(player, `§cEssence cooldown: ${remaining}s`);
                return false;
            }

            // Set cooldown
            this.state.playerCooldowns.set(playerId, currentTick);

            // Heal player
            this.healPlayer(player, this.config.essence.healAmount);

            // Create healing aura
            this.createHealingAura(player, this.config.essence.range, this.config.essence.duration);

            // Apply buffs
            this.applyEssenceBuffs(player, this.config.essence.duration);

            // Visual effects
            this.createEssenceEffects(player);

            // Consume item
            this.consumeItem(player, itemStack);

            this.sendEssenceMessage(player, '§aAncient essence activated!');
            return true;

        } catch (error) {
            this.sendEssenceMessage(player, '§cEssence failed');
            return false;
        }
    },

    // ==================== CRYSTALLIZED ANCIENT MYTHRIL ESSENCE ====================
    handleCrystallizedEssenceUse(player, itemStack) {
        try {
            const playerId = player.id;
            const currentTick = system.currentTick;

            // Check cooldown
            const lastUse = this.state.playerCooldowns.get(playerId) || 0;
            if (currentTick - lastUse < this.config.crystallized.cooldown) {
                const remaining = Math.ceil((this.config.crystallized.cooldown - (currentTick - lastUse)) / 20);
                this.sendEssenceMessage(player, `§cCrystallized essence cooldown: ${remaining}s`);
                return false;
            }

            // Set cooldown
            this.state.playerCooldowns.set(playerId, currentTick);

            // Heal player
            this.healPlayer(player, this.config.crystallized.healAmount);

            // Create powerful healing aura
            this.createHealingAura(player, this.config.crystallized.range, this.config.crystallized.duration);

            // Create crystal shield
            this.createCrystalShield(player, this.config.crystallized.duration);

            // Apply enhanced buffs
            this.applyCrystallizedBuffs(player, this.config.crystallized.duration);

            // Visual effects
            this.createCrystallizedEffects(player);

            // Consume item
            this.consumeItem(player, itemStack);

            this.sendEssenceMessage(player, '§dCrystallized essence activated!');
            return true;

        } catch (error) {
            this.sendEssenceMessage(player, '§cCrystallized essence failed');
            return false;
        }
    },

    // ==================== ANCIENT MYTHRIL CHARGE ====================
    handleChargeUse(player, itemStack) {
        try {
            const playerId = player.id;
            const currentTick = system.currentTick;

            // Check cooldown
            const lastUse = this.state.playerCooldowns.get(playerId) || 0;
            if (currentTick - lastUse < this.config.charge.cooldown) {
                const remaining = Math.ceil((this.config.charge.cooldown - (currentTick - lastUse)) / 20);
                this.sendEssenceMessage(player, `§cCharge cooldown: ${remaining}s`);
                return false;
            }

            // Set cooldown
            this.state.playerCooldowns.set(playerId, currentTick);

            // Create explosive charge
            this.createExplosiveCharge(player);

            // Create lightning effect
            if (this.config.charge.lightning) {
                this.createLightningEffect(player);
            }

            // Visual effects
            this.createChargeEffects(player);

            // Consume item
            this.consumeItem(player, itemStack);

            this.sendEssenceMessage(player, '§cAncient charge activated!');
            return true;

        } catch (error) {
            this.sendEssenceMessage(player, '§cCharge failed');
            return false;
        }
    },

    // ==================== EFFECTS ====================
    healPlayer(player, amount) {
        try {
            const health = player.getComponent('minecraft:health');
            if (health) {
                health.setCurrentValue(Math.min(health.currentValue + amount, health.effectiveMax));
            }
        } catch (error) {
            // Ignore errors
        }
    },

    createHealingAura(player, range, duration) {
        try {
            const playerId = player.id;
            const startTick = system.currentTick;
            const endTick = startTick + duration;

            // Store active effect
            this.state.activeEffects.set(playerId, {
                type: 'healing_aura',
                startTick: startTick,
                endTick: endTick,
                range: range,
                player: player
            });

            // Start healing loop
            this.startHealingLoop(playerId, range, endTick);

        } catch (error) {
            // Ignore errors
        }
    },

    startHealingLoop(playerId, range, endTick) {
        const healingInterval = system.runInterval(() => {
            try {
                const currentTick = system.currentTick;
                if (currentTick >= endTick) {
                    this.state.activeEffects.delete(playerId);
                    return;
                }

                const effect = this.state.activeEffects.get(playerId);
                if (!effect || !effect.player) {
                    this.state.activeEffects.delete(playerId);
                    return;
                }

                const player = effect.player;
                const dimension = player.dimension;
                const playerPos = player.location;

                // Heal nearby players
                const nearbyPlayers = dimension.getPlayers({
                    location: playerPos,
                    maxDistance: range
                });

                for (const nearbyPlayer of nearbyPlayers) {
                    if (nearbyPlayer.id !== playerId) {
                        this.healPlayer(nearbyPlayer, 1);
                    }
                }

                // Create healing particles
                this.createHealingParticles(playerPos, dimension, range);

            } catch (error) {
                this.state.activeEffects.delete(playerId);
            }
        }, 20); // Every second
    },

    createCrystalShield(player, duration) {
        try {
            const playerId = player.id;
            const startTick = system.currentTick;
            const endTick = startTick + duration;

            // Store shield effect
            this.state.activeEffects.set(playerId + '_shield', {
                type: 'crystal_shield',
                startTick: startTick,
                endTick: endTick,
                player: player
            });

            // Create shield particles
            this.createShieldParticles(player, duration);

        } catch (error) {
            // Ignore errors
        }
    },

    createExplosiveCharge(player) {
        try {
            const dimension = player.dimension;
            const playerPos = player.location;

            // Create explosion
            dimension.createExplosion(playerPos, this.config.charge.explosionRadius, {
                allowUnderwater: true,
                breaksBlocks: true,
                causesFire: false
            });

            // Damage nearby entities
            const entities = dimension.getEntities({
                location: playerPos,
                maxDistance: this.config.charge.explosionRadius
            });

            for (const entity of entities) {
                if (entity.id !== player.id) {
                    entity.applyDamage(this.config.charge.damage, {
                        cause: 'explosion',
                        damagingEntity: player
                    });

                    // Apply knockback
                    const direction = {
                        x: entity.location.x - playerPos.x,
                        y: 0.5,
                        z: entity.location.z - playerPos.z
                    };
                    const distance = Math.sqrt(direction.x * direction.x + direction.z * direction.z);
                    if (distance > 0) {
                        direction.x = (direction.x / distance) * this.config.charge.knockback;
                        direction.z = (direction.z / distance) * this.config.charge.knockback;
                        entity.applyKnockback(direction.x, direction.z);
                    }

                    // Apply fire damage
                    if (this.config.charge.fireDamage > 0) {
                        entity.applyDamage(this.config.charge.fireDamage, {
                            cause: 'fire',
                            damagingEntity: player
                        });
                    }
                }
            }

        } catch (error) {
            // Ignore errors
        }
    },

    createLightningEffect(player) {
        try {
            const dimension = player.dimension;
            const playerPos = player.location;

            // Spawn lightning
            dimension.spawnEntity('minecraft:lightning_bolt', playerPos);

            // Lightning particles
            for (let i = 0; i < 8; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('minecraft:lightning', {
                        x: playerPos.x + (Math.random() - 0.5) * 4,
                        y: playerPos.y + Math.random() * 5,
                        z: playerPos.z + (Math.random() - 0.5) * 4
                    });
                }, i * 3);
            }

        } catch (error) {
            // Ignore errors
        }
    },

    applyEssenceBuffs(player, duration) {
        try {
            const playerId = player.id;
            const startTick = system.currentTick;
            const endTick = startTick + duration;

            // Store buff effect
            this.state.activeEffects.set(playerId + '_buffs', {
                type: 'essence_buffs',
                startTick: startTick,
                endTick: endTick,
                player: player,
                speedBoost: this.config.essence.speedBoost,
                jumpBoost: this.config.essence.jumpBoost,
                resistance: this.config.essence.resistance
            });

            // Apply effects
            this.applyPlayerEffects(player, 'speed', this.config.essence.speedBoost);
            this.applyPlayerEffects(player, 'jump_boost', this.config.essence.jumpBoost);
            this.applyPlayerEffects(player, 'resistance', this.config.essence.resistance);

        } catch (error) {
            // Ignore errors
        }
    },

    applyCrystallizedBuffs(player, duration) {
        try {
            const playerId = player.id;
            const startTick = system.currentTick;
            const endTick = startTick + duration;

            // Store enhanced buff effect
            this.state.activeEffects.set(playerId + '_crystal_buffs', {
                type: 'crystallized_buffs',
                startTick: startTick,
                endTick: endTick,
                player: player,
                speedBoost: this.config.crystallized.speedBoost,
                jumpBoost: this.config.crystallized.jumpBoost,
                resistance: this.config.crystallized.resistance,
                regeneration: this.config.crystallized.regeneration,
                nightVision: this.config.crystallized.nightVision,
                waterBreathing: this.config.crystallized.waterBreathing
            });

            // Apply enhanced effects
            this.applyPlayerEffects(player, 'speed', this.config.crystallized.speedBoost);
            this.applyPlayerEffects(player, 'jump_boost', this.config.crystallized.jumpBoost);
            this.applyPlayerEffects(player, 'resistance', this.config.crystallized.resistance);
            this.applyPlayerEffects(player, 'regeneration', this.config.crystallized.regeneration);
            
            if (this.config.crystallized.nightVision) {
                this.applyPlayerEffects(player, 'night_vision', 1);
            }
            
            if (this.config.crystallized.waterBreathing) {
                this.applyPlayerEffects(player, 'water_breathing', 1);
            }

            // Start regeneration loop
            this.startRegenerationLoop(playerId, this.config.crystallized.regeneration, endTick);

        } catch (error) {
            // Ignore errors
        }
    },

    applyPlayerEffects(player, effectType, amplifier) {
        try {
            // This would apply the actual effects to the player
            // For now, we'll just store the information
            // In a real implementation, you'd use the effect system
        } catch (error) {
            // Ignore errors
        }
    },

    startRegenerationLoop(playerId, healAmount, endTick) {
        const regenInterval = system.runInterval(() => {
            try {
                const currentTick = system.currentTick;
                if (currentTick >= endTick) {
                    return;
                }

                const effect = this.state.activeEffects.get(playerId + '_crystal_buffs');
                if (!effect || !effect.player) {
                    return;
                }

                const player = effect.player;
                this.healPlayer(player, healAmount);

            } catch (error) {
                // Ignore errors
            }
        }, 20); // Every second
    },

    // ==================== VISUAL EFFECTS ====================
    createEssenceEffects(player) {
        try {
            const dimension = player.dimension;
            const playerPos = player.location;

            // Healing particles
            for (let i = 0; i < 15; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('minecraft:heart_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 2,
                        y: playerPos.y + Math.random() * 2,
                        z: playerPos.z + (Math.random() - 0.5) * 2
                    });
                }, i * 2);
            }

            // Mythril heal particles
            for (let i = 0; i < 12; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_heal_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 3,
                        y: playerPos.y + Math.random() * 3,
                        z: playerPos.z + (Math.random() - 0.5) * 3
                    });
                }, i * 3);
            }

            // Mythril particles
            for (let i = 0; i < 8; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 4,
                        y: playerPos.y + Math.random() * 4,
                        z: playerPos.z + (Math.random() - 0.5) * 4
                    });
                }, i * 4);
            }

        } catch (error) {
            // Ignore errors
        }
    },

    createCrystallizedEffects(player) {
        try {
            const dimension = player.dimension;
            const playerPos = player.location;

            // Crystal particles
            for (let i = 0; i < 20; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('minecraft:crystal_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 4,
                        y: playerPos.y + Math.random() * 4,
                        z: playerPos.z + (Math.random() - 0.5) * 4
                    });
                }, i * 2);
            }

            // Mythril heal particles
            for (let i = 0; i < 18; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_heal_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 5,
                        y: playerPos.y + Math.random() * 5,
                        z: playerPos.z + (Math.random() - 0.5) * 5
                    });
                }, i * 2);
            }

            // Mythril serpentine particles
            for (let i = 0; i < 15; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle_serpentine', {
                        x: playerPos.x + (Math.random() - 0.5) * 6,
                        y: playerPos.y + Math.random() * 6,
                        z: playerPos.z + (Math.random() - 0.5) * 6
                    });
                }, i * 3);
            }

            // Enchanting particles
            for (let i = 0; i < 12; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('minecraft:enchanting_table_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 3,
                        y: playerPos.y + Math.random() * 3,
                        z: playerPos.z + (Math.random() - 0.5) * 3
                    });
                }, i * 4);
            }

        } catch (error) {
            // Ignore errors
        }
    },

    createChargeEffects(player) {
        try {
            const dimension = player.dimension;
            const playerPos = player.location;

            // Explosion particles
            for (let i = 0; i < 25; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('minecraft:explosion', {
                        x: playerPos.x + (Math.random() - 0.5) * 6,
                        y: playerPos.y + Math.random() * 4,
                        z: playerPos.z + (Math.random() - 0.5) * 6
                    });
                }, i * 1);
            }

            // Mythril serpentine particles
            for (let i = 0; i < 20; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle_serpentine', {
                        x: playerPos.x + (Math.random() - 0.5) * 8,
                        y: playerPos.y + Math.random() * 6,
                        z: playerPos.z + (Math.random() - 0.5) * 8
                    });
                }, i * 2);
            }

            // Fire particles
            for (let i = 0; i < 18; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('minecraft:flame_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 5,
                        y: playerPos.y + Math.random() * 3,
                        z: playerPos.z + (Math.random() - 0.5) * 5
                    });
                }, i * 2);
            }

            // Mythril particles
            for (let i = 0; i < 15; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle', {
                        x: playerPos.x + (Math.random() - 0.5) * 7,
                        y: playerPos.y + Math.random() * 5,
                        z: playerPos.z + (Math.random() - 0.5) * 7
                    });
                }, i * 3);
            }

        } catch (error) {
            // Ignore errors
        }
    },

    createHealingParticles(location, dimension, range) {
        try {
            // Create healing particles in range
            for (let i = 0; i < 8; i++) {
                const randomPos = {
                    x: location.x + (Math.random() - 0.5) * range * 2,
                    y: location.y + Math.random() * 2,
                    z: location.z + (Math.random() - 0.5) * range * 2
                };

                dimension.spawnParticle('minecraft:heart_particle', randomPos);
            }

            // Mythril heal particles
            for (let i = 0; i < 6; i++) {
                const randomPos = {
                    x: location.x + (Math.random() - 0.5) * range * 2,
                    y: location.y + Math.random() * 2,
                    z: location.z + (Math.random() - 0.5) * range * 2
                };

                dimension.spawnParticle('myw:mythril_heal_particle', randomPos);
            }
        } catch (error) {
            // Ignore errors
        }
    },

    createShieldParticles(player, duration) {
        try {
            const dimension = player.dimension;
            const playerPos = player.location;

            // Create shield particles around player
            for (let i = 0; i < duration / 10; i++) {
                system.runTimeout(() => {
                    // Create circular shield particles
                    for (let angle = 0; angle < 360; angle += 30) {
                        const rad = (angle * Math.PI) / 180;
                        const x = playerPos.x + Math.cos(rad) * 2;
                        const z = playerPos.z + Math.sin(rad) * 2;

                        dimension.spawnParticle('minecraft:crystal_particle', {
                            x: x,
                            y: playerPos.y + 1,
                            z: z
                        });
                    }

                    // Mythril heal particles in shield
                    for (let angle = 0; angle < 360; angle += 45) {
                        const rad = (angle * Math.PI) / 180;
                        const x = playerPos.x + Math.cos(rad) * 2.5;
                        const z = playerPos.z + Math.sin(rad) * 2.5;

                        dimension.spawnParticle('myw:mythril_heal_particle', {
                            x: x,
                            y: playerPos.y + 1.5,
                            z: z
                        });
                    }
                }, i * 10);
            }
        } catch (error) {
            // Ignore errors
        }
    },

    // ==================== UTILITIES ====================
    consumeItem(player, itemStack) {
        try {
            const inventory = player.getComponent('minecraft:inventory');
            if (!inventory) return;

            const container = inventory.container;
            if (!container) return;

            // Find and consume the item
            for (let i = 0; i < container.size; i++) {
                const item = container.getItem(i);
                if (item && item.typeId === itemStack.typeId) {
                    const newAmount = Math.max(0, item.amount - 1);
                    if (newAmount === 0) {
                        container.setItem(i, undefined);
                    } else {
                        container.setItem(i, { typeId: item.typeId, amount: newAmount });
                    }
                    break;
                }
            }
        } catch (error) {
            // Ignore errors
        }
    },

    sendEssenceMessage(player, message) {
        try {
            player.onScreenDisplay.setActionBar(`§5[ESSENCE] ${message}`);
        } catch (error) {
            // Ignore errors
        }
    }
};

// ==================== EVENT HANDLERS ====================
function handleItemUse(event) {
    const { itemStack, source } = event;
    
    if (itemStack.typeId === 'myw:ancient_mythril_essence') {
        AncientEssenceSystem.handleEssenceUse(source, itemStack);
    } else if (itemStack.typeId === 'myw:ancient_mythril_essence_crystallized') {
        AncientEssenceSystem.handleCrystallizedEssenceUse(source, itemStack);
    } else if (itemStack.typeId === 'myw:ancient_mythril_charge') {
        AncientEssenceSystem.handleChargeUse(source, itemStack);
    }
}

// ==================== EXPORTS ====================
export function registerAncientEssenceSystem() {
    console.log('[ANCIENT ESSENCE] Essence system registered');
}

export function initializeAncientEssenceSystem() {
    world.afterEvents.itemUse.subscribe(handleItemUse);
    console.log('[ANCIENT ESSENCE] Initialized - Healing, Crystallized, Charge');
}
