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

export const MythrilArmorSystem = {
    config: {
        maxMana: {
            boots: 100,
            leggings: 60,
            chestplate: 80,
            helmet: 60,
            crown: 80
        },
        manaRegen: {
            base: 2,
            combat: 0.5,
            meditation: 5
        },

        jumpManaCost: 25,
        maxJumps: 5,
        jumpBoostAmplifier: 2,
        jumpPower: 1.3,
        speedBoostAmplifier: 1,
        ultimateSlamDamage: 1000,
        ultimateSlamRadius: 20,

        dashManaCost: 50,
        dashDistance: 15,
        dashCooldown: 40,

        magnetismManaCost: 5,
        magnetismActivationCost: 75,
        magnetismRadius: 7,
        magnetismDuration: 400,

        visionManaCost: 3,
        visionActivationCost: 50,
        entityDetectionRadius: 15,
        oreDetectionRadius: 10,
        visionDuration: 300,
        visionHoldTime: 40, // 2 seconds (40 ticks)

        crownEntityRadius: 20,
        crownOreRadius: 15,
        crownVisionDuration: 600,
        leadershipRadius: 10
    },

    ui: {
        colors: {
            mana: '§9',
            high: '§a',
            medium: '§e',
            low: '§c',
            active: '§f',
            inactive: '§7',
            special: '§d',
            legendary: '§6'
        },

        createManaBar(current, max, length = 10) {
            const percentage = (current / max) * 100;
            const filled = Math.round((percentage / 100) * length);

            let color;
            if (percentage >= 75) color = this.colors.high;
            else if (percentage >= 40) color = this.colors.medium;
            else if (percentage >= 20) color = this.colors.low;
            else color = '§4';

            let bar = color;

            bar += '<';

            for (let i = 0; i < filled; i++) {
                if (i === 0) bar += '=';
                else if (i === filled - 1) bar += '>';
                else bar += '=';
            }

            bar += '§8';
            for (let i = filled; i < length; i++) {
                bar += '-';
            }

            bar += '§r>';

            return bar;
        },

        createFrame(content, type = 'normal') {
            const frames = {
                normal: { left: '[', right: ']' },
                special: { left: '<<', right: '>>' },
                legendary: { left: '<<<', right: '>>>' }
            };

            const frame = frames[type] || frames.normal;
            return `§7${frame.left}§r ${content} §7${frame.right}§r`;
        }
    },

    activePlayers: new Map(),
    activeSessions: new Map(),
    playerInputStates: new Map(),
    manaSystem: new Map(),

    initializeManaSystem(player) {
        const playerId = player.id;

        this.manaSystem.set(playerId, {
            boots: this.config.maxMana.boots,
            leggings: this.config.maxMana.leggings,
            chestplate: this.config.maxMana.chestplate,
            helmet: this.config.maxMana.helmet,
            crown: this.config.maxMana.crown,

            isRegenerating: true,
            inCombat: false,
            lastCombatTime: 0,
            isMeditating: false,
            meditationStart: 0
        });
    },

    getMana(player, piece) {
        const playerId = player.id;
        const manaData = this.manaSystem.get(playerId);
        if (!manaData) return 0;
        return manaData[piece] || 0;
    },

    setMana(player, piece, value) {
        const playerId = player.id;
        const manaData = this.manaSystem.get(playerId);
        if (!manaData) return;

        const maxMana = this.config.maxMana[piece];
        manaData[piece] = Math.max(0, Math.min(value, maxMana));
    },

    consumeMana(player, piece, amount) {
        const currentMana = this.getMana(player, piece);
        if (currentMana < amount) return false;

        this.setMana(player, piece, currentMana - amount);

        const playerId = player.id;
        const manaData = this.manaSystem.get(playerId);
        if (manaData) {
            manaData.inCombat = true;
            manaData.lastCombatTime = world.getAbsoluteTime();
        }

        return true;
    },

    regenerateMana(player) {
        const playerId = player.id;
        const manaData = this.manaSystem.get(playerId);
        if (!manaData || !manaData.isRegenerating) return;

        const armor = this.checkEquippedArmor(player);
        const currentTime = world.getAbsoluteTime();

        let regenRate = this.config.manaRegen.base;

        const velocity = player.getVelocity();
        const isMoving = Math.abs(velocity.x) > 0.01 || Math.abs(velocity.z) > 0.01;

        if (player.isSneaking && !isMoving) {
            if (!manaData.isMeditating) {
                manaData.meditationStart = currentTime;
                manaData.isMeditating = true;
            } else if (currentTime - manaData.meditationStart > 40) {
                regenRate = this.config.manaRegen.meditation;

                if (currentTime % 20 === 0) {
                    this.createMeditationEffect(player);
                }
            }
        } else {
            manaData.isMeditating = false;
        }

        if (manaData.inCombat && currentTime - manaData.lastCombatTime > 100) {
            manaData.inCombat = false;
        }

        if (manaData.inCombat) {
            regenRate = this.config.manaRegen.combat;
        }

        const pieces = ['boots', 'leggings', 'chestplate', 'helmet', 'crown'];
        pieces.forEach(piece => {
            if (armor[piece]) {
                const current = this.getMana(player, piece);
                const max = this.config.maxMana[piece];
                if (current < max) {
                    this.setMana(player, piece, current + regenRate);
                }
            }
        });
    },

    initializePlayer(player) {
        const playerId = player.id;

        const playerData = {
            initialized: true,
            currentDisplayPiece: null,
            lastDisplayUpdate: 0,
            lastNotificationTime: 0,
            dashReady: true
        };

        this.activePlayers.set(playerId, playerData);

        this.playerInputStates.set(playerId, {
            wasOnGround: true,
            wasSneaking: false,
            wasJumping: false,

            lastJumpTime: 0,
            jumpCount: 0,

            airJumpCount: 0,
            lastAirJumpTime: 0,

            isPerformingSlam: false,
            slamStartHeight: 0,

            lastSneakTime: 0,
            sneakCount: 0,

            // Vision hold tracking
            sneakHoldStart: 0,
            isHoldingSneak: false,
            visionReady: true,
            visionActivationTime: 0
        });

        this.initializeManaSystem(player);

        this.setJumpCount(player, 0);
        this.setLastDashTime(player, 0);

        try {
            const location = player.location;
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                player.dimension.spawnParticle('myw:mythril_particle', {
                    x: location.x + Math.cos(angle) * 2,
                    y: location.y + 1,
                    z: location.z + Math.sin(angle) * 2
                });
            }
            this.playSound(player, 'random.levelup');
        } catch { }
    },

    showNotification(player, message, type = 'normal') {
        if (type === 'special' || type === 'legendary') {
            const colors = {
                special: '§d',
                legendary: '§6'
            };

            const color = colors[type] || '§a';

            try {
                player.onScreenDisplay.setTitle(color + message, {
                    stayDuration: 8,
                    fadeInDuration: 2,
                    fadeOutDuration: 3
                });
            } catch { }
        }
    },

    updatePlayerInput(player) {
        const playerId = player.id;
        const inputState = this.playerInputStates.get(playerId);
        if (!inputState) return;

        const armor = this.checkEquippedArmor(player);
        const currentTick = world.getAbsoluteTime();

        const isOnGround = player.isOnGround;
        const isSneaking = player.isSneaking;
        const isJumping = player.isJumping;

        // BOOTS - Multi-jump system
        if (armor.boots) {
            if (isOnGround && !inputState.wasOnGround) {
                inputState.airJumpCount = 0;
                inputState.isPerformingSlam = false;
            }

            if (!isOnGround && isJumping && !inputState.wasJumping) {
                if (currentTick - inputState.lastAirJumpTime > 5) {
                    this.handleMultiJump(player);
                    inputState.lastAirJumpTime = currentTick;
                }
            }
        }

        // LEGGINGS - Double jump dash ONLY
        if (armor.leggings) {
            if (isJumping && !inputState.wasJumping) {
                if (currentTick - inputState.lastJumpTime < 10) {
                    // Double jump detected - activate dash
                    this.activateDash(player);
                    inputState.jumpCount = 0;
                    inputState.lastJumpTime = 0;
                } else {
                    inputState.jumpCount = 1;
                    inputState.lastJumpTime = currentTick;
                }
            }

            // Reset jump count after timeout
            if (currentTick - inputState.lastJumpTime > 20) {
                inputState.jumpCount = 0;
            }
        }

        // CHESTPLATE - Double sneak magnetism
        if (armor.chestplate) {
            if (isSneaking && !inputState.wasSneaking) {
                if (currentTick - inputState.lastSneakTime < 15) {
                    // Double sneak detected - activate magnetism
                    this.activateMagnetism(player);
                    inputState.sneakCount = 0;
                    inputState.lastSneakTime = 0;
                } else {
                    inputState.sneakCount = 1;
                    inputState.lastSneakTime = currentTick;
                }
            }

            // Reset sneak count after timeout
            if (currentTick - inputState.lastSneakTime > 30) {
                inputState.sneakCount = 0;
            }
        }

        // HELMET/CROWN - Hold sneak for 2 seconds
        if (armor.helmet || armor.crown) {
            if (isSneaking) {
                if (!inputState.isHoldingSneak) {
                    // Start holding sneak
                    inputState.isHoldingSneak = true;
                    inputState.sneakHoldStart = currentTick;
                } else {
                    // Check if held for 2 seconds
                    const holdDuration = currentTick - inputState.sneakHoldStart;

                    if (holdDuration >= this.config.visionHoldTime && inputState.visionReady) {
                        // Activate vision after 2 seconds of holding
                        if (currentTick - inputState.visionActivationTime > 20) {
                            this.activateVision(player, armor.crown);
                            inputState.visionActivationTime = currentTick;
                            inputState.visionReady = false;
                        }
                    } else if (holdDuration >= 20 && holdDuration < this.config.visionHoldTime) {
                        // Show charging indicator after 1 second
                        if (currentTick % 10 === 0) {
                            const remaining = Math.ceil((this.config.visionHoldTime - holdDuration) / 20);
                            this.showMessage(player, `§b◉ Hold sneak: ${remaining}s`);
                        }
                    }
                }
            } else {
                // Released sneak
                if (inputState.isHoldingSneak) {
                    inputState.isHoldingSneak = false;
                    inputState.visionReady = true;
                }
            }
        }

        inputState.wasOnGround = isOnGround;
        inputState.wasSneaking = isSneaking;
        inputState.wasJumping = isJumping;
    },

    handleMultiJump(player) {
        const armor = this.checkEquippedArmor(player);
        if (!armor.boots || player.isOnGround) return;

        const inputState = this.playerInputStates.get(player.id);
        if (!inputState) return;

        if (inputState.airJumpCount >= this.config.maxJumps) {
            this.initiateUltimateSlam(player);
            return;
        }

        if (!this.consumeMana(player, 'boots', this.config.jumpManaCost)) {
            this.playSound(player, 'note.bass');
            return;
        }

        const jumpPower = this.config.jumpPower - (inputState.airJumpCount * 0.1);

        try {
            player.applyKnockback(0, 0, 0, jumpPower);
            inputState.airJumpCount++;

            this.createJumpEffects(player, inputState.airJumpCount);

            if (inputState.airJumpCount >= 4) {
                this.playSound(player, 'mob.wither.shoot');
            } else {
                this.playSound(player, 'mob.enderdragon.flap');
            }

        } catch (error) { }
    },

    initiateUltimateSlam(player) {
        const inputState = this.playerInputStates.get(player.id);
        if (!inputState) return;

        const remainingMana = this.getMana(player, 'boots');
        if (remainingMana < 10) {
            this.playSound(player, 'note.bass');
            return;
        }

        this.setMana(player, 'boots', 0);

        player.applyKnockback(0, 0, 0, -3);

        try {
            player.onScreenDisplay.setTitle('§c§lULTIMATE SLAM!', {
                stayDuration: 10,
                fadeInDuration: 2,
                fadeOutDuration: 5
            });
        } catch { }

        this.playSound(player, 'mob.wither.spawn');

        inputState.isPerformingSlam = true;
        inputState.slamStartHeight = player.location.y;

        const slamCheck = system.runInterval(() => {
            if (player.isOnGround || player.location.y < inputState.slamStartHeight - 50) {
                system.clearRun(slamCheck);
                this.executeUltimateSlam(player, remainingMana);
                inputState.isPerformingSlam = false;
                inputState.airJumpCount = 0;
            }
        }, 1);
    },

    executeUltimateSlam(player, manaUsed) {
        const location = player.location;
        const dimension = player.dimension;

        const damage = this.config.ultimateSlamDamage;
        const radius = this.config.ultimateSlamRadius;

        for (let ring = 1; ring <= 10; ring++) {
            system.runTimeout(() => {
                const r = ring * 2;
                for (let i = 0; i < 24; i++) {
                    const angle = (i / 24) * Math.PI * 2;

                    dimension.spawnParticle('minecraft:sonic_explosion', {
                        x: location.x + Math.cos(angle) * r,
                        y: location.y + 0.1,
                        z: location.z + Math.sin(angle) * r
                    });

                    if (ring === 5 || ring === 10) {
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: location.x + Math.cos(angle) * r,
                            y: location.y + 0.5,
                            z: location.z + Math.sin(angle) * r
                        });
                    }
                }
            }, ring * 2);
        }

        try {
            const nearbyEntities = dimension.getEntities({
                location: location,
                maxDistance: radius,
                excludeFamilies: ['player']
            });

            nearbyEntities.forEach(entity => {
                try {
                    entity.kill();
                } catch {
                    try {
                        const health = entity.getComponent('minecraft:health');
                        if (health) {
                            entity.applyDamage(damage);
                        }
                    } catch { }
                }
            });
        } catch { }

        for (let x = -radius; x <= radius; x++) {
            for (let y = -5; y <= 10; y++) {
                for (let z = -radius; z <= radius; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    if (distance <= radius) {
                        const blockLocation = {
                            x: Math.floor(location.x + x),
                            y: Math.floor(location.y + y),
                            z: Math.floor(location.z + z)
                        };

                        system.runTimeout(() => {
                            try {
                                const block = dimension.getBlock(blockLocation);
                                if (block) {
                                    const typeId = block.typeId;

                                    if (typeId.includes('log') || typeId.includes('leaves') ||
                                        typeId.includes('grass') || typeId.includes('tallgrass') ||
                                        typeId.includes('flower') || typeId.includes('sapling') ||
                                        typeId.includes('bush') || typeId.includes('plant') ||
                                        typeId.includes('fern') || typeId.includes('vine') ||
                                        typeId.includes('mushroom') || typeId.includes('bamboo')) {

                                        dimension.runCommandAsync(`setblock ${blockLocation.x} ${blockLocation.y} ${blockLocation.z} air destroy`);
                                    }

                                    if (y <= 1 && distance < radius / 2) {
                                        if (typeId === 'minecraft:grass_block' || typeId === 'minecraft:grass') {
                                            dimension.runCommandAsync(`setblock ${blockLocation.x} ${blockLocation.y} ${blockLocation.z} dirt`);
                                        } else if (typeId === 'minecraft:stone') {
                                            dimension.runCommandAsync(`setblock ${blockLocation.x} ${blockLocation.y} ${blockLocation.z} cobblestone`);
                                        } else if (typeId === 'minecraft:dirt') {
                                            dimension.runCommandAsync(`setblock ${blockLocation.x} ${blockLocation.y} ${blockLocation.z} coarse_dirt`);
                                        }
                                    }
                                }
                            } catch { }
                        }, Math.floor(distance));
                    }
                }
            }
        }

        try {
            dimension.runCommandAsync(`fill ${Math.floor(location.x - 5)} ${Math.floor(location.y - 2)} ${Math.floor(location.z - 5)} ${Math.floor(location.x + 5)} ${Math.floor(location.y)} ${Math.floor(location.z + 5)} air destroy`);
        } catch { }

        this.playSound(player, 'mob.wither.break_block');
        this.playSound(player, 'random.explode');
        this.playSound(player, 'mob.enderdragon.death');

        player.addEffect('slowness', 40, { amplifier: 3, showParticles: false });
        player.addEffect('blindness', 20, { amplifier: 0, showParticles: false });

        try {
            dimension.runCommandAsync(`title @a[r=${radius}] title §4§l§kXXX §c§lDEVASTATION §4§l§kXXX`);
        } catch { }
    },

    activateDash(player) {
        const armor = this.checkEquippedArmor(player);
        if (!armor.leggings) return;

        const currentTick = world.getAbsoluteTime();
        const lastDash = this.getLastDashTime(player);

        const cooldownRemaining = this.config.dashCooldown - (currentTick - lastDash);
        if (cooldownRemaining > 0) {
            return;
        }

        if (!this.consumeMana(player, 'leggings', this.config.dashManaCost)) {
            this.playSound(player, 'note.bass');
            return;
        }

        try {
            const viewDirection = player.getViewDirection();
            const currentLocation = player.location;

            this.createDashTrail(player, currentLocation, viewDirection);

            const dashForce = 3.0;
            const upwardForce = player.isOnGround ? 0.5 : 0.3;

            const magnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
            const normalizedX = viewDirection.x / magnitude;
            const normalizedZ = viewDirection.z / magnitude;

            player.applyKnockback(
                normalizedX * dashForce,
                normalizedZ * dashForce,
                dashForce,
                upwardForce
            );

            try {
                player.addEffect('speed', 40, { amplifier: 3, showParticles: false });
            } catch { }

            this.setLastDashTime(player, currentTick);

            this.createDashEffects(player, currentLocation, 'start');
            this.playSound(player, 'mob.shulker.shoot');
            this.playSound(player, 'mob.phantom.flap');

            let dashTicks = 0;
            const dashEffect = system.runInterval(() => {
                dashTicks++;

                if (dashTicks > 20) {
                    system.clearRun(dashEffect);
                    return;
                }

                const pos = player.location;
                for (let i = 0; i < 3; i++) {
                    player.dimension.spawnParticle('myw:mythril_particle_serpentine', {
                        x: pos.x + (Math.random() - 0.5) * 0.5,
                        y: pos.y + 0.5 + i * 0.3,
                        z: pos.z + (Math.random() - 0.5) * 0.5
                    });
                }

                if (dashTicks % 3 === 0) {
                    player.dimension.spawnParticle('myw:mythril_particle', {
                        x: pos.x + 1,
                        y: pos.y + 0.5,
                        z: pos.z
                    });
                    player.dimension.spawnParticle('myw:mythril_particle', {
                        x: pos.x - 1,
                        y: pos.y + 0.5,
                        z: pos.z
                    });
                }

            }, 1);

        } catch (error) { }
    },

    createDashTrail(player, startLocation, direction) {
        const dimension = player.dimension;
        const distance = 10;

        for (let line = 0; line < 3; line++) {
            for (let i = 0; i < distance * 2; i++) {
                const offset = i * 0.5;
                const sideOffset = (line - 1) * 0.5;

                const pos = {
                    x: startLocation.x + direction.x * offset + direction.z * sideOffset,
                    y: startLocation.y + direction.y * offset + 0.5 + line * 0.2,
                    z: startLocation.z + direction.z * offset - direction.x * sideOffset
                };

                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle_serpentine', pos);

                    if (i % 2 === 0) {
                        dimension.spawnParticle('myw:mythril_particle_minimalist', {
                            x: pos.x,
                            y: pos.y + 0.3,
                            z: pos.z
                        });
                    }
                }, i);
            }
        }
    },

    activateMagnetism(player) {
        const armor = this.checkEquippedArmor(player);
        if (!armor.chestplate) return;

        const playerId = player.id;

        if (this.activeSessions.has(`${playerId}-magnetism`)) {
            this.deactivateMagnetism(player);
            return;
        }

        if (!this.consumeMana(player, 'chestplate', this.config.magnetismActivationCost)) {
            this.playSound(player, 'note.bass');
            return;
        }

        this.startMagnetismSession(player);
        this.showNotification(player, 'MAGNETISM', 'special');
        this.playSound(player, 'random.orb');
    },

    startMagnetismSession(player) {
        const playerId = player.id;
        let sessionTicks = 0;

        const magnetismInterval = system.runInterval(() => {
            const armor = this.checkEquippedArmor(player);

            if (!armor.chestplate) {
                this.endSession(playerId, 'magnetism');
                return;
            }

            sessionTicks++;

            if (sessionTicks % 20 === 0) {
                if (!this.consumeMana(player, 'chestplate', this.config.magnetismManaCost)) {
                    this.deactivateMagnetism(player);
                    this.playSound(player, 'note.bass');
                    return;
                }
            }

            if (sessionTicks >= this.config.magnetismDuration) {
                this.deactivateMagnetism(player);
                return;
            }

            this.attractNearbyItems(player);

            if (sessionTicks % 20 === 0) {
                this.createMagnetismEffects(player);
            }

        }, 1);

        this.activeSessions.set(`${playerId}-magnetism`, magnetismInterval);
    },

    deactivateMagnetism(player) {
        const playerId = player.id;
        this.endSession(playerId, 'magnetism');
    },

    activateVision(player, isCrown = false) {
        const armor = this.checkEquippedArmor(player);
        if (!armor.helmet && !armor.crown) return;

        const playerId = player.id;
        const piece = isCrown ? 'crown' : 'helmet';
        const manaCost = isCrown ? 100 : this.config.visionActivationCost;

        if (this.activeSessions.has(`${playerId}-vision`)) {
            this.deactivateVision(player, isCrown);
            return;
        }

        if (!this.consumeMana(player, piece, manaCost)) {
            this.playSound(player, 'note.bass');
            return;
        }

        const duration = isCrown ? this.config.crownVisionDuration : this.config.visionDuration;

        player.addEffect('night_vision', duration + 20, { amplifier: 0, showParticles: false });

        if (isCrown) {
            player.addEffect('speed', duration, { amplifier: 1, showParticles: false });
        }

        this.startVisionSession(player, isCrown);

        const message = isCrown ? 'SUPREME' : 'VISION';
        const type = isCrown ? 'legendary' : 'special';
        this.showNotification(player, message, type);
        this.playSound(player, isCrown ? 'mob.wither.spawn' : 'mob.enderdragon.growl');
    },

    startVisionSession(player, isCrown = false) {
        const playerId = player.id;
        let sessionTicks = 0;
        const duration = isCrown ? this.config.crownVisionDuration : this.config.visionDuration;
        const piece = isCrown ? 'crown' : 'helmet';

        const visionInterval = system.runInterval(() => {
            const armor = this.checkEquippedArmor(player);

            if ((!armor.helmet && !armor.crown) || (!armor[piece])) {
                this.endSession(playerId, 'vision');
                return;
            }

            sessionTicks++;

            if (sessionTicks % 20 === 0) {
                const manaCost = isCrown ? 5 : this.config.visionManaCost;
                if (!this.consumeMana(player, piece, manaCost)) {
                    this.deactivateVision(player, isCrown);
                    this.playSound(player, 'note.bass');
                    return;
                }
            }

            if (sessionTicks >= duration) {
                this.deactivateVision(player, isCrown);
                return;
            }

            if (sessionTicks % 5 === 0) {
                this.scanNearbyEntities(player, isCrown);
                this.scanNearbyOres(player, isCrown);
            }

        }, 1);

        this.activeSessions.set(`${playerId}-vision`, visionInterval);
    },

    deactivateVision(player, isCrown = false) {
        const playerId = player.id;

        try {
            player.removeEffect('night_vision');
            if (isCrown) {
                player.removeEffect('speed');
            }
        } catch (error) { }

        this.endSession(playerId, 'vision');
    },

    updateDisplay(player) {
        const armor = this.checkEquippedArmor(player);
        if (!armor.boots && !armor.leggings && !armor.chestplate && !armor.helmet && !armor.crown) {
            return;
        }

        const playerId = player.id;
        const manaData = this.manaSystem.get(playerId);
        if (!manaData) return;

        let totalMana = 0;
        let totalMaxMana = 0;
        let pieceCount = 0;

        const pieces = ['boots', 'leggings', 'chestplate', 'helmet', 'crown'];
        pieces.forEach(piece => {
            if (armor[piece]) {
                totalMana += this.getMana(player, piece);
                totalMaxMana += this.config.maxMana[piece];
                pieceCount++;
            }
        });

        if (pieceCount === 0) return;

        const percentage = (totalMana / totalMaxMana) * 100;
        const barLength = 20;
        const filled = Math.round((percentage / 100) * barLength);

        let color = '§b';
        if (percentage < 20) color = '§4';
        else if (percentage < 40) color = '§c';
        else if (percentage < 60) color = '§e';
        else if (percentage < 80) color = '§a';

        let bar = color + '[';
        for (let i = 0; i < barLength; i++) {
            if (i < filled) {
                bar += '█';
            } else {
                bar += '§8-';
            }
        }
        bar += color + ']';

        let status = '';

        if (manaData.isMeditating && world.getAbsoluteTime() - manaData.meditationStart > 40) {
            status = ' §d◆MEDITATING◆';
        }

        if (this.activeSessions.has(`${playerId}-vision`)) {
            status += ' §b◉VIS';
        }
        if (this.activeSessions.has(`${playerId}-magnetism`)) {
            status += ' §e◉MAG';
        }

        if (armor.leggings) {
            const currentTick = world.getAbsoluteTime();
            const lastDash = this.getLastDashTime(player);
            const cooldown = Math.max(0, Math.ceil((this.config.dashCooldown - (currentTick - lastDash)) / 20));
            if (cooldown > 0) {
                status += ` §c◉CD:${cooldown}`;
            } else {
                status += ' §a◉DASH';
            }
        }

        if (armor.boots) {
            const inputState = this.playerInputStates.get(playerId);
            const jumpsLeft = this.config.maxJumps - (inputState?.airJumpCount || 0);
            status += ` §f◉J:${jumpsLeft}`;
        }

        const display = `§9◆MITHRIL◆ ${bar} §b${Math.round(totalMana)}/${totalMaxMana}${status}`;
        this.showMessage(player, display);
    },

    showMessage(player, message) {
        try {
            player.onScreenDisplay.setActionBar(message);
        } catch (error) { }
    },

    checkEquippedArmor(player) {
        try {
            const equippableComp = player.getComponent('minecraft:equippable');
            if (!equippableComp) {
                return { boots: false, leggings: false, chestplate: false, helmet: false, crown: false };
            }

            const feet = equippableComp.getEquipment(EquipmentSlot.Feet);
            const legs = equippableComp.getEquipment(EquipmentSlot.Legs);
            const chest = equippableComp.getEquipment(EquipmentSlot.Chest);
            const head = equippableComp.getEquipment(EquipmentSlot.Head);

            return {
                boots: feet?.typeId === 'myw:mythril_boots',
                leggings: legs?.typeId === 'myw:mythril_leggings' || legs?.typeId === 'myw:mythril_leggins',
                chestplate: chest?.typeId === 'myw:mythril_chestplate',
                helmet: head?.typeId === 'myw:mythril_helmet',
                crown: head?.typeId === 'myw:mythril_crown'
            };
        } catch (error) {
            return { boots: false, leggings: false, chestplate: false, helmet: false, crown: false };
        }
    },

    getJumpCount(player) {
        try {
            return player.getDynamicProperty('myw:jump_count') ?? 0;
        } catch { return 0; }
    },
    setJumpCount(player, value) {
        try {
            player.setDynamicProperty('myw:jump_count', Math.max(0, value));
        } catch { }
    },

    getLastDashTime(player) {
        try {
            return player.getDynamicProperty('myw:last_dash') ?? 0;
        } catch { return 0; }
    },
    setLastDashTime(player, value) {
        try {
            player.setDynamicProperty('myw:last_dash', value);
        } catch { }
    },

    findSafeDashLocation(player, targetLocation) {
        const dimension = player.dimension;

        for (let yOffset = -1; yOffset <= 2; yOffset++) {
            const checkLocation = {
                x: Math.floor(targetLocation.x),
                y: Math.floor(targetLocation.y) + yOffset,
                z: Math.floor(targetLocation.z)
            };

            try {
                const block = dimension.getBlock(checkLocation);
                const blockAbove = dimension.getBlock({
                    x: checkLocation.x,
                    y: checkLocation.y + 1,
                    z: checkLocation.z
                });

                if (block && blockAbove) {
                    if (block.typeId === 'minecraft:air' && blockAbove.typeId === 'minecraft:air') {
                        return {
                            x: checkLocation.x + 0.5,
                            y: checkLocation.y + 0.1,
                            z: checkLocation.z + 0.5
                        };
                    }
                }
            } catch (error) {
                continue;
            }
        }

        return targetLocation;
    },

    attractNearbyItems(player) {
        try {
            const playerLocation = player.location;
            const dimension = player.dimension;

            const nearbyItems = dimension.getEntities({
                location: playerLocation,
                maxDistance: this.config.magnetismRadius,
                type: 'minecraft:item'
            });

            nearbyItems.forEach(item => {
                try {
                    const direction = {
                        x: playerLocation.x - item.location.x,
                        y: playerLocation.y + 1 - item.location.y,
                        z: playerLocation.z - item.location.z
                    };

                    const distance = Math.sqrt(direction.x ** 2 + direction.y ** 2 + direction.z ** 2);
                    if (distance > 0.8) {
                        const force = 0.4;
                        item.applyImpulse({
                            x: (direction.x / distance) * force,
                            y: (direction.y / distance) * force,
                            z: (direction.z / distance) * force
                        });
                    }
                } catch (error) { }
            });

        } catch (error) { }
    },

    scanNearbyEntities(player, isCrown = false) {
        try {
            const radius = isCrown ? this.config.crownEntityRadius : this.config.entityDetectionRadius;
            const nearbyEntities = player.dimension.getEntities({
                location: player.location,
                maxDistance: radius,
                excludeTypes: ['minecraft:item', 'minecraft:xp_orb']
            });

            nearbyEntities.forEach(entity => {
                if (entity.id !== player.id) {
                    this.highlightEntity(entity, isCrown);
                }
            });
        } catch (error) { }
    },

    scanNearbyOres(player, isCrown = false) {
        try {
            const radius = isCrown ? this.config.crownOreRadius : this.config.oreDetectionRadius;
            const playerLocation = player.location;
            const dimension = player.dimension;

            for (let attempts = 0; attempts < 15; attempts++) {
                const x = Math.floor(playerLocation.x) + Math.floor((Math.random() - 0.5) * radius * 2);
                const y = Math.floor(playerLocation.y) + Math.floor((Math.random() - 0.5) * radius * 2);
                const z = Math.floor(playerLocation.z) + Math.floor((Math.random() - 0.5) * radius * 2);

                try {
                    const block = dimension.getBlock({ x, y, z });
                    if (block && block.typeId.includes('_ore')) {
                        this.highlightOre(dimension, { x, y, z }, block.typeId);
                    }
                } catch (error) { }
            }
        } catch (error) { }
    },

    createJumpEffects(player, jumpNumber) {
        try {
            const location = player.location;
            const dimension = player.dimension;

            const intensity = Math.min(jumpNumber, 5);

            for (let i = 0; i < intensity * 4; i++) {
                const angle = (i / (intensity * 4)) * Math.PI * 2;
                const radius = 1.5 + (intensity * 0.3);

                dimension.spawnParticle('minecraft:sonic_explosion', {
                    x: location.x + Math.cos(angle) * radius,
                    y: location.y - 0.3,
                    z: location.z + Math.sin(angle) * radius
                });
            }

            if (jumpNumber >= 3) {
                for (let i = 0; i < jumpNumber * 2; i++) {
                    dimension.spawnParticle('minecraft:wind_explosion_emitter', {
                        x: location.x + (Math.random() - 0.5) * 3,
                        y: location.y + Math.random() * 2,
                        z: location.z + (Math.random() - 0.5) * 3
                    });
                }
            }

            if (jumpNumber === 4) {
                for (let i = 0; i < 6; i++) {
                    dimension.spawnParticle('myw:mythril_particle', {
                        x: location.x + (Math.random() - 0.5) * 2,
                        y: location.y + 3,
                        z: location.z + (Math.random() - 0.5) * 2
                    });
                }
            }

        } catch (error) { }
    },

    createDashEffects(player, location, type) {
        try {
            const dimension = player.dimension;

            if (type === 'start') {
                for (let i = 0; i < 16; i++) {
                    const angle = (i / 16) * Math.PI * 2;
                    const radius = 2.5;

                    dimension.spawnParticle('myw:mythril_particle_serpentine', {
                        x: location.x + Math.cos(angle) * radius,
                        y: location.y + 0.5,
                        z: location.z + Math.sin(angle) * radius
                    });
                }

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

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

                    dimension.spawnParticle('myw:mythril_particle', {
                        x: location.x + Math.cos(angle) * 1.5,
                        y: location.y + 0.1,
                        z: location.z + Math.sin(angle) * 1.5
                    });
                }

                for (let i = 0; i < 5; i++) {
                    dimension.spawnParticle('myw:mythril_particle_minimalist', {
                        x: location.x,
                        y: location.y + 0.5 + i * 0.2,
                        z: location.z
                    });
                }
            }
        } catch (error) { }
    },

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

            for (let ring = 1; ring <= 3; ring++) {
                const numParticles = ring * 4;
                const radius = ring * 1.5;

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

                    const particle = ring % 2 === 0 ?
                        'myw:mythril_particle_minimalist' :
                        'myw:mythril_particle';

                    dimension.spawnParticle(particle, {
                        x: location.x + Math.cos(angle) * radius,
                        y: location.y + 0.8 + (ring * 0.3),
                        z: location.z + Math.sin(angle) * radius
                    });
                }
            }
        } catch (error) { }
    },

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

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

                dimension.spawnParticle('myw:mythril_particle_minimalist', {
                    x: location.x + Math.cos(angle) * 1,
                    y: location.y + 2,
                    z: location.z + Math.sin(angle) * 1
                });
            }

            dimension.spawnParticle('myw:mythril_particle_serpentine', {
                x: location.x,
                y: location.y + 2.5,
                z: location.z
            });
        } catch (error) { }
    },

    highlightEntity(entity, isCrown = false) {
        try {
            const location = entity.location;
            const dimension = entity.dimension;

            const particle = isCrown ?
                'myw:mythril_particle' :
                'myw:mythril_particle_minimalist';

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

                dimension.spawnParticle(particle, {
                    x: location.x + Math.cos(angle) * 1.2,
                    y: location.y + 1.5,
                    z: location.z + Math.sin(angle) * 1.2
                });
            }

            if (isCrown) {
                dimension.spawnParticle('myw:mythril_particle_serpentine', {
                    x: location.x,
                    y: location.y + 2.5,
                    z: location.z
                });
            }
        } catch (error) { }
    },

    highlightOre(dimension, location, oreType) {
        try {
            let particle = 'myw:mythril_particle_minimalist';

            if (oreType.includes('diamond')) {
                particle = 'myw:mythril_particle';
            } else if (oreType.includes('ancient_debris')) {
                particle = 'myw:mythril_particle_serpentine';
            }

            dimension.spawnParticle(particle, {
                x: location.x + 0.5,
                y: location.y + 0.5,
                z: location.z + 0.5
            });
        } catch (error) { }
    },

    playSound(player, soundId) {
        try {
            player.playSound(soundId, { volume: 0.8, pitch: 1.0 });
        } catch (error) {
            try {
                player.dimension.runCommandAsync(`playsound ${soundId} @p ~ ~ ~ 0.8 1.0`);
            } catch (cmdError) { }
        }
    },

    endSession(playerId, sessionType) {
        const sessionKey = `${playerId}-${sessionType}`;
        const sessionInterval = this.activeSessions.get(sessionKey);

        if (sessionInterval) {
            system.clearRun(sessionInterval);
            this.activeSessions.delete(sessionKey);
        }
    },

    cleanupPlayer(playerId) {
        this.activePlayers.delete(playerId);
        this.playerInputStates.delete(playerId);
        this.manaSystem.delete(playerId);

        const sessionsToDelete = [];
        for (const [key, interval] of this.activeSessions.entries()) {
            if (key.startsWith(playerId + '-')) {
                system.clearRun(interval);
                sessionsToDelete.push(key);
            }
        }

        sessionsToDelete.forEach(key => this.activeSessions.delete(key));
    }
};

