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

export const CarmotArmorSystem = {
    config: {
        // Energy system
        maxEnergy: {
            boots: 50,
            leggings: 50,
            chestplate: 60,
            helmet: 40,
            crown: 40
        },

        // BOOTS - Permanent Phase Walk
        phaseWalkPassive: true,
        phaseStepHeight: 3,
        voidWalkBonus: 2,
        phaseWalkEnergyPerMove: 2, // Energy cost when moving

        // LEGGINGS - Reality Control
        gravityFieldRadius: 15,
        gravityFieldEnergyCost: 60,
        gravityManipulationCost: 3,
        realityWarpRadius: 20,
        realityAnchorCost: 80,
        realityHoldTime: 60, // 3 seconds (60 ticks)

        // CHESTPLATE - Time Manipulation
        timeStopRadius: 18,
        timeStopDuration: 60,
        timeStopEnergyCost: 70,
        rewindDuration: 100,
        rewindEnergyCost: 50,
        chronoShieldCost: 40,

        // HELMET - Attraction Ray (Extended)
        attractionRayRange: 50, // Extended from 30
        attractionRayForce: 8, // Increased from 5
        attractionRayEnergyCost: 25,
        attractionRayDrainPerTick: 3,
        megaRayEnergyCost: 100,
        rayDamage: 15, // Increased from 10

        // CROWN - Ultimate Powers
        ultimateSlashDamage: 2500, // Massively increased
        ultimateSlashRadius: 50, // Doubled range
        ultimateSlashMinEnergy: 300, // Need 300 total energy
        dimensionalRiftDuration: 200,
        crownAuraRadius: 15,
        ultimateCooldown: 400, // 20 seconds

        energyRegen: {
            base: 4,
            moving: 5,
            combat: 2,
            crown: 8
        }
    },

    activePlayers: new Map(),
    energySystem: new Map(),
    playerStates: new Map(),
    timelineHistory: new Map(),
    gravityFields: new Map(),
    attractionBeams: new Map(),

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

        // Initialize energy
        this.energySystem.set(playerId, {
            boots: this.config.maxEnergy.boots,
            leggings: this.config.maxEnergy.leggings,
            chestplate: this.config.maxEnergy.chestplate,
            helmet: this.config.maxEnergy.helmet,
            crown: this.config.maxEnergy.crown
        });

        // Initialize states
        this.playerStates.set(playerId, {
            // Boots
            isPhasingActive: true, // Always active with boots

            // Leggings - Reality control hold tracking
            realityHoldStart: 0,
            isHoldingSneak: false,
            realityReady: true,
            realityActivationTime: 0,
            hasGravityField: false,
            gravityIntensity: 1,

            // Chestplate
            isTimeStopped: false,
            timelinePosition: 0,

            // Helmet
            isChannelingRay: false,
            rayTarget: null,

            // Crown
            ultimateReady: true,
            lastUltimateTime: 0,

            // General
            lastMovementTime: 0,
            positionHistory: [],
            healthHistory: []
        });

        this.timelineHistory.set(playerId, []);
        this.activePlayers.set(playerId, true);

        this.showActivation(player);
    },

    // BOOTS - Permanent Phase Walking
    handlePhaseWalk(player) {
        const state = this.playerStates.get(player.id);
        if (!state?.isPhasingActive) return;

        try {
            const velocity = player.getVelocity();
            const viewDir = player.getViewDirection();
            const location = player.location;
            const dimension = player.dimension;

            // Allow walking through walls when moving
            if (Math.abs(velocity.x) > 0.1 || Math.abs(velocity.z) > 0.1) {
                // Check blocks ahead
                const checkDistance = 2;
                for (let i = 1; i <= checkDistance; i++) {
                    const checkPos = {
                        x: Math.floor(location.x + viewDir.x * i),
                        y: Math.floor(location.y),
                        z: Math.floor(location.z + viewDir.z * i)
                    };

                    try {
                        const block = dimension.getBlock(checkPos);
                        if (block && block.typeId !== 'minecraft:air') {
                            // Phase through the block
                            this.createPhaseEffect(player, checkPos);

                            // Allow passage
                            player.addEffect('resistance', 5, {
                                amplifier: 4,
                                showParticles: false
                            });
                        }
                    } catch { }
                }
            }

            // Vertical phasing when looking up/down strongly
            if (Math.abs(viewDir.y) > 0.7) {
                const phaseForce = viewDir.y * 0.8;
                player.applyKnockback(0, 0, 0, phaseForce);

                // Create vertical phase trail
                this.createVerticalPhaseTrail(player);
            }

            // Void walking - walk on air when sneaking
            if (player.isSneaking && !player.isOnGround) {
                player.addEffect('levitation', 5, {
                    amplifier: 0,
                    showParticles: false
                });

                // Create platform effect
                if (world.getAbsoluteTime() % 10 === 0) {
                    this.createVoidPlatform(player);
                }
            }

            // Continuous phase particles
            if (world.getAbsoluteTime() % 5 === 0) {
                this.createPhaseAura(player);
            }

        } catch { }
    },

    // LEGGINGS - Reality Control (Hold sneak for 3 seconds)
    activateRealityControl(player) {
        const state = this.playerStates.get(player.id);

        if (state?.hasGravityField) {
            this.deactivateRealityControl(player);
            return;
        }

        if (!this.consumeEnergy(player, 'leggings', this.config.gravityFieldEnergyCost)) {
            this.playSound(player, 'note.bass');
            this.showMessage(player, '§cInsufficient energy for Reality Control!');
            return;
        }

        state.hasGravityField = true;

        this.showNotification(player, '◎ REALITY CONTROL ◎', 'legendary');
        this.playSound(player, 'mob.wither.spawn');

        // Create reality manipulation field
        const gravityInterval = system.runInterval(() => {
            if (!state.hasGravityField) {
                system.clearRun(gravityInterval);
                return;
            }

            this.manipulateReality(player);

            // Energy drain every second
            if (world.getAbsoluteTime() % 20 === 0) {
                if (!this.consumeEnergy(player, 'leggings', this.config.gravityManipulationCost)) {
                    this.deactivateRealityControl(player);
                    this.showMessage(player, '§cReality Control deactivated - No energy!');
                }
            }

        }, 1);

        this.gravityFields.set(player.id, gravityInterval);
    },

    manipulateReality(player) {
        try {
            const location = player.location;
            const dimension = player.dimension;
            const state = this.playerStates.get(player.id);

            // Anti-gravity for player - Now with levitation
            player.addEffect('slow_falling', 10, {
                amplifier: 2,
                showParticles: false
            });

            player.addEffect('levitation', 10, {
                amplifier: 0,
                showParticles: false
            });

            // Reality warping field
            const entities = dimension.getEntities({
                location: location,
                maxDistance: this.config.gravityFieldRadius,
                excludeFamilies: ['player']
            });

            entities.forEach(entity => {
                const dist = this.getDistance(location, entity.location);
                const force = (1 - dist / this.config.gravityFieldRadius);

                // Gravity manipulation based on player's view
                const viewDir = player.getViewDirection();

                if (player.isSneaking) {
                    // Reverse gravity - entities float up
                    entity.applyKnockback(0, 0, 0, force * 0.8);
                } else {
                    // Orbital gravity - entities orbit around player
                    const angle = Math.atan2(
                        entity.location.z - location.z,
                        entity.location.x - location.x
                    ) + 0.1;

                    const orbitX = Math.cos(angle) * dist;
                    const orbitZ = Math.sin(angle) * dist;

                    entity.teleport({
                        x: location.x + orbitX,
                        y: entity.location.y,
                        z: location.z + orbitZ
                    });
                }

                // Slow entities in the field
                entity.addEffect('slowness', 5, {
                    amplifier: Math.floor(force * 3),
                    showParticles: false
                });
            });

            // Visual reality distortion
            this.createRealityDistortion(player);

        } catch { }
    },

    deactivateRealityControl(player) {
        const playerId = player.id;
        const state = this.playerStates.get(playerId);

        if (state) {
            state.hasGravityField = false;
        }

        const interval = this.gravityFields.get(playerId);
        if (interval) {
            system.clearRun(interval);
            this.gravityFields.delete(playerId);
        }
    },

    // CHESTPLATE - Time Manipulation (Sneak + Jump activation)
    activateTimeManipulation(player) {
        const state = this.playerStates.get(player.id);

        // Toggle between time stop and rewind based on sprint
        if (player.isSprinting) {
            this.activateTimeStop(player);
        } else {
            this.activateTimeRewind(player);
        }
    },

    activateTimeStop(player) {
        if (!this.consumeEnergy(player, 'chestplate', this.config.timeStopEnergyCost)) {
            this.playSound(player, 'note.bass');
            this.showMessage(player, '§cInsufficient energy for Time Stop!');
            return;
        }

        const location = player.location;
        const dimension = player.dimension;

        this.showNotification(player, '⧗ TIME STOP ⧗', 'legendary');
        this.playSound(player, 'mob.warden.heartbeat');

        // Create time stop field
        try {
            const entities = dimension.getEntities({
                location: location,
                maxDistance: this.config.timeStopRadius,
                excludeFamilies: ['player']
            });

            entities.forEach(entity => {
                // Freeze entities completely
                entity.addEffect('slowness', this.config.timeStopDuration, {
                    amplifier: 255,
                    showParticles: false
                });

                entity.addEffect('weakness', this.config.timeStopDuration, {
                    amplifier: 255,
                    showParticles: false
                });

                entity.addEffect('mining_fatigue', this.config.timeStopDuration, {
                    amplifier: 255,
                    showParticles: false
                });

                // Visual freeze
                this.createTimeFreezeEffect(entity);
            });

        } catch { }

        // Time field visuals
        this.createTimeStopField(player);
    },

    activateTimeRewind(player) {
        const timeline = this.timelineHistory.get(player.id);

        if (!timeline || timeline.length < 10) {
            this.showMessage(player, '§cNot enough timeline data!');
            return;
        }

        if (!this.consumeEnergy(player, 'chestplate', this.config.rewindEnergyCost)) {
            this.playSound(player, 'note.bass');
            this.showMessage(player, '§cInsufficient energy for Time Rewind!');
            return;
        }

        // Get position from 5 seconds ago
        const rewindIndex = Math.max(0, timeline.length - 100);
        const rewindData = timeline[rewindIndex];

        if (rewindData) {
            // Create epic rewind effect
            this.createRewindEffect(player, player.location, rewindData.position);

            // Restore position
            player.teleport(rewindData.position);

            // Restore health
            try {
                const health = player.getComponent('minecraft:health');
                if (health && rewindData.health > health.currentValue) {
                    health.setCurrentValue(rewindData.health);
                }
            } catch { }

            // Clear timeline
            timeline.splice(rewindIndex);

            this.showNotification(player, '⟲ CHRONO REWIND ⟲', 'time');
            this.playSound(player, 'mob.warden.sonic_boom');
        }
    },

    // HELMET - Mega Attraction Ray
    activateAttractionRay(player) {
        const state = this.playerStates.get(player.id);

        if (state?.isChannelingRay) {
            this.deactivateAttractionRay(player);
            return;
        }

        if (!this.consumeEnergy(player, 'helmet', this.config.attractionRayEnergyCost)) {
            this.playSound(player, 'note.bass');
            this.showMessage(player, '§cInsufficient energy for Attraction Ray!');
            return;
        }

        state.isChannelingRay = true;

        this.showNotification(player, '⚡ ATTRACTION RAY ⚡', 'electric');
        this.playSound(player, 'mob.shulker.shoot');

        // Channel the ray
        const rayInterval = system.runInterval(() => {
            if (!state.isChannelingRay) {
                system.clearRun(rayInterval);
                return;
            }

            this.fireAttractionBeam(player);

            // Energy drain - FIXED to actually consume every 5 ticks
            if (world.getAbsoluteTime() % 5 === 0) {
                if (!this.consumeEnergy(player, 'helmet', this.config.attractionRayDrainPerTick)) {
                    this.deactivateAttractionRay(player);
                    this.showMessage(player, '§cAttraction Ray deactivated - No energy!');
                }
            }

        }, 1);

        this.attractionBeams.set(player.id, rayInterval);
    },

    fireAttractionBeam(player) {
        try {
            const viewDir = player.getViewDirection();
            const location = player.location;
            const dimension = player.dimension;

            // EXTENDED Ray cast to 50 blocks
            const extendedRange = 50;

            for (let i = 1; i <= extendedRange; i++) {
                const checkPos = {
                    x: location.x + viewDir.x * i,
                    y: location.y + 1.5 + viewDir.y * i,
                    z: location.z + viewDir.z * i
                };

                // MORE PARTICLES for better visibility
                dimension.spawnParticle('myw:carmot_particle_serpentine', checkPos);

                // Extra particles every 2 blocks
                if (i % 2 === 0) {
                    dimension.spawnParticle('myw:carmot_particle', checkPos);

                    // Side particles for beam width
                    const perpX = -viewDir.z * 0.3;
                    const perpZ = viewDir.x * 0.3;

                    dimension.spawnParticle('myw:carmot_particle_gravity', {
                        x: checkPos.x + perpX,
                        y: checkPos.y,
                        z: checkPos.z + perpZ
                    });

                    dimension.spawnParticle('myw:carmot_particle_gravity', {
                        x: checkPos.x - perpX,
                        y: checkPos.y,
                        z: checkPos.z - perpZ
                    });
                }

                // Check for entities
                const entities = dimension.getEntities({
                    location: checkPos,
                    maxDistance: 2.5,
                    excludeFamilies: ['player']
                });

                if (entities.length > 0) {
                    const target = entities[0];

                    // Pull target with MASSIVE force
                    const pullDir = {
                        x: location.x - target.location.x,
                        y: location.y - target.location.y + 1,
                        z: location.z - target.location.z
                    };

                    const dist = Math.sqrt(pullDir.x ** 2 + pullDir.y ** 2 + pullDir.z ** 2);

                    if (dist > 0) {
                        const force = 8; // Increased force

                        target.applyKnockback(
                            (pullDir.x / dist) * force,
                            (pullDir.z / dist) * force,
                            force,
                            (pullDir.y / dist) * force * 0.8
                        );

                        // More damage on contact
                        if (dist < 3) {
                            target.applyDamage(15);
                            this.createElectricExplosion(target.location, dimension);
                        }
                    }

                    break;
                }
            }

        } catch { }
    },

    deactivateAttractionRay(player) {
        const state = this.playerStates.get(player.id);
        if (state) {
            state.isChannelingRay = false;
        }

        const interval = this.attractionBeams.get(player.id);
        if (interval) {
            system.clearRun(interval);
            this.attractionBeams.delete(player.id);
        }
    },

    // CROWN - Dimensional Ultimate Slash
    activateUltimateSlash(player) {
        const state = this.playerStates.get(player.id);
        const armor = this.checkEquippedArmor(player);

        // MUST have FULL armor set
        if (!armor.boots || !armor.leggings || !armor.chestplate || !armor.helmet || !armor.crown) {
            this.showMessage(player, '§cNeed FULL Carmot armor set for Ultimate!');
            return;
        }

        if (!state?.ultimateReady) {
            const cooldown = 400 - (world.getAbsoluteTime() - state.lastUltimateTime);
            if (cooldown > 0) {
                this.showMessage(player, `§cUltimate ready in ${Math.ceil(cooldown / 20)}s`);
                return;
            }
        }

        // Consume ALL energy from ALL pieces for ultimate
        const energy = this.energySystem.get(player.id);
        const totalEnergy = energy.boots + energy.leggings + energy.chestplate + energy.helmet + energy.crown;

        if (totalEnergy < 300) {
            this.showMessage(player, '§cNeed 300+ total energy!');
            return;
        }

        // Drain all energy
        energy.boots = 0;
        energy.leggings = 0;
        energy.chestplate = 0;
        energy.helmet = 0;
        energy.crown = 0;

        state.ultimateReady = false;
        state.lastUltimateTime = world.getAbsoluteTime();

        // APOCALYPTIC DIMENSIONAL SLASH
        this.executeApocalypticSlash(player);
    },

    executeApocalypticSlash(player) {
        const location = player.location;
        const dimension = player.dimension;
        const viewDir = player.getViewDirection();

        this.showNotification(player, '§5§l◆◆◆ APOCALYPTIC SLASH ◆◆◆', 'ultimate');

        // Multiple sound layers
        this.playSound(player, 'mob.enderdragon.death');
        this.playSound(player, 'mob.wither.death');
        this.playSound(player, 'mob.warden.death');

        // Phase 1: Dimensional Tear Charge
        for (let i = 0; i < 30; i++) {
            system.runTimeout(() => {
                // Spiraling energy vortex
                const radius = (30 - i) / 3;
                const height = i * 0.5;

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

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

                    // Inner vortex
                    if (j % 2 === 0) {
                        dimension.spawnParticle('myw:carmot_particle_serpentine', {
                            x: location.x + Math.cos(angle) * (radius / 2),
                            y: location.y + height + 2,
                            z: location.z + Math.sin(angle) * (radius / 2)
                        });
                    }
                }

                // Screen shake effect
                if (i % 5 === 0) {
                    try {
                        dimension.runCommandAsync(`camerashake add @a[r=50] 1 1 positional`);
                    } catch { }
                }
            }, i);
        }

        // Phase 2: The Apocalyptic Slash - 3 WAVES
        system.runTimeout(() => {
            // WAVE 1 - Main slash
            for (let dist = 0; dist <= 50; dist++) {
                system.runTimeout(() => {
                    const slashPos = {
                        x: location.x + viewDir.x * dist,
                        y: location.y + 1,
                        z: location.z + viewDir.z * dist
                    };

                    // Massive vertical tear
                    for (let height = -10; height <= 30; height++) {
                        dimension.spawnParticle('myw:carmot_particle_serpentine', {
                            x: slashPos.x,
                            y: slashPos.y + height,
                            z: slashPos.z
                        });

                        // Side tears
                        if (height % 2 === 0) {
                            for (let side = -10; side <= 10; side += 2) {
                                dimension.spawnParticle('myw:carmot_particle_gravity', {
                                    x: slashPos.x + side,
                                    y: slashPos.y + height,
                                    z: slashPos.z + side
                                });
                            }
                        }
                    }

                    // TOTAL ANNIHILATION
                    try {
                        const nearbyEntities = dimension.getEntities({
                            location: slashPos,
                            maxDistance: 15,
                            excludeFamilies: ['player']
                        });

                        nearbyEntities.forEach(entity => {
                            // Instant erasure
                            entity.kill();
                            this.createDimensionalCollapse(entity.location, dimension);
                        });

                        // MASSIVE terrain destruction
                        for (let x = -8; x <= 8; x++) {
                            for (let y = -5; y <= 20; y++) {
                                for (let z = -8; z <= 8; z++) {
                                    const blockPos = {
                                        x: Math.floor(slashPos.x + x),
                                        y: Math.floor(slashPos.y + y),
                                        z: Math.floor(slashPos.z + z)
                                    };

                                    try {
                                        const block = dimension.getBlock(blockPos);
                                        if (block && !block.typeId.includes('bedrock')) {
                                            if (Math.random() > 0.3) { // 70% destruction
                                                dimension.runCommandAsync(
                                                    `setblock ${blockPos.x} ${blockPos.y} ${blockPos.z} air destroy`
                                                );
                                            }
                                        }
                                    } catch { }
                                }
                            }
                        }

                    } catch { }

                }, dist * 2);
            }

            // WAVE 2 - Side slashes (45 degrees)
            system.runTimeout(() => {
                const leftDir = {
                    x: viewDir.x * 0.707 - viewDir.z * 0.707,
                    y: viewDir.y,
                    z: viewDir.z * 0.707 + viewDir.x * 0.707
                };

                const rightDir = {
                    x: viewDir.x * 0.707 + viewDir.z * 0.707,
                    y: viewDir.y,
                    z: viewDir.z * 0.707 - viewDir.x * 0.707
                };

                // Left slash
                for (let dist = 0; dist <= 35; dist++) {
                    system.runTimeout(() => {
                        this.createSecondarySlash(player, leftDir, dist);
                    }, dist);
                }

                // Right slash
                for (let dist = 0; dist <= 35; dist++) {
                    system.runTimeout(() => {
                        this.createSecondarySlash(player, rightDir, dist);
                    }, dist);
                }
            }, 30);

            // WAVE 3 - Dimensional implosion
            system.runTimeout(() => {
                // Pull everything back
                const implosionRadius = 60;

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

                    allEntities.forEach(entity => {
                        const pullDir = {
                            x: location.x - entity.location.x,
                            y: location.y - entity.location.y + 10,
                            z: location.z - entity.location.z
                        };

                        const dist = Math.sqrt(pullDir.x ** 2 + pullDir.z ** 2);
                        if (dist > 0) {
                            entity.applyKnockback(
                                (pullDir.x / dist) * 10,
                                (pullDir.z / dist) * 10,
                                10,
                                2
                            );
                        }

                        // Damage based on distance
                        const damage = Math.max(100, 500 - dist * 5);
                        entity.applyDamage(damage);
                    });
                } catch { }

                // Final explosion
                this.createApocalypticExplosion(location, dimension);

            }, 80);

            // Screen effect
            try {
                dimension.runCommandAsync(`title @a[r=60] title §5§k|||§r §4§lAPOCALYPSE§r §5§k|||§r`);
                dimension.runCommandAsync(`title @a[r=60] subtitle §c§lReality has been torn asunder`);
            } catch { }

        }, 30);

        // Phase 3: Aftermath - Dimensional scars remain
        system.runTimeout(() => {
            // Lingering rifts
            for (let i = 0; i < 200; i++) {
                system.runTimeout(() => {
                    const dist = Math.random() * 40;
                    const angle = Math.random() * Math.PI * 2;

                    dimension.spawnParticle('myw:carmot_particle', {
                        x: location.x + Math.cos(angle) * dist,
                        y: location.y + Math.random() * 30,
                        z: location.z + Math.sin(angle) * dist
                    });
                }, i);
            }

            const state = this.playerStates.get(player.id);
            if (state) {
                state.ultimateReady = true;
            }

        }, 120);
    },

    createSecondarySlash(player, direction, distance) {
        try {
            const location = player.location;
            const dimension = player.dimension;

            const slashPos = {
                x: location.x + direction.x * distance,
                y: location.y + 1,
                z: location.z + direction.z * distance
            };

            // Slash visuals
            for (let height = -5; height <= 15; height += 2) {
                dimension.spawnParticle('myw:carmot_particle_gravity', {
                    x: slashPos.x,
                    y: slashPos.y + height,
                    z: slashPos.z
                });
            }

            // Destruction
            const entities = dimension.getEntities({
                location: slashPos,
                maxDistance: 8,
                excludeFamilies: ['player']
            });

            entities.forEach(entity => {
                entity.applyDamage(200);
            });
        } catch { }
    },

    createApocalypticExplosion(location, dimension) {
        try {
            // Massive final explosion
            for (let ring = 1; ring <= 10; ring++) {
                system.runTimeout(() => {
                    const radius = ring * 6;
                    const particles = ring * 12;

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

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

                    // Shockwave
                    dimension.spawnParticle('minecraft:dragon_death_explosion_emitter', {
                        x: location.x,
                        y: location.y + ring,
                        z: location.z
                    });

                }, ring * 2);
            }

            // Final sound
            this.playSound({ location }, 'random.explode');

        } catch (error) {
            console.error("Error en createApocalypticExplosion:", error);
        }
    },

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

            nearbyEntities.forEach(entity => {
                // Dimensional erasure
                entity.kill();
                this.createDimensionalCollapse(entity.location, dimension);
            });

            // Terrain destruction
            for (let x = -3; x <= 3; x++) {
                for (let y = -2; y <= 10; y++) {
                    for (let z = -3; z <= 3; z++) {
                        const blockPos = {
                            x: Math.floor(slashPos.x + x),
                            y: Math.floor(slashPos.y + y),
                            z: Math.floor(slashPos.z + z)
                        };

                        try {
                            const block = dimension.getBlock(blockPos);
                            if (block && !block.typeId.includes('bedrock')) {
                                dimension.runCommandAsync(
                                    `setblock ${blockPos.x} ${blockPos.y} ${blockPos.z} air destroy`
                                );
                            }
                        } catch (blockError) {
                            console.error("Error al destruir bloque:", blockError);
                        }
                    }
                }
            }

        } catch (error) {
            console.error("Error en destroyEverythingInPath:", error);
        }
    },

    // CROWN PASSIVE - Dimensional Aura
    applyCrownAura(player) {
        try {
            const location = player.location;
            const dimension = player.dimension;

            // Allies get buffs
            const allies = dimension.getEntities({
                location: location,
                maxDistance: this.config.crownAuraRadius,
                families: ['player']
            });

            allies.forEach(ally => {
                if (ally.id !== player.id) {
                    ally.addEffect('strength', 60, { amplifier: 1, showParticles: false });
                    ally.addEffect('resistance', 60, { amplifier: 0, showParticles: false });
                }
            });

            // Enemies get debuffs
            const enemies = dimension.getEntities({
                location: location,
                maxDistance: this.config.crownAuraRadius,
                excludeFamilies: ['player']
            });

            enemies.forEach(enemy => {
                enemy.addEffect('wither', 20, { amplifier: 0, showParticles: false });
            });

            // Visual aura
            if (world.getAbsoluteTime() % 20 === 0) {
                this.createCrownAura(player);
            }

        } catch (error) {
            console.error("Error en applyCrownAura:", error);
        }
    },

    // Input handling
    updatePlayerInput(player) {
        const playerId = player.id;
        const armor = this.checkEquippedArmor(player);
        const currentTime = world.getAbsoluteTime();
        const state = this.playerStates.get(playerId);

        // BOOTS - Always active phasing - COSTS ENERGY WHEN MOVING
        if (armor.boots) {
            this.handlePhaseWalk(player);

            // Drain energy when moving
            const velocity = player.getVelocity();
            const isMoving = Math.abs(velocity.x) > 0.1 || Math.abs(velocity.z) > 0.1;

            if (isMoving && currentTime % 10 === 0) {
                if (!this.consumeEnergy(player, 'boots', this.config.phaseWalkEnergyPerMove)) {
                    // No energy = no phase
                    if (state) state.isPhasingActive = false;
                } else {
                    if (state) state.isPhasingActive = true;
                }
            }
        }

        // LEGGINGS - Hold sneak for 3 seconds for Reality Control
        if (armor.leggings && state) {
            const isSneaking = player.isSneaking;
            const velocity = player.getVelocity();
            const isMoving = Math.abs(velocity.x) > 0.01 || Math.abs(velocity.z) > 0.01;

            if (isSneaking && !isMoving) {
                if (!state.isHoldingSneak) {
                    // Start holding sneak
                    state.isHoldingSneak = true;
                    state.realityHoldStart = currentTime;
                } else {
                    // Check if held for 3 seconds
                    const holdDuration = currentTime - state.realityHoldStart;

                    if (holdDuration >= this.config.realityHoldTime && state.realityReady) {
                        // Activate reality control after 3 seconds of holding
                        if (currentTime - state.realityActivationTime > 20) {
                            this.activateRealityControl(player);
                            state.realityActivationTime = currentTime;
                            state.realityReady = false;
                        }
                    } else if (holdDuration >= 20 && holdDuration < this.config.realityHoldTime) {
                        // Show charging indicator after 1 second
                        if (currentTime % 10 === 0) {
                            const remaining = Math.ceil((this.config.realityHoldTime - holdDuration) / 20);
                            this.showMessage(player, `§5◎ Hold sneak: ${remaining}s for Reality Control`);
                        }
                    }
                }
            } else {
                // Released sneak or started moving
                if (state.isHoldingSneak) {
                    state.isHoldingSneak = false;
                    state.realityReady = true;
                }
            }
        }

        // CHESTPLATE - Sneak + Jump for Time Manipulation
        if (armor.chestplate && player.isSneaking && player.isJumping) {
            const lastTimeActivation = player.getDynamicProperty('carmot:lastTimeActivation') || 0;

            if (currentTime - lastTimeActivation > 20) {
                this.activateTimeManipulation(player);
                player.setDynamicProperty('carmot:lastTimeActivation', currentTime);
            }
        }

        // HELMET - Double sneak to activate ray
        if (armor.helmet) {
            if (player.isSneaking) {
                const lastSneak = player.getDynamicProperty('carmot:lastSneak') || 0;
                const sneakCount = player.getDynamicProperty('carmot:sneakCount') || 0;

                if (currentTime - lastSneak > 15) {
                    // First sneak
                    player.setDynamicProperty('carmot:sneakCount', 1);
                    player.setDynamicProperty('carmot:lastSneak', currentTime);
                } else if (sneakCount === 1) {
                    // Second sneak - activate
                    this.activateAttractionRay(player);
                    player.setDynamicProperty('carmot:sneakCount', 0);
                }
            }
        }

        // CROWN - ONLY WITH FULL ARMOR - Hold Jump while Sprinting
        if (armor.crown && armor.boots && armor.leggings && armor.chestplate && armor.helmet) {
            if (player.isSprinting && player.isJumping) {
                const jumpHoldStart = player.getDynamicProperty('carmot:jumpHoldStart') || 0;

                if (jumpHoldStart === 0) {
                    player.setDynamicProperty('carmot:jumpHoldStart', currentTime);
                } else if (currentTime - jumpHoldStart > 40) { // 2 seconds hold
                    this.activateUltimateSlash(player);
                    player.setDynamicProperty('carmot:jumpHoldStart', 0);
                }
            } else {
                player.setDynamicProperty('carmot:jumpHoldStart', 0);
            }
        }
    },

    // Visual Effects with custom particles
    createPhaseAura(player) {
        try {
            const loc = player.location;
            const dim = player.dimension;

            for (let i = 0; i < 6; i++) {
                const angle = (i / 6) * Math.PI * 2;
                dim.spawnParticle('myw:carmot_particle', {
                    x: loc.x + Math.cos(angle) * 1,
                    y: loc.y + 0.5,
                    z: loc.z + Math.sin(angle) * 1
                });
            }
        } catch { }
    },

    createPhaseEffect(player, blockPos) {
        try {
            const dim = player.dimension;

            for (let i = 0; i < 8; i++) {
                dim.spawnParticle('myw:carmot_particle_serpentine', {
                    x: blockPos.x + 0.5 + (Math.random() - 0.5),
                    y: blockPos.y + 0.5 + (Math.random() - 0.5),
                    z: blockPos.z + 0.5 + (Math.random() - 0.5)
                });
            }
        } catch { }
    },

    createVerticalPhaseTrail(player) {
        try {
            const loc = player.location;
            const dim = player.dimension;

            for (let i = 0; i < 10; i++) {
                dim.spawnParticle('myw:carmot_particle_gravity', {
                    x: loc.x,
                    y: loc.y - i * 0.5,
                    z: loc.z
                });
            }
        } catch { }
    },

    createVoidPlatform(player) {
        try {
            const loc = player.location;
            const dim = player.dimension;

            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                dim.spawnParticle('myw:carmot_particle', {
                    x: loc.x + Math.cos(angle) * 1.5,
                    y: loc.y - 0.5,
                    z: loc.z + Math.sin(angle) * 1.5
                });
            }
        } catch { }
    },

    createRealityDistortion(player) {
        try {
            const loc = player.location;
            const dim = player.dimension;
            const time = world.getAbsoluteTime();

            // Warping reality rings
            for (let ring = 1; ring <= 3; ring++) {
                const radius = ring * 5;
                const particles = ring * 8;

                for (let i = 0; i < particles; i++) {
                    const angle = (i / particles) * Math.PI * 2 + (time * 0.01 * ring);

                    dim.spawnParticle('myw:carmot_particle_gravity', {
                        x: loc.x + Math.cos(angle) * radius,
                        y: loc.y + ring,
                        z: loc.z + Math.sin(angle) * radius
                    });
                }
            }
        } catch { }
    },

    createTimeStopField(player) {
        try {
            const loc = player.location;
            const dim = player.dimension;

            // Time stop dome
            for (let i = 0; i < 30; i++) {
                const theta = Math.random() * Math.PI;
                const phi = Math.random() * Math.PI * 2;
                const radius = this.config.timeStopRadius;

                dim.spawnParticle('myw:carmot_particle_serpentine', {
                    x: loc.x + Math.sin(theta) * Math.cos(phi) * radius,
                    y: loc.y + Math.cos(theta) * radius + 5,
                    z: loc.z + Math.sin(theta) * Math.sin(phi) * radius
                });
            }
        } catch { }
    },

    createTimeFreezeEffect(entity) {
        try {
            const loc = entity.location;
            const dim = entity.dimension;

            // Frozen in time crystals
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                dim.spawnParticle('myw:carmot_particle', {
                    x: loc.x + Math.cos(angle) * 0.8,
                    y: loc.y + 1,
                    z: loc.z + Math.sin(angle) * 0.8
                });
            }
        } catch { }
    },

    createRewindEffect(player, currentPos, pastPos) {
        try {
            const dim = player.dimension;

            // Time trail
            const steps = 30;
            for (let i = 0; i <= steps; i++) {
                const t = i / steps;
                const pos = {
                    x: currentPos.x + (pastPos.x - currentPos.x) * t,
                    y: currentPos.y + (pastPos.y - currentPos.y) * t + 1,
                    z: currentPos.z + (pastPos.z - currentPos.z) * t
                };

                system.runTimeout(() => {
                    dim.spawnParticle('myw:carmot_particle_serpentine', pos);

                    if (i % 3 === 0) {
                        dim.spawnParticle('myw:carmot_particle_gravity', {
                            x: pos.x + (Math.random() - 0.5),
                            y: pos.y,
                            z: pos.z + (Math.random() - 0.5)
                        });
                    }
                }, i);
            }
        } catch { }
    },

    createElectricExplosion(location, dimension) {
        try {
            // Electric burst
            for (let i = 0; i < 20; i++) {
                const angle = (i / 20) * Math.PI * 2;
                const radius = 3;

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

            dimension.spawnParticle('minecraft:dragon_breath_fire', location);
        } catch { }
    },

    createDimensionalCollapse(location, dimension) {
        try {
            // Collapsing space
            for (let i = 0; i < 15; i++) {
                system.runTimeout(() => {
                    const radius = (15 - i) / 3;
                    for (let j = 0; j < 8; j++) {
                        const angle = (j / 8) * Math.PI * 2;

                        dimension.spawnParticle('myw:carmot_particle_gravity', {
                            x: location.x + Math.cos(angle) * radius,
                            y: location.y + 1,
                            z: location.z + Math.sin(angle) * radius
                        });
                    }
                }, i);
            }
        } catch { }
    },

    createCrownAura(player) {
        try {
            const loc = player.location;
            const dim = player.dimension;

            // Royal dimensional aura
            for (let ring = 1; ring <= 2; ring++) {
                const radius = this.config.crownAuraRadius * (ring / 2);
                const particles = 16;

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

                    dim.spawnParticle('myw:carmot_particle_gravity', {
                        x: loc.x + Math.cos(angle) * radius,
                        y: loc.y + 0.1,
                        z: loc.z + Math.sin(angle) * radius
                    });
                }
            }

            // Ascending particles
            for (let i = 0; i < 6; i++) {
                dim.spawnParticle('myw:carmot_particle', {
                    x: loc.x + (Math.random() - 0.5) * 3,
                    y: loc.y + Math.random() * 4,
                    z: loc.z + (Math.random() - 0.5) * 3
                });
            }
        } catch { }
    },

    // Energy Management - FIXED to ensure proper consumption
    consumeEnergy(player, piece, amount) {
        const playerId = player.id;
        const energy = this.energySystem.get(playerId);

        if (!energy || energy[piece] < amount) {
            return false;
        }

        energy[piece] = Math.max(0, energy[piece] - amount);
        return true;
    },

    regenerateEnergy(player) {
        const playerId = player.id;
        const energy = this.energySystem.get(playerId);
        const armor = this.checkEquippedArmor(player);

        if (!energy) return;

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

        // MUCH SLOWER regen rates to match consumption
        let regenRate = 1; // Base regen reduced from 4 to 1

        if (isMoving) {
            regenRate = 1.5; // Moving regen reduced from 5 to 1.5
        }

        // Check if player is meditating (sneaking without moving)
        if (player.isSneaking && !isMoving) {
            const state = this.playerStates.get(playerId);
            if (state && !state.isHoldingSneak) { // Not charging abilities
                regenRate = 3; // Meditation regen
            }
        }

        if (armor.crown) {
            regenRate = Math.max(regenRate, 2); // Crown regen reduced from 8 to 2
        }

        const pieces = ['boots', 'leggings', 'chestplate', 'helmet', 'crown'];
        pieces.forEach(piece => {
            if (armor[piece]) {
                const current = energy[piece];
                const max = this.config.maxEnergy[piece];
                if (current < max) {
                    energy[piece] = Math.min(current + regenRate, max);
                }
            }
        });
    },

    // Timeline tracking for time rewind
    recordTimeline(player) {
        const playerId = player.id;
        let timeline = this.timelineHistory.get(playerId);

        if (!timeline) {
            timeline = [];
            this.timelineHistory.set(playerId, timeline);
        }

        const health = player.getComponent('minecraft:health');
        timeline.push({
            position: { ...player.location },
            health: health?.currentValue || 20,
            time: world.getAbsoluteTime()
        });

        // Keep only last 5 seconds
        if (timeline.length > 100) {
            timeline.shift();
        }
    },

    // Display
    updateDisplay(player) {
        const playerId = player.id;
        const energy = this.energySystem.get(playerId);
        const armor = this.checkEquippedArmor(player);
        const state = this.playerStates.get(playerId);

        if (!energy) return;

        let totalEnergy = 0;
        let totalMax = 0;

        const pieces = ['boots', 'leggings', 'chestplate', 'helmet', 'crown'];
        pieces.forEach(piece => {
            if (armor[piece]) {
                totalEnergy += energy[piece];
                totalMax += this.config.maxEnergy[piece];
            }
        });

        if (totalMax === 0) return;

        const percentage = (totalEnergy / totalMax) * 100;
        const barLength = 20;
        const filled = Math.round((percentage / 100) * barLength);

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

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

        // Status indicators
        let status = '';

        if (armor.boots) status += ' §d◈PHASE';
        if (state?.hasGravityField) status += ' §5◎REALITY';
        if (state?.isTimeStopped) status += ' §b⧗TIME';
        if (state?.isChannelingRay) status += ' §e⚡RAY';

        // Ultimate cooldown
        if (armor.crown && state) {
            const cooldown = 200 - (world.getAbsoluteTime() - (state.lastUltimateTime || 0));
            if (cooldown > 0) {
                status += ` §c◆CD:${Math.ceil(cooldown / 20)}`;
            } else {
                status += ' §6◆READY';
            }
        }

        const display = `§d◆CARMOT◆ ${bar} §d${Math.round(totalEnergy)}/${totalMax}${status}`;
        this.showMessage(player, display);
    },

    // Utility functions
    getDistance(pos1, pos2) {
        const dx = pos1.x - pos2.x;
        const dy = pos1.y - pos2.y;
        const dz = pos1.z - pos2.z;
        return Math.sqrt(dx * dx + dy * dy + dz * dz);
    },

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

    showNotification(player, message, type = 'normal') {
        const colors = {
            normal: '§a',
            legendary: '§6',
            time: '§b',
            electric: '§e',
            ultimate: '§5'
        };

        const color = colors[type] || colors.normal;

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

    showActivation(player) {
        try {
            const loc = player.location;
            const dim = player.dimension;

            // Carmot activation burst
            for (let i = 0; i < 16; i++) {
                const angle = (i / 16) * Math.PI * 2;
                dim.spawnParticle('myw:carmot_particle_gravity', {
                    x: loc.x + Math.cos(angle) * 2.5,
                    y: loc.y + 1,
                    z: loc.z + Math.sin(angle) * 2.5
                });
            }

            this.playSound(player, 'random.levelup');
        } catch { }
    },

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

    checkEquippedArmor(player) {
        try {
            const equipment = player.getComponent('minecraft:equippable');
            if (!equipment) return {};

            return {
                boots: equipment.getEquipment(EquipmentSlot.Feet)?.typeId === 'myw:carmot_boots',
                leggings: equipment.getEquipment(EquipmentSlot.Legs)?.typeId === 'myw:carmot_leggins', // FIXED: changed to leggins
                chestplate: equipment.getEquipment(EquipmentSlot.Chest)?.typeId === 'myw:carmot_chestplate',
                helmet: equipment.getEquipment(EquipmentSlot.Head)?.typeId === 'myw:carmot_helmet',
                crown: equipment.getEquipment(EquipmentSlot.Head)?.typeId === 'myw:carmot_crown'
            };
        } catch {
            return {};
        }
    },

    cleanupPlayer(playerId) {
        this.activePlayers.delete(playerId);
        this.energySystem.delete(playerId);
        this.playerStates.delete(playerId);
        this.timelineHistory.delete(playerId);

        // Clear active effects
        const gravityInterval = this.gravityFields.get(playerId);
        if (gravityInterval) {
            system.clearRun(gravityInterval);
            this.gravityFields.delete(playerId);
        }

        const rayInterval = this.attractionBeams.get(playerId);
        if (rayInterval) {
            system.clearRun(rayInterval);
            this.attractionBeams.delete(playerId);
        }
    }
};

