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

export const MythrilSpellSystem = {

    config: {
        throwCooldown: 20, // ticks (1 second)
        blastRadius: 4.5,
        damage: 6, // Base damage
        knockbackStrength: 2.0,
        energyRadius: 6, // Energy restoration radius
        energyAmount: 3, // Energy points restored (reduced)
        mythrilParticleCount: 25,
        explosionParticleCount: 40,
        trajectorySpeed: 1.2,
        maxDistance: 20,
        bounceCount: 2, // Number of bounces before exploding
        homingRange: 8, // Range to detect and home towards enemies
        mythrilBoostMultiplier: 1.5, // Extra effects with mythril armor
        chainRadius: 5, // Chain damage radius
        chainDamageMultiplier: 0.7, // Chain damage is 70% of original
        maxChainTargets: 3 // Maximum targets for chain damage
    },

    // Utility function for sending styled action bar messages
    sendActionBar(player, message, color = '§b') {
        try {
            player.onScreenDisplay.setActionBar(`${color}${message}`);
        } catch (error) {
            try {
                player.onScreenDisplay.setActionBar(message);
            } catch (e) {
                // Silent fail
            }
        }
    },

    handleSpellThrow(player, itemStack) {
        try {
            // Check cooldown
            const lastThrow = player.getDynamicProperty('myw:last_spell_throw') || 0;
            const currentTime = Date.now();

            if (currentTime - lastThrow < this.config.throwCooldown * 50) {
                const remainingTime = Math.ceil((this.config.throwCooldown * 50 - (currentTime - lastThrow)) / 1000);
                this.sendActionBar(player, `⏱ §6Mythril Spell Cooldown §8▸ §e${remainingTime}s remaining`, '§6');
                return false;
            }

            player.setDynamicProperty('myw:last_spell_throw', currentTime);

            // Check if player has mythril armor for bonuses
            const mythrilPower = this.getMythrilArmorCount(player);
            const hasFullSet = mythrilPower >= 4;

            // Create mythril spell projectile
            this.createMythrilProjectile(player, hasFullSet, mythrilPower);

            // Consume item
            const inventory = player.getComponent('minecraft:inventory');
            if (inventory) {
                const selectedSlot = player.selectedSlotIndex;
                const item = inventory.container.getItem(selectedSlot);
                if (item && item.typeId === 'myw:mythril_simple_spell' && item.amount > 1) {
                    inventory.container.setItem(selectedSlot, new ItemStack('myw:mythril_simple_spell', item.amount - 1));
                } else {
                    inventory.container.setItem(selectedSlot, undefined);
                }
            }

            // Feedback messages
            if (hasFullSet) {
                this.sendActionBar(player, '✨ §bMythril Spell §8▸ §eFull Set Mastery §7| §aHoming + Chain Magic', '§b');
            } else if (mythrilPower >= 2) {
                this.sendActionBar(player, '💫 §bMythril Spell §8▸ §eArmor Boost §7| §aEnhanced Chain Effects', '§b');
            } else {
                this.sendActionBar(player, '⚡ §bMythril Spell §8▸ §7Energy Projectile §7| §aBlast + Chain Damage', '§b');
            }

            return true;

        } catch (error) {
            this.sendActionBar(player, '⚠ §cSpell Error Occurred', '§c');
            return false;
        }
    },

    createMythrilProjectile(player, hasFullSet, mythrilPower) {
        try {
            const startLocation = {
                x: player.location.x,
                y: player.location.y + 1.6, // Eye level
                z: player.location.z
            };

            const viewDirection = player.getViewDirection();
            const velocity = {
                x: viewDirection.x * this.config.trajectorySpeed,
                y: viewDirection.y * this.config.trajectorySpeed,
                z: viewDirection.z * this.config.trajectorySpeed
            };

            // Enhanced projectile data
            const projectileData = {
                owner: player,
                location: { ...startLocation },
                velocity: { ...velocity },
                originalVelocity: { ...velocity },
                distance: 0,
                bounces: 0,
                hasFullSet,
                mythrilPower,
                age: 0,
                target: null,
                dimension: player.dimension
            };

            // Find initial target if has full set (homing ability)
            if (hasFullSet) {
                projectileData.target = this.findNearestEnemy(player, startLocation, this.config.homingRange);
            }

            // Start projectile flight
            this.flyProjectile(projectileData);

            // Launch effects
            this.createLaunchEffects(player.dimension, startLocation, hasFullSet);

        } catch (error) {
            // Error creating projectile
        }
    },

    flyProjectile(projectileData) {
        const flightInterval = system.runInterval(() => {
            try {
                projectileData.age++;

                // Update location
                projectileData.location.x += projectileData.velocity.x;
                projectileData.location.y += projectileData.velocity.y;
                projectileData.location.z += projectileData.velocity.z;

                projectileData.distance += Math.sqrt(
                    projectileData.velocity.x ** 2 +
                    projectileData.velocity.y ** 2 +
                    projectileData.velocity.z ** 2
                );

                // Homing behavior for full set users
                if (projectileData.hasFullSet && projectileData.target) {
                    this.applyHomingBehavior(projectileData);
                }

                // Create flight trail
                this.createFlightTrail(projectileData);

                // Check for collision or max distance
                if (this.checkCollision(projectileData) || projectileData.distance >= this.config.maxDistance) {
                    system.clearRun(flightInterval);
                    this.explodeDust(projectileData);
                    return;
                }

                // Check for bounce
                if (this.checkBounce(projectileData)) {
                    this.handleBounce(projectileData);
                }

                // Age limit (10 seconds max flight time)
                if (projectileData.age >= 200) {
                    system.clearRun(flightInterval);
                    this.explodeDust(projectileData);
                }

            } catch (error) {
                system.clearRun(flightInterval);
            }
        }, 1);
    },

    applyHomingBehavior(projectileData) {
        try {
            if (!projectileData.target || !projectileData.target.isValid()) {
                // Find new target
                projectileData.target = this.findNearestEnemy(
                    projectileData.owner,
                    projectileData.location,
                    this.config.homingRange
                );
                return;
            }

            const targetLocation = projectileData.target.location;

            // Calculate direction to target
            const toTarget = {
                x: targetLocation.x - projectileData.location.x,
                y: targetLocation.y + 0.5 - projectileData.location.y,
                z: targetLocation.z - projectileData.location.z
            };

            const distance = Math.sqrt(toTarget.x ** 2 + toTarget.y ** 2 + toTarget.z ** 2);
            if (distance > 0) {
                // Normalize and apply homing force (gentle curve, not instant lock-on)
                const homingStrength = 0.3;
                const normalizedTarget = {
                    x: toTarget.x / distance * homingStrength,
                    y: toTarget.y / distance * homingStrength,
                    z: toTarget.z / distance * homingStrength
                };

                // Blend current velocity with homing direction
                projectileData.velocity.x = projectileData.velocity.x * 0.8 + normalizedTarget.x;
                projectileData.velocity.y = projectileData.velocity.y * 0.8 + normalizedTarget.y;
                projectileData.velocity.z = projectileData.velocity.z * 0.8 + normalizedTarget.z;

                // Maintain speed
                const currentSpeed = Math.sqrt(
                    projectileData.velocity.x ** 2 +
                    projectileData.velocity.y ** 2 +
                    projectileData.velocity.z ** 2
                );

                if (currentSpeed > 0) {
                    const speedMultiplier = this.config.trajectorySpeed / currentSpeed;
                    projectileData.velocity.x *= speedMultiplier;
                    projectileData.velocity.y *= speedMultiplier;
                    projectileData.velocity.z *= speedMultiplier;
                }
            }

        } catch (error) {
            // Error with homing
        }
    },

    createFlightTrail(projectileData) {
        try {
            const location = projectileData.location;
            const dimension = projectileData.dimension;

            // Main mythril particle trail
            dimension.spawnParticle('myw:mythril_particle', {
                x: location.x + (Math.random() - 0.5) * 0.3,
                y: location.y + (Math.random() - 0.5) * 0.3,
                z: location.z + (Math.random() - 0.5) * 0.3
            });

            // Enhanced effects for full set users
            if (projectileData.hasFullSet) {
                dimension.spawnParticle('myw:mythril_particle_serpentine', {
                    x: location.x + (Math.random() - 0.5) * 0.5,
                    y: location.y + (Math.random() - 0.5) * 0.5,
                    z: location.z + (Math.random() - 0.5) * 0.5
                });

                // Homing indicator particles
                if (projectileData.target && projectileData.target.isValid()) {
                    const targetLoc = projectileData.target.location;
                    const steps = 3;
                    for (let i = 1; i <= steps; i++) {
                        const progress = i / steps;
                        const trailLoc = {
                            x: location.x + (targetLoc.x - location.x) * progress * 0.3,
                            y: location.y + (targetLoc.y - location.y) * progress * 0.3,
                            z: location.z + (targetLoc.z - location.z) * progress * 0.3
                        };

                        system.runTimeout(() => {
                            try {
                                dimension.spawnParticle('myw:mythril_particle_minimalist', trailLoc);
                            } catch (error) {
                                // Error with target trail
                            }
                        }, i * 2);
                    }
                }
            }

        } catch (error) {
            // Error creating trail
        }
    },

    checkCollision(projectileData) {
        try {
            const location = projectileData.location;
            const dimension = projectileData.dimension;

            // Check for entity collision
            const nearbyEntities = dimension.getEntitiesAtBlockLocation(location);
            for (const entity of nearbyEntities) {
                if (entity.id !== projectileData.owner.id && entity.typeId !== 'minecraft:item') {
                    return true;
                }
            }

            // Check for block collision
            const block = dimension.getBlock(location);
            if (block && !block.isAir) {
                return true;
            }

            return false;

        } catch (error) {
            return true; // Assume collision on error
        }
    },

    checkBounce(projectileData) {
        try {
            if (projectileData.bounces >= this.config.bounceCount) {
                return false;
            }

            const location = projectileData.location;
            const dimension = projectileData.dimension;

            // Check if near ground for bounce
            const blockBelow = dimension.getBlock({
                x: Math.floor(location.x),
                y: Math.floor(location.y) - 1,
                z: Math.floor(location.z)
            });

            return blockBelow && !blockBelow.isAir && location.y <= Math.floor(location.y) + 0.1;

        } catch (error) {
            return false;
        }
    },

    handleBounce(projectileData) {
        try {
            projectileData.bounces++;

            // Reverse Y velocity and reduce overall speed
            projectileData.velocity.y = Math.abs(projectileData.velocity.y) * 0.7;
            projectileData.velocity.x *= 0.8;
            projectileData.velocity.z *= 0.8;

            // Bounce effects
            this.createBounceEffects(projectileData.dimension, projectileData.location, projectileData.hasFullSet);

            // Sound effect (if available)
            try {
                projectileData.dimension.playSound('block.amethyst_block.hit', projectileData.location, { volume: 0.5 });
            } catch (error) {
                // No sound available
            }

        } catch (error) {
            // Error with bounce
        }
    },

    explodeDust(projectileData) {
        try {
            const location = projectileData.location;
            const dimension = projectileData.dimension;
            const owner = projectileData.owner;

            // Calculate damage based on mythril power
            const baseDamage = this.config.damage;
            const bonusDamage = projectileData.mythrilPower * 1.5;
            const totalDamage = baseDamage + bonusDamage;

            // Create explosion effects
            this.createExplosionEffects(dimension, location, projectileData.hasFullSet);

            // Damage and knockback nearby entities
            this.damageNearbyEntities(dimension, location, totalDamage, owner, projectileData.hasFullSet);

            // Restore energy to nearby players with mythril armor
            this.restoreNearbyEnergy(dimension, location, owner, projectileData.mythrilPower);

            // Special effects for full set users
            if (projectileData.hasFullSet) {
                this.createFullSetExplosionEffects(dimension, location);
                this.applyFullSetBonuses(dimension, location, owner);
            }

            // Explosion sound
            try {
                dimension.playSound('entity.generic.explode', location, { volume: 0.8, pitch: 1.2 });
            } catch (error) {
                // No sound available
            }

        } catch (error) {
            // Error with explosion
        }
    },

    damageNearbyEntities(dimension, location, damage, owner, hasFullSet) {
        try {
            const radius = this.config.blastRadius;
            const knockbackStrength = this.config.knockbackStrength;
            const damagedEntities = new Set();
            const chainCandidates = [];

            // Find all entities in blast radius
            const nearbyEntities = dimension.getEntities({
                location: location,
                maxDistance: radius,
                excludeTypes: ['minecraft:item']
            });

            nearbyEntities.forEach(entity => {
                if (entity.id === owner.id) return; // Don't damage the owner

                const distance = this.getDistance(entity.location, location);
                if (distance > radius) return;

                // Calculate distance-based damage falloff
                const falloff = Math.max(0.2, 1 - (distance / radius));
                const finalDamage = damage * falloff;

                try {
                    // Apply damage
                    entity.applyDamage(finalDamage, { cause: EntityDamageCause.magic });
                    damagedEntities.add(entity);

                    // Add to chain candidates for chain damage system
                    chainCandidates.push({
                        entity: entity,
                        damage: finalDamage,
                        location: entity.location
                    });

                    // Apply knockback
                    const knockbackDirection = {
                        x: entity.location.x - location.x,
                        y: Math.max(0.3, entity.location.y - location.y + 0.5),
                        z: entity.location.z - location.z
                    };

                    const knockbackDistance = Math.sqrt(
                        knockbackDirection.x ** 2 +
                        knockbackDirection.y ** 2 +
                        knockbackDirection.z ** 2
                    );

                    if (knockbackDistance > 0) {
                        const normalizedKnockback = {
                            x: knockbackDirection.x / knockbackDistance * knockbackStrength * falloff,
                            y: knockbackDirection.y / knockbackDistance * knockbackStrength * falloff,
                            z: knockbackDirection.z / knockbackDistance * knockbackStrength * falloff
                        };

                        entity.applyKnockback(
                            normalizedKnockback.x,
                            normalizedKnockback.z,
                            Math.abs(normalizedKnockback.x) + Math.abs(normalizedKnockback.z),
                            Math.max(0.3, normalizedKnockback.y)
                        );
                    }

                    // Full set bonus: apply weakness effect to enemies
                    if (hasFullSet && entity.typeId.includes('monster')) {
                        entity.addEffect('weakness', 100, { amplifier: 1 });
                    }

                } catch (entityError) {
                    // Error damaging specific entity
                }
            });

            // Chain damage system - only if we actually hit someone
            if (chainCandidates.length > 0) {
                this.applyChainDamage(dimension, chainCandidates, damage, owner, hasFullSet, damagedEntities);
            }

        } catch (error) {
            // Error with damage system
        }
    },

    applyChainDamage(dimension, chainCandidates, originalDamage, owner, hasFullSet, alreadyDamaged) {
        try {
            const chainRadius = this.config.chainRadius;
            const chainDamage = originalDamage * this.config.chainDamageMultiplier;
            let chainsProcessed = 0;

            chainCandidates.forEach(source => {
                if (chainsProcessed >= this.config.maxChainTargets) return;

                // Find nearby entities for chain damage
                const chainTargets = dimension.getEntities({
                    location: source.location,
                    maxDistance: chainRadius,
                    excludeTypes: ['minecraft:item', 'minecraft:player']
                });

                let validTargets = [];
                chainTargets.forEach(target => {
                    // Don't chain to already damaged entities or the owner
                    if (!alreadyDamaged.has(target) && target.id !== owner.id && target.id !== source.entity.id) {
                        const distance = this.getDistance(target.location, source.location);
                        validTargets.push({
                            entity: target,
                            distance: distance,
                            sourceLocation: source.location
                        });
                    }
                });

                // Sort by distance and take closest targets
                validTargets.sort((a, b) => a.distance - b.distance);
                const targetsToChain = validTargets.slice(0, Math.min(2, this.config.maxChainTargets - chainsProcessed));

                targetsToChain.forEach((target, index) => {
                    system.runTimeout(() => {
                        try {
                            // Create chain lightning effect
                            this.createChainLightningEffect(dimension, target.sourceLocation, target.entity.location, hasFullSet);

                            // Apply chain damage
                            const finalChainDamage = chainDamage * (hasFullSet ? 1.2 : 1.0);
                            target.entity.applyDamage(finalChainDamage, { cause: EntityDamageCause.magic });

                            // Mark as damaged to prevent infinite chains
                            alreadyDamaged.add(target.entity);

                            // Chain visual effects
                            this.createChainDamageEffects(dimension, target.entity.location, hasFullSet);

                            chainsProcessed++;

                        } catch (error) {
                            // Error with chain damage
                        }
                    }, index * 8); // Stagger chain effects
                });

                // Show chain damage message to owner
                if (targetsToChain.length > 0) {
                    system.runTimeout(() => {
                        this.sendActionBar(owner, `⚡ §6Chain Magic §8▸ §e+${targetsToChain.length} targets §7| §b${Math.round(chainDamage)} damage each`, '§6');
                    }, 15);
                }
            });

        } catch (error) {
            // Error with chain damage system
        }
    },

    createChainLightningEffect(dimension, fromLocation, toLocation, hasFullSet) {
        try {
            const steps = hasFullSet ? 8 : 6;
            for (let i = 0; i <= steps; i++) {
                const progress = i / steps;

                // Add some random variation to make it look like lightning
                const randomOffset = {
                    x: (Math.random() - 0.5) * 0.4,
                    y: (Math.random() - 0.5) * 0.3,
                    z: (Math.random() - 0.5) * 0.4
                };

                const lightningLocation = {
                    x: fromLocation.x + (toLocation.x - fromLocation.x) * progress + randomOffset.x,
                    y: fromLocation.y + (toLocation.y - fromLocation.y) * progress + randomOffset.y + 0.5,
                    z: fromLocation.z + (toLocation.z - fromLocation.z) * progress + randomOffset.z
                };

                system.runTimeout(() => {
                    try {
                        const particleType = hasFullSet ? 'myw:mythril_particle_serpentine' : 'myw:mythril_particle';
                        dimension.spawnParticle(particleType, lightningLocation);
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 1);
            }
        } catch (error) {
            // Error creating chain lightning
        }
    },

    createChainDamageEffects(dimension, location, hasFullSet) {
        try {
            // Chain impact burst
            const particleCount = hasFullSet ? 12 : 8;
            for (let i = 0; i < particleCount; i++) {
                const angle = (i / particleCount) * Math.PI * 2;
                const radius = 1.2;

                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + 0.5 + Math.random() * 0.5,
                            z: location.z + Math.sin(angle) * radius
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }

            // Central impact
            for (let i = 0; i < 4; i++) {
                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle_minimalist', {
                            x: location.x + (Math.random() - 0.5) * 0.6,
                            y: location.y + 0.5 + (Math.random() - 0.5) * 0.6,
                            z: location.z + (Math.random() - 0.5) * 0.6
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 3);
            }

        } catch (error) {
            // Error creating chain effects
        }
    },

    restoreNearbyEnergy(dimension, location, owner, mythrilPower) {
        try {
            const radius = this.config.energyRadius;
            const baseEnergy = this.config.energyAmount;
            const bonusEnergy = Math.floor(mythrilPower / 2); // Much smaller bonus
            const totalEnergy = baseEnergy + bonusEnergy;

            // Find players in energy restoration radius
            const nearbyPlayers = dimension.getPlayers({
                location: location,
                maxDistance: radius
            });

            nearbyPlayers.forEach(player => {
                try {
                    // Check if player has mythril armor
                    const playerMythrilCount = this.getMythrilArmorCount(player);

                    if (playerMythrilCount > 0) {
                        // Restore health (much more conservative)
                        player.addEffect('regeneration', 40, { // 2 seconds instead of 5
                            amplifier: Math.min(1, Math.floor(playerMythrilCount / 3)), // Max amplifier 1
                            showParticles: false
                        });

                        // Restore absorption hearts (reduced)
                        if (playerMythrilCount >= 3) {
                            player.addEffect('absorption', 100, { // 5 seconds instead of 10
                                amplifier: 0, // Only 1 absorption heart
                                showParticles: false
                            });
                        }

                        // Energy restoration message
                        if (player.id === owner.id) {
                            this.sendActionBar(player, `💙 §bSpell Energy §8▸ §a+${totalEnergy} points §7| §eLight healing`, '§b');
                        } else {
                            this.sendActionBar(player, `💫 §bMythril Blessing §8▸ §aEnergy from ally spell §7| §eTeam bonus`, '§b');
                        }

                        // Create energy restoration particles around player
                        this.createEnergyRestorationEffects(dimension, player.location);
                    }

                } catch (playerError) {
                    // Error restoring energy to specific player
                }
            });

        } catch (error) {
            // Error with energy restoration
        }
    },

    // VISUAL EFFECTS
    createLaunchEffects(dimension, location, hasFullSet) {
        try {
            // Launch burst
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                const particleLocation = {
                    x: location.x + Math.cos(angle) * 0.5,
                    y: location.y,
                    z: location.z + Math.sin(angle) * 0.5
                };

                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle', particleLocation);
                        if (hasFullSet) {
                            dimension.spawnParticle('myw:mythril_particle_serpentine', particleLocation);
                        }
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 2);
            }

        } catch (error) {
            // Error creating launch effects
        }
    },

    createBounceEffects(dimension, location, hasFullSet) {
        try {
            // Bounce particles
            for (let i = 0; i < 6; i++) {
                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle_minimalist', {
                            x: location.x + (Math.random() - 0.5) * 1.0,
                            y: location.y + Math.random() * 0.5,
                            z: location.z + (Math.random() - 0.5) * 1.0
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 3);
            }

        } catch (error) {
            // Error creating bounce effects
        }
    },

    createExplosionEffects(dimension, location, hasFullSet) {
        try {
            const particleCount = hasFullSet ? this.config.explosionParticleCount * 1.5 : this.config.explosionParticleCount;

            // Main explosion burst
            for (let i = 0; i < particleCount; i++) {
                const angle = (Math.random() * Math.PI * 2);
                const elevation = (Math.random() - 0.5) * Math.PI;
                const distance = Math.random() * this.config.blastRadius;

                const particleLocation = {
                    x: location.x + Math.cos(angle) * Math.cos(elevation) * distance,
                    y: location.y + Math.sin(elevation) * distance,
                    z: location.z + Math.sin(angle) * Math.cos(elevation) * distance
                };

                const delay = Math.random() * 20;
                system.runTimeout(() => {
                    try {
                        const particleType = Math.random() > 0.6 ? 'myw:mythril_particle' : 'myw:mythril_particle_minimalist';
                        dimension.spawnParticle(particleType, particleLocation);
                    } catch (error) {
                        // Error with particles
                    }
                }, delay);
            }

            // Central explosion core
            for (let i = 0; i < 5; i++) {
                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: location.x + (Math.random() - 0.5) * 0.5,
                            y: location.y + (Math.random() - 0.5) * 0.5,
                            z: location.z + (Math.random() - 0.5) * 0.5
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 4);
            }

        } catch (error) {
            // Error creating explosion effects
        }
    },

    createFullSetExplosionEffects(dimension, location) {
        try {
            // Enhanced explosion ring
            for (let ring = 1; ring <= 3; ring++) {
                const radius = ring * 1.5;
                const particlesInRing = ring * 8;

                for (let i = 0; i < particlesInRing; i++) {
                    const angle = (i / particlesInRing) * Math.PI * 2;
                    const ringLocation = {
                        x: location.x + Math.cos(angle) * radius,
                        y: location.y + Math.sin(ring * 0.5) * 0.5,
                        z: location.z + Math.sin(angle) * radius
                    };

                    system.runTimeout(() => {
                        try {
                            dimension.spawnParticle('myw:mythril_particle_serpentine', ringLocation);
                        } catch (error) {
                            // Error with particles
                        }
                    }, ring * 8 + i * 2);
                }
            }

        } catch (error) {
            // Error creating full set effects
        }
    },

    createEnergyRestorationEffects(dimension, location) {
        try {
            // Energy spiral around player
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                const height = i * 0.2;
                const radius = 1.5 - (i * 0.1);

                system.runTimeout(() => {
                    try {
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + height,
                            z: location.z + Math.sin(angle) * radius
                        });
                    } catch (error) {
                        // Error with particles
                    }
                }, i * 5);
            }

        } catch (error) {
            // Error creating energy effects
        }
    },

    applyFullSetBonuses(dimension, location, owner) {
        try {
            // Apply speed boost to owner
            owner.addEffect('speed', 200, {
                amplifier: 1,
                showParticles: false
            });

            // Apply resistance
            owner.addEffect('resistance', 100, {
                amplifier: 0,
                showParticles: false
            });

            this.sendActionBar(owner, '👑 §6Full Set Mastery §8▸ §eSpeed + Resistance §7| §bMythril Supremacy', '§6');

        } catch (error) {
            // Error applying bonuses
        }
    },

    // UTILITY FUNCTIONS
    getMythrilArmorCount(player) {
        try {
            const equippableComp = player.getComponent('minecraft:equippable');
            if (!equippableComp) return 0;

            let mythrilCount = 0;
            const armorSlots = [EquipmentSlot.Head, EquipmentSlot.Chest, EquipmentSlot.Legs, EquipmentSlot.Feet];

            armorSlots.forEach(slot => {
                const item = equippableComp.getEquipment(slot);
                if (item && item.typeId.includes('myw:mythril')) {
                    mythrilCount++;
                }
            });

            return mythrilCount;
        } catch (error) {
            return 0;
        }
    },

    findNearestEnemy(player, location, range) {
        try {
            const dimension = player.dimension;
            const entities = dimension.getEntities({
                location: location,
                maxDistance: range,
                excludeTypes: ['minecraft:player', 'minecraft:item']
            });

            let nearestEnemy = null;
            let shortestDistance = range + 1;

            entities.forEach(entity => {
                if (entity.id === player.id) return;

                // Prefer hostile mobs
                const isHostile = entity.typeId.includes('zombie') ||
                    entity.typeId.includes('skeleton') ||
                    entity.typeId.includes('creeper') ||
                    entity.typeId.includes('spider') ||
                    entity.typeId.includes('enderman') ||
                    entity.hasComponent('minecraft:angry');

                const distance = this.getDistance(entity.location, location);

                if (isHostile && distance < shortestDistance) {
                    nearestEnemy = entity;
                    shortestDistance = distance;
                }
            });

            // If no hostile mobs, target any mob except players and items
            if (!nearestEnemy) {
                entities.forEach(entity => {
                    if (entity.id === player.id) return;

                    const distance = this.getDistance(entity.location, location);
                    if (distance < shortestDistance) {
                        nearestEnemy = entity;
                        shortestDistance = distance;
                    }
                });
            }

            return nearestEnemy;

        } catch (error) {
            return null;
        }
    },

    getDistance(loc1, loc2) {
        return Math.sqrt(
            (loc1.x - loc2.x) ** 2 +
            (loc1.y - loc2.y) ** 2 +
            (loc1.z - loc2.z) ** 2
        );
    }
};

// Register mythril simple spell component
export function registerMythrilSimpleSpell(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_simple_spell', {
        onUse(eventData) {
            const { itemStack, source } = eventData;
            MythrilSpellSystem.handleSpellThrow(source, itemStack);
        }
    });
}

// Initialize spell systems
export function initializeSpellSystems() {
    // Show initialization message
    system.runTimeout(() => {
        world.getAllPlayers().forEach(player => {
            MythrilSpellSystem.sendActionBar(player, '🔮 §bMythril Spell System §8▸ §aOnline §7| §eChain Magic & Homing', '§b');
        });
    }, 60);

    world.sendMessage('[OK] Mythril Spell System initialized');
}