export function registerMythrilBoots(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_boots', {});
}

export function registerMythrilLeggings(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_leggings', {});
    itemComponentRegistry.registerCustomComponent('myw:mythril_leggins', {});
}

export function registerMythrilChestplate(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_chestplate', {});
}

export function registerMythrilHelmet(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_helmet', {});
}

export function registerMythrilCrown(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:mythril_crown', {});
}

export function initializeMythrilArmorSystems() {
    system.runInterval(() => {
        try {
            world.getAllPlayers().forEach(player => {
                const playerId = player.id;
                const armor = MythrilArmorSystem.checkEquippedArmor(player);

                const hasAnyArmor = armor.boots || armor.leggings || armor.chestplate || armor.helmet || armor.crown;

                if (hasAnyArmor) {
                    if (!MythrilArmorSystem.activePlayers.has(playerId)) {
                        MythrilArmorSystem.initializePlayer(player);
                    }

                    MythrilArmorSystem.regenerateMana(player);

                    if (armor.boots) {
                        player.addEffect('speed', 60, {
                            amplifier: MythrilArmorSystem.config.speedBoostAmplifier,
                            showParticles: false
                        });
                        player.addEffect('jump_boost', 60, {
                            amplifier: MythrilArmorSystem.config.jumpBoostAmplifier,
                            showParticles: false
                        });

                        // Aplicar resistencia nivel 5 para reducir todo el daño en 100%
                        // pero solo cuando está cayendo para prevenir daño de caída
                        if (!player.isOnGround && player.getVelocity().y < -0.5) {
                            player.addEffect('resistance', 5, {
                                amplifier: 4, // Resistencia V = 100% reducción de daño
                                showParticles: false
                            });
                        }
                    }

                    if (armor.crown) {
                        player.addEffect('regeneration', 60, { amplifier: 0, showParticles: false });
                    }

                    MythrilArmorSystem.updatePlayerInput(player);

                } else {
                    if (MythrilArmorSystem.activePlayers.has(playerId)) {
                        MythrilArmorSystem.cleanupPlayer(playerId);
                    }
                }
            });
        } catch (error) {
            world.sendMessage('§c[ERROR] System: ' + error.message);
        }
    }, 1);

    system.runInterval(() => {
        try {
            world.getAllPlayers().forEach(player => {
                if (MythrilArmorSystem.activePlayers.has(player.id)) {
                    MythrilArmorSystem.updateDisplay(player);
                }
            });
        } catch (error) { }
    }, 20);

    world.afterEvents.playerLeave.subscribe(eventData => {
        MythrilArmorSystem.cleanupPlayer(eventData.playerId);
    });

    world.sendMessage('§b================================');
    world.sendMessage('§6    MITHRIL ARMOR SYSTEM v3.1   ');
    world.sendMessage('§b================================');
    world.sendMessage('§fCONTROLS:');
    world.sendMessage('§a  Boots: Auto jump in air (5x = ULTIMATE)');
    world.sendMessage('§d  Leggings: Double-Jump for Dash');
    world.sendMessage('§e  Chestplate: Double-Sneak for Magnetism');
    world.sendMessage('§b  Helmet: Hold Sneak 2s for Vision');
    world.sendMessage('§6  Crown: Hold Sneak 2s for SUPREME Vision');
    world.sendMessage('§b================================');
    world.sendMessage('§dTIP: Crouch without moving 2s to');
    world.sendMessage('§d     meditate and regenerate mana x2.5');
    world.sendMessage('§b================================');
    world.sendMessage('§3Custom Mythril particles active!');
}