// Component registration
export function registerCarmotBoots(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_boots', {});
}

export function registerCarmotLeggings(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_leggins', {}); // FIXED: changed to leggins
}

export function registerCarmotChestplate(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_chestplate', {});
}

export function registerCarmotHelmet(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_helmet', {});
}

export function registerCarmotCrown(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_crown', {});
}

// System initialization
export function initializeCarmotArmorSystems() {
    // Main update loop
    system.runInterval(() => {
        try {
            world.getAllPlayers().forEach(player => {
                const playerId = player.id;
                const armor = CarmotArmorSystem.checkEquippedArmor(player);

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

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

                    // Update systems
                    CarmotArmorSystem.regenerateEnergy(player);
                    CarmotArmorSystem.updatePlayerInput(player);

                    // Record timeline for time abilities
                    if (armor.chestplate) {
                        CarmotArmorSystem.recordTimeline(player);
                    }

                    // Crown aura
                    if (armor.crown) {
                        CarmotArmorSystem.applyCrownAura(player);
                    }

                    // Boots passive effects
                    if (armor.boots) {
                        // No fall damage
                        player.addEffect('resistance', 5, {
                            amplifier: 4,
                            showParticles: false
                        });

                        // Enhanced speed
                        player.addEffect('speed', 60, {
                            amplifier: 2,
                            showParticles: false
                        });
                    }

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

    // Display update loop
    system.runInterval(() => {
        try {
            world.getAllPlayers().forEach(player => {
                if (CarmotArmorSystem.activePlayers.has(player.id)) {
                    CarmotArmorSystem.updateDisplay(player);
                }
            });
        } catch { }
    }, 20);

    // Cleanup on player leave
    world.afterEvents.playerLeave.subscribe(eventData => {
        CarmotArmorSystem.cleanupPlayer(eventData.playerId);
    });

    // System initialization message
    world.sendMessage('§5╔════════════════════════════════╗');
    world.sendMessage('§5║   CARMOT ARMOR SYSTEM v2.2     ║');
    world.sendMessage('§5╠════════════════════════════════╣');
    world.sendMessage('§f║ CONTROLS:                      ║');
    world.sendMessage('§d║  Boots: Always Phase (costs energy)║');
    world.sendMessage('§5║  Legs: Hold Sneak 3s = Reality ║');
    world.sendMessage('§b║  Chest: Sneak+Jump = Time Stop ║');
    world.sendMessage('§e║  Helmet: 2x Sneak = Attract Ray║');
    world.sendMessage('§6║  Crown: Hold Jump+Sprint = ULTIMATE║');
    world.sendMessage('§c║  (REQUIRES FULL ARMOR SET!)    ║');
    world.sendMessage('§5╠════════════════════════════════╣');
    world.sendMessage('§f║ FEATURES:                      ║');
    world.sendMessage('§a║ • Phase through everything     ║');
    world.sendMessage('§a║ • Control gravity & reality    ║');
    world.sendMessage('§a║ • Stop and rewind time         ║');
    world.sendMessage('§a║ • 50-block attraction ray      ║');
    world.sendMessage('§a║ • APOCALYPTIC ULTIMATE SLASH   ║');
    world.sendMessage('§5╚════════════════════════════════╝');
}