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

export const AncientMythrilStaffSystem = {

    config: {
        // Configuración del poder cósmico
        cosmicPower: {
            baseRadius: 35,
            maxCharges: 7,
            chargeTime: 40, // ticks para carga completa
            damagePerCharge: 15,
            maxDamage: 150
        },

        // Sistema de devastación orbital
        orbitalStrike: {
            orbitRadius: 15,
            orbitCount: 12,
            orbitDamage: 25,
            orbitDuration: 200, // 10 segundos
            homingSpeed: 2.5,
            chainRadius: 8
        },

        // Nova mítica
        mythrilNova: {
            waveCount: 5,
            waveRadius: 50,
            waveDamage: 35,
            waveDelay: 10,
            voidRadius: 20,
            temporalFreeze: 60 // ticks de congelación temporal
        },

        // Invocación ancestral
        ancientSummon: {
            guardianCount: 3,
            guardianDuration: 400, // 20 segundos
            guardianDamage: 20,
            guardianHealth: 100,
            auraRadius: 25
        },

        // Transformación divina
        divineForm: {
            duration: 600, // 30 segundos
            damageMultiplier: 3.0,
            speedBoost: 3,
            regeneration: 2,
            flightHeight: 15
        }
    },

    playerStates: new Map(),
    activeOrbitals: new Map(),
    ancientGuardians: new Set(),
    cosmicRifts: new Map(),

    // Sistema principal de activación
    handleStaffUse(player, itemStack) {
        try {
            const playerId = player.id;
            let state = this.playerStates.get(playerId) || this.createNewState(playerId);

            const currentTime = Date.now();
            const isCharging = state.isCharging;
            const isTransformed = state.divineFormActive;

            // Si está en forma divina, ejecuta ataque supremo
            if (isTransformed) {
                this.executeDivineAttack(player, state);
                return;
            }

            // Sistema de carga
            if (!isCharging) {
                this.startCharging(player, state);
            } else {
                const chargeTime = currentTime - state.chargeStartTime;
                const charges = Math.min(Math.floor(chargeTime / (this.config.cosmicPower.chargeTime * 50)),
                    this.config.cosmicPower.maxCharges);

                if (charges > 0) {
                    this.releaseCosmicPower(player, charges, state);
                }
            }

            this.playerStates.set(playerId, state);

        } catch (error) {
            this.sendStaffMessage(player, '§c⚠ Error en el sistema ancestral');
        }
    },

    // Inicia el proceso de carga
    startCharging(player, state) {
        state.isCharging = true;
        state.chargeStartTime = Date.now();
        state.chargeInterval = system.runInterval(() => {
            try {
                const chargeTime = Date.now() - state.chargeStartTime;
                const charges = Math.min(Math.floor(chargeTime / (this.config.cosmicPower.chargeTime * 50)),
                    this.config.cosmicPower.maxCharges);

                // Efectos visuales de carga
                this.createChargingEffects(player, charges);

                // Mensaje de estado
                const chargeBar = this.createChargeBar(charges);
                this.sendStaffMessage(player, `§b⚡ Ancient Power ${chargeBar} §e[${charges}/${this.config.cosmicPower.maxCharges}]`);

                // Auto-release en carga máxima
                if (charges >= this.config.cosmicPower.maxCharges) {
                    system.clearRun(state.chargeInterval);
                    this.releaseCosmicPower(player, charges, state);
                }

            } catch (error) {
                system.clearRun(state.chargeInterval);
            }
        }, 5);
    },

    // Libera el poder cósmico acumulado
    releaseCosmicPower(player, charges, state) {
        try {
            state.isCharging = false;
            if (state.chargeInterval) {
                system.clearRun(state.chargeInterval);
            }

            // Incrementa combo
            state.comboCount++;
            state.lastAttackTime = Date.now();

            // Determina el tipo de ataque basado en cargas y combo
            if (charges >= 7 && state.comboCount >= 5) {
                // ULTIMATE: Transformación Divina
                this.activateDivineForm(player, state);
            } else if (charges >= 5) {
                // Nova Mítica
                this.executeMythrilNova(player, charges);
            } else if (charges >= 3) {
                // Ataque Orbital
                this.executeOrbitalStrike(player, charges);
            } else {
                // Devastación Básica
                this.executeBasicDevastation(player, charges);
            }

            // Invocación ancestral en combos altos
            if (state.comboCount >= 3 && Math.random() < 0.5) {
                this.summonAncientGuardian(player);
            }

            // Reset combo después de tiempo
            system.runTimeout(() => {
                if (Date.now() - state.lastAttackTime > 5000) {
                    state.comboCount = 0;
                }
            }, 100);

        } catch (error) {
            this.sendStaffMessage(player, '§c⚠ Error liberando poder');
        }
    },

    // ATAQUE BÁSICO: Devastación
    executeBasicDevastation(player, charges) {
        try {
            const dimension = player.dimension;
            const origin = player.location;
            const damage = this.config.cosmicPower.damagePerCharge * charges;
            const radius = this.config.cosmicPower.baseRadius * (1 + charges * 0.2);

            // Onda de choque principal
            this.createShockwave(dimension, origin, radius, damage);

            // Rayos míticos cayendo del cielo
            for (let i = 0; i < charges * 3; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const dist = Math.random() * radius;
                    const strikeLocation = {
                        x: origin.x + Math.cos(angle) * dist,
                        y: origin.y + 20,
                        z: origin.z + Math.sin(angle) * dist
                    };

                    this.createMythrilLightning(dimension, strikeLocation, damage / 2);
                }, i * 5);
            }

            this.sendStaffMessage(player, `§6⚔ DEVASTATION §8▸ §e${charges} charges §7| §c${damage} damage`);

        } catch (error) {
            // Error en devastación
        }
    },

    // ATAQUE ORBITAL: Esferas devastadoras
    executeOrbitalStrike(player, charges) {
        try {
            const playerId = player.id;
            const dimension = player.dimension;
            const orbitCount = this.config.orbitalStrike.orbitCount;

            // Limpia orbitales anteriores
            if (this.activeOrbitals.has(playerId)) {
                const oldOrbital = this.activeOrbitals.get(playerId);
                if (oldOrbital.interval) system.clearRun(oldOrbital.interval);
            }

            // Crea nuevos orbitales
            const orbitals = [];
            for (let i = 0; i < orbitCount; i++) {
                orbitals.push({
                    angle: (i / orbitCount) * Math.PI * 2,
                    height: Math.sin(i * 0.5) * 3,
                    radius: this.config.orbitalStrike.orbitRadius,
                    target: null,
                    age: 0
                });
            }

            const orbitalData = {
                orbitals: orbitals,
                player: player,
                interval: null
            };

            // Sistema de actualización orbital
            orbitalData.interval = system.runInterval(() => {
                try {
                    if (!player.isValid()) {
                        system.clearRun(orbitalData.interval);
                        this.activeOrbitals.delete(playerId);
                        return;
                    }

                    const playerLoc = player.location;

                    orbitals.forEach((orbital, index) => {
                        orbital.age++;
                        orbital.angle += 0.15; // Rotación

                        // Posición orbital
                        const orbitalPos = {
                            x: playerLoc.x + Math.cos(orbital.angle) * orbital.radius,
                            y: playerLoc.y + 2 + orbital.height,
                            z: playerLoc.z + Math.sin(orbital.angle) * orbital.radius
                        };

                        // Busca objetivos cercanos
                        if (orbital.age % 20 === 0) {
                            orbital.target = this.findNearestTarget(dimension, orbitalPos, 15, player);
                        }

                        // Si tiene objetivo, dispara proyectil
                        if (orbital.target && orbital.target.isValid() && orbital.age % 10 === 0) {
                            this.fireOrbitalProjectile(dimension, orbitalPos, orbital.target, charges);
                        }

                        // Efectos visuales
                        this.createOrbitalEffects(dimension, orbitalPos, index);
                    });

                    // Termina después de la duración
                    if (orbitals[0].age >= this.config.orbitalStrike.orbitDuration) {
                        system.clearRun(orbitalData.interval);
                        this.activeOrbitals.delete(playerId);
                        this.executeOrbitalFinale(player, dimension, playerLoc);
                    }

                } catch (error) {
                    system.clearRun(orbitalData.interval);
                }
            }, 2);

            this.activeOrbitals.set(playerId, orbitalData);
            this.sendStaffMessage(player, `§5⭐ ORBITAL STRIKE §8▸ §d${orbitCount} orbitals §7| §eSeeking targets`);

        } catch (error) {
            // Error en ataque orbital
        }
    },

    // NOVA MÍTICA: Explosión de ondas devastadoras
    executeMythrilNova(player, charges) {
        try {
            const dimension = player.dimension;
            const origin = player.location;
            const waveCount = this.config.mythrilNova.waveCount;

            // Congela el tiempo para enemigos cercanos
            this.applyTemporalFreeze(dimension, origin, this.config.mythrilNova.voidRadius);

            // Crea el vórtice central
            this.createMythrilVortex(dimension, origin);

            // Ondas de nova expansivas
            for (let wave = 0; wave < waveCount; wave++) {
                system.runTimeout(() => {
                    const waveRadius = this.config.mythrilNova.waveRadius * ((wave + 1) / waveCount);
                    const waveDamage = this.config.mythrilNova.waveDamage * (1 + charges * 0.2);

                    // Crea anillo de devastación
                    this.createNovaRing(dimension, origin, waveRadius, waveDamage, wave);

                    // Levanta bloques y entidades
                    this.createGravityWell(dimension, origin, waveRadius);

                }, wave * this.config.mythrilNova.waveDelay);
            }

            // Implosión final
            system.runTimeout(() => {
                this.createNovaImplosion(dimension, origin, charges);
            }, waveCount * this.config.mythrilNova.waveDelay + 20);

            this.sendStaffMessage(player, `§d✦ MYTHRIL NOVA §8▸ §5${waveCount} waves §7| §cTemporal disruption`);

        } catch (error) {
            // Error en nova
        }
    },

    // TRANSFORMACIÓN DIVINA: Forma suprema
    activateDivineForm(player, state) {
        try {
            if (state.divineFormActive) return;

            state.divineFormActive = true;
            state.divineFormStart = Date.now();

            const dimension = player.dimension;
            const duration = this.config.divineForm.duration;

            // Efectos de transformación
            this.createTransformationEffects(player);

            // Aplica buffs divinos
            player.addEffect('speed', duration, { amplifier: this.config.divineForm.speedBoost });
            player.addEffect('strength', duration, { amplifier: 3 });
            player.addEffect('resistance', duration, { amplifier: 2 });
            player.addEffect('regeneration', duration, { amplifier: this.config.divineForm.regeneration });
            player.addEffect('jump_boost', duration, { amplifier: 3 });
            player.addEffect('slow_falling', duration, { amplifier: 1 });

            // Aura divina continua
            state.divineAuraInterval = system.runInterval(() => {
                try {
                    if (!player.isValid() || !state.divineFormActive) {
                        system.clearRun(state.divineAuraInterval);
                        return;
                    }

                    // Aura de daño
                    this.createDivineAura(player);

                    // Regeneración de salud
                    const health = player.getComponent('minecraft:health');
                    if (health && health.currentValue < health.effectiveMax) {
                        health.setCurrentValue(Math.min(health.currentValue + 2, health.effectiveMax));
                    }

                    // Mensaje de poder
                    const remainingTime = Math.ceil((duration * 50 - (Date.now() - state.divineFormStart)) / 1000);
                    this.sendStaffMessage(player, `§6⚡ DIVINE FORM §8▸ §e${remainingTime}s §7| §cUnlimited Power`);

                } catch (error) {
                    system.clearRun(state.divineAuraInterval);
                }
            }, 10);

            // Termina la transformación
            system.runTimeout(() => {
                state.divineFormActive = false;
                if (state.divineAuraInterval) {
                    system.clearRun(state.divineAuraInterval);
                }
                this.sendStaffMessage(player, `§7Divine form ended...`);
            }, duration);

            this.sendStaffMessage(player, `§6♔ DIVINE TRANSFORMATION §8▸ §eAscended §7| §cGodlike Power`);

        } catch (error) {
            // Error en transformación
        }
    },

    // ATAQUE DIVINO: Poder supremo en forma divina
    executeDivineAttack(player, state) {
        try {
            const dimension = player.dimension;
            const origin = player.location;

            // Crea una esfera de aniquilación
            this.createAnnihilationSphere(dimension, origin);

            // Rayos divinos en todas direcciones
            for (let i = 0; i < 16; i++) {
                const angle = (i / 16) * Math.PI * 2;
                system.runTimeout(() => {
                    this.createDivineBeam(dimension, origin, angle);
                }, i * 2);
            }

            // Meteoros míticos
            this.summonMythrilMeteors(dimension, origin, 8);

            // Daño masivo
            const entities = dimension.getEntities({
                location: origin,
                maxDistance: 50,
                excludeTypes: ['minecraft:player']
            });

            entities.forEach(entity => {
                if (entity.id !== player.id) {
                    try {
                        entity.applyDamage(100, { cause: EntityDamageCause.magic });

                        // Desintegración para enemigos débiles
                        const health = entity.getComponent('minecraft:health');
                        if (health && health.currentValue <= 20) {
                            this.disintegrateEntity(dimension, entity);
                        }
                    } catch (error) {
                        // Error dañando entidad
                    }
                }
            });

            this.sendStaffMessage(player, `§6☄ DIVINE WRATH §8▸ §cAnnihilation §7| §eObliterate All`);

        } catch (error) {
            // Error en ataque divino
        }
    },

    // INVOCACIÓN: Guardian Ancestral
    summonAncientGuardian(player) {
        try {
            const dimension = player.dimension;
            const spawnPos = {
                x: player.location.x + (Math.random() - 0.5) * 10,
                y: player.location.y + 2,
                z: player.location.z + (Math.random() - 0.5) * 10
            };

            // Crea efectos de invocación
            this.createSummonPortal(dimension, spawnPos);

            // Simula un guardian con partículas persistentes
            const guardianData = {
                location: { ...spawnPos },
                owner: player,
                health: this.config.ancientSummon.guardianHealth,
                age: 0,
                target: null,
                dimension: dimension
            };

            const guardianInterval = system.runInterval(() => {
                try {
                    guardianData.age++;

                    // Busca objetivo
                    if (guardianData.age % 20 === 0) {
                        guardianData.target = this.findNearestTarget(
                            dimension,
                            guardianData.location,
                            20,
                            player
                        );
                    }

                    // Movimiento hacia objetivo
                    if (guardianData.target && guardianData.target.isValid()) {
                        const targetLoc = guardianData.target.location;
                        const direction = {
                            x: targetLoc.x - guardianData.location.x,
                            y: targetLoc.y - guardianData.location.y,
                            z: targetLoc.z - guardianData.location.z
                        };

                        const distance = Math.sqrt(direction.x ** 2 + direction.y ** 2 + direction.z ** 2);
                        if (distance > 2) {
                            guardianData.location.x += (direction.x / distance) * 0.5;
                            guardianData.location.y += (direction.y / distance) * 0.3;
                            guardianData.location.z += (direction.z / distance) * 0.5;
                        }

                        // Ataque si está cerca
                        if (distance < 5 && guardianData.age % 30 === 0) {
                            this.guardianAttack(dimension, guardianData);
                        }
                    }

                    // Efectos visuales del guardian
                    this.createGuardianEffects(dimension, guardianData.location);

                    // Expira después de la duración
                    if (guardianData.age >= this.config.ancientSummon.guardianDuration) {
                        system.clearRun(guardianInterval);
                        this.createGuardianDespawn(dimension, guardianData.location);
                    }

                } catch (error) {
                    system.clearRun(guardianInterval);
                }
            }, 2);

            this.ancientGuardians.add(guardianInterval);

        } catch (error) {
            // Error invocando guardian
        }
    },

    // SISTEMA DE EFECTOS VISUALES MASIVOS

    createChargingEffects(player, charges) {
        try {
            const dimension = player.dimension;
            const location = player.location;

            // Anillos de carga ascendentes
            for (let ring = 0; ring < charges; ring++) {
                const radius = 2 + ring * 0.5;
                const height = ring * 0.7;
                const particles = 8 + ring * 2;

                for (let i = 0; i < particles; i++) {
                    const angle = (i / particles) * Math.PI * 2;
                    dimension.spawnParticle('myw:mythril_particle_serpentine', {
                        x: location.x + Math.cos(angle) * radius,
                        y: location.y + height,
                        z: location.z + Math.sin(angle) * radius
                    });
                }
            }

            // Rayos de energía convergentes
            if (charges >= 3) {
                for (let i = 0; i < 6; i++) {
                    const angle = Math.random() * Math.PI * 2;
                    const startRadius = 10;
                    const startPos = {
                        x: location.x + Math.cos(angle) * startRadius,
                        y: location.y + 10,
                        z: location.z + Math.sin(angle) * startRadius
                    };

                    this.createEnergyBeam(dimension, startPos, location);
                }
            }

        } catch (error) {
            // Error en efectos
        }
    },

    createShockwave(dimension, origin, radius, damage) {
        try {
            // Onda expansiva con múltiples anillos
            for (let ring = 1; ring <= 5; ring++) {
                system.runTimeout(() => {
                    const ringRadius = (radius / 5) * ring;
                    const particleCount = Math.floor(ringRadius * 4);

                    for (let i = 0; i < particleCount; i++) {
                        const angle = (i / particleCount) * Math.PI * 2;
                        const ringPos = {
                            x: origin.x + Math.cos(angle) * ringRadius,
                            y: origin.y + 0.1,
                            z: origin.z + Math.sin(angle) * ringRadius
                        };

                        dimension.spawnParticle('myw:mythril_particle', ringPos);

                        // Columnas de energía
                        if (i % 4 === 0) {
                            for (let h = 0; h < 8; h++) {
                                system.runTimeout(() => {
                                    dimension.spawnParticle('myw:mythril_particle_serpentine', {
                                        x: ringPos.x,
                                        y: ringPos.y + h * 0.5,
                                        z: ringPos.z
                                    });
                                }, h * 2);
                            }
                        }
                    }

                    // Daño en el anillo
                    const entities = dimension.getEntities({
                        location: origin,
                        minDistance: ring > 1 ? (ringRadius - radius / 5) : 0,
                        maxDistance: ringRadius
                    });

                    entities.forEach(entity => {
                        if (entity.typeId !== 'minecraft:player') {
                            try {
                                entity.applyDamage(damage * (1 - ring * 0.15), {
                                    cause: EntityDamageCause.magic
                                });

                                // Levitación
                                entity.applyKnockback(0, 0, 0, 1.5);
                            } catch (error) {
                                // Error aplicando daño
                            }
                        }
                    });

                }, ring * 3);
            }

        } catch (error) {
            // Error en shockwave
        }
    },

    createMythrilLightning(dimension, location, damage) {
        try {
            // Rayo descendente
            for (let y = 20; y >= 0; y--) {
                system.runTimeout(() => {
                    const lightningPos = {
                        x: location.x + (Math.random() - 0.5) * 2,
                        y: location.y - 20 + y,
                        z: location.z + (Math.random() - 0.5) * 2
                    };

                    dimension.spawnParticle('myw:mythril_particle_serpentine', lightningPos);

                    // Ramificaciones
                    if (y % 5 === 0) {
                        for (let branch = 0; branch < 3; branch++) {
                            const branchAngle = Math.random() * Math.PI * 2;
                            const branchDist = Math.random() * 3;
                            dimension.spawnParticle('myw:mythril_particle', {
                                x: lightningPos.x + Math.cos(branchAngle) * branchDist,
                                y: lightningPos.y,
                                z: lightningPos.z + Math.sin(branchAngle) * branchDist
                            });
                        }
                    }
                }, (20 - y) * 2);
            }

            // Impacto en el suelo
            system.runTimeout(() => {
                const groundPos = {
                    x: location.x,
                    y: location.y - 20,
                    z: location.z
                };

                // Explosión de impacto
                for (let i = 0; i < 20; i++) {
                    const angle = Math.random() * Math.PI * 2;
                    const dist = Math.random() * 5;
                    const height = Math.random() * 3;

                    dimension.spawnParticle('myw:mythril_particle', {
                        x: groundPos.x + Math.cos(angle) * dist,
                        y: groundPos.y + height,
                        z: groundPos.z + Math.sin(angle) * dist
                    });
                }

                // Daño en área de impacto
                const entities = dimension.getEntities({
                    location: groundPos,
                    maxDistance: 5
                });

                entities.forEach(entity => {
                    if (entity.typeId !== 'minecraft:player') {
                        try {
                            entity.applyDamage(damage, { cause: EntityDamageCause.lightning });
                        } catch (error) {
                            // Error aplicando daño
                        }
                    }
                });

            }, 45);

        } catch (error) {
            // Error en lightning
        }
    },

    createOrbitalEffects(dimension, position, index) {
        try {
            // Esfera orbital principal
            for (let i = 0; i < 3; i++) {
                const offset = {
                    x: (Math.random() - 0.5) * 0.5,
                    y: (Math.random() - 0.5) * 0.5,
                    z: (Math.random() - 0.5) * 0.5
                };

                dimension.spawnParticle('myw:mythril_particle_serpentine', {
                    x: position.x + offset.x,
                    y: position.y + offset.y,
                    z: position.z + offset.z
                });
            }

            // Trail de energía
            dimension.spawnParticle('myw:mythril_particle', position);

            // Pulso ocasional
            if (index % 30 === 0) {
                for (let ring = 0; ring < 3; ring++) {
                    system.runTimeout(() => {
                        const particleCount = 8;
                        const radius = ring * 0.5;

                        for (let i = 0; i < particleCount; i++) {
                            const angle = (i / particleCount) * Math.PI * 2;
                            dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                x: position.x + Math.cos(angle) * radius,
                                y: position.y,
                                z: position.z + Math.sin(angle) * radius
                            });
                        }
                    }, ring * 2);
                }
            }

        } catch (error) {
            // Error en efectos orbitales
        }
    },

    fireOrbitalProjectile(dimension, origin, target, charges) {
        try {
            const targetPos = target.location;
            const direction = {
                x: targetPos.x - origin.x,
                y: targetPos.y - origin.y + 1,
                z: targetPos.z - origin.z
            };

            const distance = Math.sqrt(direction.x ** 2 + direction.y ** 2 + direction.z ** 2);
            const steps = Math.ceil(distance * 2);

            for (let step = 0; step <= steps; step++) {
                system.runTimeout(() => {
                    const progress = step / steps;
                    const projectilePos = {
                        x: origin.x + direction.x * progress,
                        y: origin.y + direction.y * progress,
                        z: origin.z + direction.z * progress
                    };

                    // Trail del proyectil
                    dimension.spawnParticle('myw:mythril_particle', projectilePos);

                    // Impacto
                    if (step === steps) {
                        try {
                            const damage = this.config.orbitalStrike.orbitDamage * (1 + charges * 0.2);
                            target.applyDamage(damage, { cause: EntityDamageCause.projectile });

                            // Explosión de impacto
                            for (let i = 0; i < 10; i++) {
                                dimension.spawnParticle('myw:mythril_particle_serpentine', {
                                    x: projectilePos.x + (Math.random() - 0.5) * 2,
                                    y: projectilePos.y + (Math.random() - 0.5) * 2,
                                    z: projectilePos.z + (Math.random() - 0.5) * 2
                                });
                            }
                        } catch (error) {
                            // Error en impacto
                        }
                    }
                }, step * 1);
            }

        } catch (error) {
            // Error disparando proyectil
        }
    },

    executeOrbitalFinale(player, dimension, location) {
        try {
            // Convergencia de todos los orbitales
            for (let i = 0; i < 12; i++) {
                const angle = (i / 12) * Math.PI * 2;
                const startPos = {
                    x: location.x + Math.cos(angle) * 15,
                    y: location.y + 5,
                    z: location.z + Math.sin(angle) * 15
                };

                // Converge hacia el centro
                const steps = 20;
                for (let step = 0; step <= steps; step++) {
                    system.runTimeout(() => {
                        const progress = step / steps;
                        const convergePos = {
                            x: startPos.x + (location.x - startPos.x) * progress,
                            y: startPos.y + (location.y - startPos.y) * progress,
                            z: startPos.z + (location.z - startPos.z) * progress
                        };

                        dimension.spawnParticle('myw:mythril_particle_serpentine', convergePos);
                    }, step * 2);
                }
            }

            // Explosión final masiva
            system.runTimeout(() => {
                this.createMassiveExplosion(dimension, location, 30, 50);
            }, 45);

        } catch (error) {
            // Error en finale orbital
        }
    },

    createMythrilVortex(dimension, origin) {
        try {
            // Vórtice espiral ascendente
            const vortexHeight = 20;
            const vortexDuration = 100;

            const vortexInterval = system.runInterval(() => {
                try {
                    for (let h = 0; h < vortexHeight; h++) {
                        const heightProgress = h / vortexHeight;
                        const radius = 5 * (1 - heightProgress * 0.8);
                        const angle = Date.now() * 0.01 + h * 0.5;

                        const vortexPos = {
                            x: origin.x + Math.cos(angle) * radius,
                            y: origin.y + h,
                            z: origin.z + Math.sin(angle) * radius
                        };

                        dimension.spawnParticle('myw:mythril_particle_serpentine', vortexPos);

                        // Partículas secundarias
                        if (h % 3 === 0) {
                            for (let i = 0; i < 4; i++) {
                                const secondaryAngle = angle + (i / 4) * Math.PI * 2;
                                dimension.spawnParticle('myw:mythril_particle', {
                                    x: origin.x + Math.cos(secondaryAngle) * radius * 1.2,
                                    y: origin.y + h,
                                    z: origin.z + Math.sin(secondaryAngle) * radius * 1.2
                                });
                            }
                        }
                    }
                } catch (error) {
                    system.clearRun(vortexInterval);
                }
            }, 2);

            system.runTimeout(() => {
                system.clearRun(vortexInterval);
            }, vortexDuration);

        } catch (error) {
            // Error creando vórtice
        }
    },

    applyTemporalFreeze(dimension, origin, radius) {
        try {
            const entities = dimension.getEntities({
                location: origin,
                maxDistance: radius,
                excludeTypes: ['minecraft:player']
            });

            entities.forEach(entity => {
                try {
                    // Congela enemigos
                    entity.addEffect('slowness', this.config.mythrilNova.temporalFreeze, {
                        amplifier: 10
                    });
                    entity.addEffect('weakness', this.config.mythrilNova.temporalFreeze, {
                        amplifier: 5
                    });

                    // Efectos visuales de congelación
                    for (let i = 0; i < 5; i++) {
                        system.runTimeout(() => {
                            if (entity.isValid()) {
                                dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                    x: entity.location.x + (Math.random() - 0.5),
                                    y: entity.location.y + Math.random() * 2,
                                    z: entity.location.z + (Math.random() - 0.5)
                                });
                            }
                        }, i * 10);
                    }

                } catch (error) {
                    // Error congelando entidad
                }
            });

        } catch (error) {
            // Error en freeze temporal
        }
    },

    createNovaRing(dimension, origin, radius, damage, waveIndex) {
        try {
            const particleCount = Math.floor(radius * 8);
            const heightVariation = Math.sin(waveIndex * 0.5) * 3;

            for (let i = 0; i < particleCount; i++) {
                const angle = (i / particleCount) * Math.PI * 2;
                const ringPos = {
                    x: origin.x + Math.cos(angle) * radius,
                    y: origin.y + heightVariation + Math.sin(i * 0.2) * 1.5,
                    z: origin.z + Math.sin(angle) * radius
                };

                // Múltiples capas de partículas
                dimension.spawnParticle('myw:mythril_particle_serpentine', ringPos);

                // Pilares de energía
                if (i % 8 === 0) {
                    for (let h = 0; h < 15; h++) {
                        system.runTimeout(() => {
                            dimension.spawnParticle('myw:mythril_particle', {
                                x: ringPos.x,
                                y: ringPos.y + h,
                                z: ringPos.z
                            });
                        }, h * 1);
                    }
                }
            }

            // Daño en el anillo
            const entities = dimension.getEntities({
                location: origin,
                maxDistance: radius + 2,
                minDistance: Math.max(0, radius - 2)
            });

            entities.forEach(entity => {
                if (entity.typeId !== 'minecraft:player') {
                    try {
                        entity.applyDamage(damage, { cause: EntityDamageCause.magic });
                        entity.applyKnockback(
                            entity.location.x - origin.x,
                            entity.location.z - origin.z,
                            2,
                            1
                        );
                    } catch (error) {
                        // Error aplicando daño
                    }
                }
            });

        } catch (error) {
            // Error en nova ring
        }
    },

    createGravityWell(dimension, origin, radius) {
        try {
            // Levanta entidades y las atrae hacia el centro
            const entities = dimension.getEntities({
                location: origin,
                maxDistance: radius
            });

            entities.forEach(entity => {
                if (entity.typeId !== 'minecraft:player') {
                    try {
                        const direction = {
                            x: origin.x - entity.location.x,
                            y: 5,
                            z: origin.z - entity.location.z
                        };

                        const distance = Math.sqrt(direction.x ** 2 + direction.z ** 2);
                        if (distance > 0) {
                            const force = Math.max(0.5, 1 - distance / radius) * 3;
                            entity.applyKnockback(
                                direction.x / distance * force,
                                direction.z / distance * force,
                                force,
                                2
                            );
                        }
                    } catch (error) {
                        // Error con gravity well
                    }
                }
            });

        } catch (error) {
            // Error en gravity well
        }
    },

    createNovaImplosion(dimension, origin, charges) {
        try {
            // Atrae todas las partículas y entidades hacia el centro
            const implosionRadius = 30;

            // Efecto visual de implosión
            for (let ring = 5; ring >= 0; ring--) {
                system.runTimeout(() => {
                    const radius = ring * 5;
                    const particleCount = radius * 4;

                    for (let i = 0; i < particleCount; i++) {
                        const angle = (i / particleCount) * Math.PI * 2;
                        const startPos = {
                            x: origin.x + Math.cos(angle) * radius,
                            y: origin.y + Math.random() * 10,
                            z: origin.z + Math.sin(angle) * radius
                        };

                        // Converge hacia el centro
                        const steps = 10;
                        for (let step = 0; step <= steps; step++) {
                            system.runTimeout(() => {
                                const progress = step / steps;
                                const implosionPos = {
                                    x: startPos.x + (origin.x - startPos.x) * progress,
                                    y: startPos.y + (origin.y - startPos.y) * progress,
                                    z: startPos.z + (origin.z - startPos.z) * progress
                                };

                                dimension.spawnParticle('myw:mythril_particle_serpentine', implosionPos);
                            }, step * 2);
                        }
                    }
                }, (5 - ring) * 5);
            }

            // Explosión final después de la implosión
            system.runTimeout(() => {
                this.createMassiveExplosion(dimension, origin, implosionRadius, 100);
            }, 35);

        } catch (error) {
            // Error en implosión
        }
    },

    createTransformationEffects(player) {
        try {
            const dimension = player.dimension;
            const location = player.location;

            // Columna de luz ascendente
            for (let h = 0; h < 30; h++) {
                system.runTimeout(() => {
                    const radius = 3 * (1 - h / 30);
                    const particleCount = 16;

                    for (let i = 0; i < particleCount; i++) {
                        const angle = (i / particleCount) * Math.PI * 2;
                        dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + h,
                            z: location.z + Math.sin(angle) * radius
                        });
                    }
                }, h * 2);
            }

            // Alas de energía
            this.createEnergyWings(dimension, location);

        } catch (error) {
            // Error en efectos de transformación
        }
    },

    createDivineAura(player) {
        try {
            const dimension = player.dimension;
            const location = player.location;
            const auraRadius = 8;

            // Aura pulsante
            const pulseRadius = auraRadius + Math.sin(Date.now() * 0.005) * 2;
            const particleCount = 24;

            for (let i = 0; i < particleCount; i++) {
                const angle = (i / particleCount) * Math.PI * 2;

                // Múltiples capas de aura
                for (let layer = 0; layer < 3; layer++) {
                    const layerRadius = pulseRadius * (1 - layer * 0.2);
                    const layerHeight = layer * 0.5;

                    dimension.spawnParticle('myw:mythril_particle', {
                        x: location.x + Math.cos(angle) * layerRadius,
                        y: location.y + layerHeight + Math.sin(angle * 3) * 0.5,
                        z: location.z + Math.sin(angle) * layerRadius
                    });
                }
            }

            // Daño de aura a enemigos cercanos
            const entities = dimension.getEntities({
                location: location,
                maxDistance: auraRadius,
                excludeTypes: ['minecraft:player']
            });

            entities.forEach(entity => {
                try {
                    entity.applyDamage(5, { cause: EntityDamageCause.magic });

                    // Quema divina
                    entity.setOnFire(3, true);

                } catch (error) {
                    // Error con aura damage
                }
            });

        } catch (error) {
            // Error en divine aura
        }
    },

    createAnnihilationSphere(dimension, origin) {
        try {
            const sphereRadius = 15;
            const duration = 60;

            let tick = 0;
            const sphereInterval = system.runInterval(() => {
                try {
                    tick++;

                    // Esfera pulsante
                    const currentRadius = sphereRadius * (1 + Math.sin(tick * 0.2) * 0.2);

                    // Crear superficie de la esfera
                    const latitudes = 8;
                    const longitudes = 16;

                    for (let lat = 0; lat < latitudes; lat++) {
                        const theta = (lat / latitudes) * Math.PI;
                        const sinTheta = Math.sin(theta);
                        const y = Math.cos(theta) * currentRadius;

                        for (let lon = 0; lon < longitudes; lon++) {
                            if (Math.random() > 0.3) continue; // Reduce partículas para performance

                            const phi = (lon / longitudes) * Math.PI * 2;
                            const x = Math.cos(phi) * sinTheta * currentRadius;
                            const z = Math.sin(phi) * sinTheta * currentRadius;

                            dimension.spawnParticle('myw:mythril_particle_serpentine', {
                                x: origin.x + x,
                                y: origin.y + y + 2,
                                z: origin.z + z
                            });
                        }
                    }

                    // Rayos internos
                    if (tick % 5 === 0) {
                        for (let i = 0; i < 3; i++) {
                            const startAngle = Math.random() * Math.PI * 2;
                            const endAngle = Math.random() * Math.PI * 2;
                            const startHeight = (Math.random() - 0.5) * currentRadius;
                            const endHeight = (Math.random() - 0.5) * currentRadius;

                            this.createInternalLightning(
                                dimension,
                                {
                                    x: origin.x + Math.cos(startAngle) * currentRadius * 0.8,
                                    y: origin.y + startHeight,
                                    z: origin.z + Math.sin(startAngle) * currentRadius * 0.8
                                },
                                {
                                    x: origin.x + Math.cos(endAngle) * currentRadius * 0.8,
                                    y: origin.y + endHeight,
                                    z: origin.z + Math.sin(endAngle) * currentRadius * 0.8
                                }
                            );
                        }
                    }

                    if (tick >= duration) {
                        system.clearRun(sphereInterval);
                    }

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

        } catch (error) {
            // Error en annihilation sphere
        }
    },

    createDivineBeam(dimension, origin, angle) {
        try {
            const beamLength = 50;
            const beamWidth = 2;

            for (let dist = 0; dist < beamLength; dist++) {
                system.runTimeout(() => {
                    const beamPos = {
                        x: origin.x + Math.cos(angle) * dist,
                        y: origin.y,
                        z: origin.z + Math.sin(angle) * dist
                    };

                    // Núcleo del rayo
                    dimension.spawnParticle('myw:mythril_particle_serpentine', beamPos);

                    // Ancho del rayo
                    for (let w = 0; w < 3; w++) {
                        const perpAngle = angle + Math.PI / 2;
                        const width = (Math.random() - 0.5) * beamWidth;

                        dimension.spawnParticle('myw:mythril_particle', {
                            x: beamPos.x + Math.cos(perpAngle) * width,
                            y: beamPos.y + Math.random() * 2,
                            z: beamPos.z + Math.sin(perpAngle) * width
                        });
                    }

                    // Daño en el camino del rayo
                    const entities = dimension.getEntities({
                        location: beamPos,
                        maxDistance: 3
                    });

                    entities.forEach(entity => {
                        if (entity.typeId !== 'minecraft:player') {
                            try {
                                entity.applyDamage(20, { cause: EntityDamageCause.magic });
                            } catch (error) {
                                // Error aplicando daño
                            }
                        }
                    });

                }, Math.floor(dist / 2));
            }

        } catch (error) {
            // Error en divine beam
        }
    },

    summonMythrilMeteors(dimension, origin, count) {
        try {
            for (let i = 0; i < count; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const distance = 10 + Math.random() * 20;
                    const meteorStart = {
                        x: origin.x + Math.cos(angle) * distance,
                        y: origin.y + 30,
                        z: origin.z + Math.sin(angle) * distance
                    };

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

                    this.createMeteor(dimension, meteorStart, meteorTarget);

                }, i * 8);
            }

        } catch (error) {
            // Error invocando meteoros
        }
    },

    createMeteor(dimension, start, target) {
        try {
            const steps = 30;

            for (let step = 0; step <= steps; step++) {
                system.runTimeout(() => {
                    const progress = step / steps;
                    const meteorPos = {
                        x: start.x + (target.x - start.x) * progress,
                        y: start.y + (target.y - start.y) * progress,
                        z: start.z + (target.z - start.z) * progress
                    };

                    // Cuerpo del meteoro
                    for (let i = 0; i < 5; i++) {
                        dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: meteorPos.x + (Math.random() - 0.5) * 2,
                            y: meteorPos.y + (Math.random() - 0.5) * 2,
                            z: meteorPos.z + (Math.random() - 0.5) * 2
                        });
                    }

                    // Cola del meteoro
                    for (let t = 1; t <= 5; t++) {
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: meteorPos.x - (target.x - start.x) * 0.1 * t,
                            y: meteorPos.y - (target.y - start.y) * 0.1 * t + t * 0.5,
                            z: meteorPos.z - (target.z - start.z) * 0.1 * t
                        });
                    }

                    // Impacto
                    if (step === steps) {
                        this.createMeteorImpact(dimension, target);
                    }

                }, step * 2);
            }

        } catch (error) {
            // Error creando meteoro
        }
    },

    createMeteorImpact(dimension, location) {
        try {
            // Crater de impacto
            const impactRadius = 8;

            // Onda de choque
            for (let ring = 0; ring < 4; ring++) {
                system.runTimeout(() => {
                    const radius = (ring + 1) * 3;
                    const particleCount = radius * 6;

                    for (let i = 0; i < particleCount; i++) {
                        const angle = (i / particleCount) * Math.PI * 2;
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + 0.1,
                            z: location.z + Math.sin(angle) * radius
                        });
                    }
                }, ring * 3);
            }

            // Columna de explosión
            for (let h = 0; h < 10; h++) {
                system.runTimeout(() => {
                    for (let i = 0; i < 8; i++) {
                        dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: location.x + (Math.random() - 0.5) * 4,
                            y: location.y + h * 2,
                            z: location.z + (Math.random() - 0.5) * 4
                        });
                    }
                }, h * 2);
            }

            // Daño masivo
            const entities = dimension.getEntities({
                location: location,
                maxDistance: impactRadius
            });

            entities.forEach(entity => {
                if (entity.typeId !== 'minecraft:player') {
                    try {
                        const distance = this.getDistance(entity.location, location);
                        const damage = 80 * (1 - distance / impactRadius);
                        entity.applyDamage(damage, { cause: EntityDamageCause.explosion });

                        // Lanzamiento por explosión
                        const knockbackDir = {
                            x: entity.location.x - location.x,
                            z: entity.location.z - location.z
                        };
                        const knockbackDist = Math.sqrt(knockbackDir.x ** 2 + knockbackDir.z ** 2);
                        if (knockbackDist > 0) {
                            entity.applyKnockback(
                                knockbackDir.x / knockbackDist * 4,
                                knockbackDir.z / knockbackDist * 4,
                                4,
                                2
                            );
                        }
                    } catch (error) {
                        // Error aplicando daño de meteoro
                    }
                }
            });

        } catch (error) {
            // Error en meteor impact
        }
    },

    disintegrateEntity(dimension, entity) {
        try {
            const location = entity.location;

            // Efecto de desintegración
            for (let i = 0; i < 20; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle_minimalist', {
                        x: location.x + (Math.random() - 0.5) * 2,
                        y: location.y + Math.random() * 2,
                        z: location.z + (Math.random() - 0.5) * 2
                    });
                }, i * 2);
            }

            // Matar la entidad
            try {
                entity.kill();
            } catch (error) {
                // Ya muerta o error
            }

        } catch (error) {
            // Error desintegrando
        }
    },

    createSummonPortal(dimension, location) {
        try {
            // Portal circular
            const portalRadius = 3;
            const duration = 40;

            for (let t = 0; t < duration; t++) {
                system.runTimeout(() => {
                    const particleCount = 16;
                    const heightOffset = Math.sin(t * 0.2) * 0.5;

                    for (let i = 0; i < particleCount; i++) {
                        const angle = (i / particleCount) * Math.PI * 2 + t * 0.1;
                        dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: location.x + Math.cos(angle) * portalRadius,
                            y: location.y + heightOffset,
                            z: location.z + Math.sin(angle) * portalRadius
                        });
                    }
                }, t);
            }

        } catch (error) {
            // Error en portal
        }
    },

    guardianAttack(dimension, guardianData) {
        try {
            if (!guardianData.target || !guardianData.target.isValid()) return;

            const origin = guardianData.location;
            const target = guardianData.target.location;

            // Rayo del guardian
            const steps = 10;
            for (let step = 0; step <= steps; step++) {
                system.runTimeout(() => {
                    const progress = step / steps;
                    const beamPos = {
                        x: origin.x + (target.x - origin.x) * progress,
                        y: origin.y + (target.y - origin.y) * progress + 1,
                        z: origin.z + (target.z - origin.z) * progress
                    };

                    dimension.spawnParticle('myw:mythril_particle', beamPos);
                }, step);
            }

            // Daño al objetivo
            system.runTimeout(() => {
                try {
                    guardianData.target.applyDamage(this.config.ancientSummon.guardianDamage, {
                        cause: EntityDamageCause.magic
                    });
                } catch (error) {
                    // Error aplicando daño
                }
            }, 12);

        } catch (error) {
            // Error en guardian attack
        }
    },

    createGuardianEffects(dimension, location) {
        try {
            // Forma etérea del guardian
            const bodyHeight = 3;

            // Cuerpo
            for (let h = 0; h < bodyHeight; h++) {
                dimension.spawnParticle('myw:mythril_particle_serpentine', {
                    x: location.x + (Math.random() - 0.5) * 0.5,
                    y: location.y + h,
                    z: location.z + (Math.random() - 0.5) * 0.5
                });
            }

            // Aura
            const auraRadius = 2;
            for (let i = 0; i < 6; i++) {
                const angle = (i / 6) * Math.PI * 2;
                dimension.spawnParticle('myw:mythril_particle', {
                    x: location.x + Math.cos(angle) * auraRadius,
                    y: location.y + 1.5,
                    z: location.z + Math.sin(angle) * auraRadius
                });
            }

        } catch (error) {
            // Error en guardian effects
        }
    },

    createGuardianDespawn(dimension, location) {
        try {
            // Implosión del guardian
            for (let i = 0; i < 15; i++) {
                system.runTimeout(() => {
                    const radius = 3 * (1 - i / 15);
                    const particleCount = 12;

                    for (let p = 0; p < particleCount; p++) {
                        const angle = (p / particleCount) * Math.PI * 2;
                        dimension.spawnParticle('myw:mythril_particle_minimalist', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + i * 0.3,
                            z: location.z + Math.sin(angle) * radius
                        });
                    }
                }, i * 2);
            }

        } catch (error) {
            // Error en despawn
        }
    },

    createEnergyWings(dimension, location) {
        try {
            // Alas de energía mítica
            const wingSpan = 8;
            const wingHeight = 4;

            for (let side = -1; side <= 1; side += 2) {
                for (let w = 0; w < 20; w++) {
                    system.runTimeout(() => {
                        const wingProgress = w / 20;
                        const wingX = side * wingSpan * wingProgress;
                        const wingY = Math.sin(wingProgress * Math.PI) * wingHeight;

                        for (let i = 0; i < 3; i++) {
                            dimension.spawnParticle('myw:mythril_particle_serpentine', {
                                x: location.x + wingX + (Math.random() - 0.5),
                                y: location.y + wingY + 2,
                                z: location.z + (Math.random() - 0.5)
                            });
                        }
                    }, w * 2);
                }
            }

        } catch (error) {
            // Error en wings
        }
    },

    createMassiveExplosion(dimension, location, radius, damage) {
        try {
            // Múltiples anillos de explosión
            for (let ring = 0; ring < 5; ring++) {
                system.runTimeout(() => {
                    const ringRadius = radius * ((ring + 1) / 5);
                    const particleCount = Math.floor(ringRadius * 10);

                    for (let i = 0; i < particleCount; i++) {
                        const angle = (i / particleCount) * Math.PI * 2;
                        const height = Math.random() * 5;

                        dimension.spawnParticle('myw:mythril_particle_serpentine', {
                            x: location.x + Math.cos(angle) * ringRadius,
                            y: location.y + height,
                            z: location.z + Math.sin(angle) * ringRadius
                        });
                    }
                }, ring * 4);
            }

            // Daño masivo
            const entities = dimension.getEntities({
                location: location,
                maxDistance: radius
            });

            entities.forEach(entity => {
                if (entity.typeId !== 'minecraft:player') {
                    try {
                        const distance = this.getDistance(entity.location, location);
                        const finalDamage = damage * (1 - distance / radius);
                        entity.applyDamage(finalDamage, { cause: EntityDamageCause.explosion });
                    } catch (error) {
                        // Error aplicando daño
                    }
                }
            });

        } catch (error) {
            // Error en massive explosion
        }
    },

    createEnergyBeam(dimension, from, to) {
        try {
            const steps = 15;
            for (let step = 0; step <= steps; step++) {
                system.runTimeout(() => {
                    const progress = step / steps;
                    const beamPos = {
                        x: from.x + (to.x - from.x) * progress,
                        y: from.y + (to.y - from.y) * progress,
                        z: from.z + (to.z - from.z) * progress
                    };

                    dimension.spawnParticle('myw:mythril_particle', beamPos);
                }, step);
            }
        } catch (error) {
            // Error en beam
        }
    },

    createInternalLightning(dimension, from, to) {
        try {
            const steps = 8;
            for (let step = 0; step <= steps; step++) {
                const progress = step / steps;
                const variance = (Math.random() - 0.5) * 2;

                const lightningPos = {
                    x: from.x + (to.x - from.x) * progress + variance,
                    y: from.y + (to.y - from.y) * progress + variance,
                    z: from.z + (to.z - from.z) * progress + variance
                };

                dimension.spawnParticle('myw:mythril_particle_serpentine', lightningPos);
            }
        } catch (error) {
            // Error en lightning
        }
    },

    // UTILIDADES

    createNewState(playerId) {
        return {
            playerId: playerId,
            isCharging: false,
            chargeStartTime: 0,
            chargeInterval: null,
            comboCount: 0,
            lastAttackTime: 0,
            divineFormActive: false,
            divineFormStart: 0,
            divineAuraInterval: null
        };
    },

    createChargeBar(charges) {
        const maxCharges = this.config.cosmicPower.maxCharges;
        let bar = '§8[';
        for (let i = 0; i < maxCharges; i++) {
            if (i < charges) {
                bar += '§b█';
            } else {
                bar += '§7░';
            }
        }
        bar += '§8]';
        return bar;
    },

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

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

            entities.forEach(entity => {
                if (entity.id === excludePlayer.id) return;
                if (entity.typeId === 'minecraft:player') return;

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

            return nearestTarget;

        } 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
        );
    },

    sendStaffMessage(player, message) {
        try {
            player.onScreenDisplay.setActionBar(message);
        } catch (error) {
            // Fallback a mensaje normal
            try {
                player.sendMessage(message);
            } catch (e) {
                // Error enviando mensaje
            }
        }
    }
};

// Registrar el componente del Ancient Staff
export function registerAncientMythrilStaff(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:ancient_mythril_staff', {
        onUse(eventData) {
            const { itemStack, source } = eventData;
            AncientMythrilStaffSystem.handleStaffUse(source, itemStack);
        }
    });
}

// Inicializar el sistema
export function initializeAncientStaffSystems() {
    system.runTimeout(() => {
        world.sendMessage('§6═══════════════════════════════════════');
        world.sendMessage('§6♔ §eMYTHRIL ANCIENT STAFF §6♔');
        world.sendMessage('§7The ultimate weapon has awakened...');
        world.sendMessage('§bCharge System §8▸ §7Hold to charge power');
        world.sendMessage('§5Combo System §8▸ §7Chain attacks for ultimate');
        world.sendMessage('§cDivine Form §8▸ §7Achieve godhood at max combo');
        world.sendMessage('§6═══════════════════════════════════════');
    }, 60);

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