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

export const CarmotUtils = {
    durability: function (player, itemStack, equipmentSlot) {
        try {
            let equipComponent = itemStack?.getComponent('minecraft:durability');
            if (!equipComponent) return;

            let currentDamage = equipComponent.damage;
            let maxDurability = equipComponent.maxDurability;
            const inventory = player.getComponent('minecraft:equippable');

            if (currentDamage < maxDurability - 1) {
                equipComponent.damage = currentDamage + 1;
                inventory.setEquipment(equipmentSlot, itemStack);
            } else {
                CarmotMagic.createGravitationalCollapse(player);
                inventory.setEquipment(equipmentSlot, undefined);
            }
        } catch (error) {
            // Silenciar errores de durabilidad
        }
    },

    isNear: function (entity1, entity2, maxDistance, maxHeightDiff = 10) {
        const distance = Math.sqrt(
            Math.pow(entity1.location.x - entity2.location.x, 2) +
            Math.pow(entity1.location.y - entity2.location.y, 2) +
            Math.pow(entity1.location.z - entity2.location.z, 2)
        );

        return distance <= maxDistance &&
            Math.abs(entity1.location.y - entity2.location.y) <= maxHeightDiff;
    },

    spawnCarmotParticle: function (dimension, x, y, z, particleType = 'standard') {
        const particles = {
            'standard': 'myw:carmot_particle',
            'gravity': 'myw:carmot_particle_gravity',
            'serpentine': 'myw:carmot_particle_serpentine'
        };

        const fallbacks = {
            'standard': 'minecraft:lava_particle',
            'gravity': 'minecraft:portal_particle',
            'serpentine': 'minecraft:crimson_spore_particle'
        };

        try {
            dimension.spawnParticle(particles[particleType] || particles.standard, { x, y, z });
        } catch (error) {
            dimension.spawnParticle(fallbacks[particleType] || fallbacks.standard, { x, y, z });
        }
    },

    applyGravitationalForce: function (entity, centerX, centerY, centerZ, strength) {
        const { x, y, z } = entity.location;
        const dx = centerX - x;
        const dy = centerY - y;
        const dz = centerZ - z;

        const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
        if (distance < 0.1) return;

        const forceX = (dx / distance) * strength;
        const forceY = (dy / distance) * strength;
        const forceZ = (dz / distance) * strength;

        try {
            entity.applyImpulse({ x: forceX, y: forceY, z: forceZ });
        } catch (error) {
            // Entidad podría no tener física
        }
    }
};

export const CarmotMagic = {
    onHitEffects: function (attacker, target) {
        const { x, y, z } = target.location;

        // Implosión y serpiente
        this.createGravitationalImplosion(attacker.dimension, x, y + 1, z);
        this.applyGravitySnakeEffect(target);

        try {
            // Daño aumentado
            target.applyDamage(10, { cause: EntityDamageCause.entityAttack });
            target.addEffect('slowness', 60, { amplifier: 3, showParticles: true });
            target.addEffect('wither', 40, { amplifier: 1, showParticles: true });
            target.addEffect('levitation', 20, { amplifier: 1, showParticles: true });
        } catch { }

        // Robo de vida mejorado
        try {
            const health = attacker.getComponent('health');
            if (health.current < health.value) {
                health.setCurrentValue(Math.min(health.value, health.current + 5));
            }
        } catch { }

        // Crítico aéreo = implosión extra
        if (!attacker.isOnGround) {
            this.createGravitationalImplosion(attacker.dimension, x, y + 1, z);
        }
    },

    activateSpecialAbility: function (player) {
        try {
            // Verificar cooldown
            const lastUsed = player.getDynamicProperty('myw:carmot_last_used') || 0;
            const currentTime = Date.now();
            const cooldownTime = 25000; // 25 segundos

            if (currentTime - lastUsed < cooldownTime) {
                const remaining = Math.ceil((cooldownTime - (currentTime - lastUsed)) / 1000);
                player.onScreenDisplay.setActionBar(`§4§l Gravitational Cooldown: §f${remaining}s §6`);
                return;
            }

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

            // Activar habilidad de campo gravitatorio
            this.createGravityField(player);
            player.onScreenDisplay.setActionBar('§4§l GRAVITY FIELD ACTIVATED ');
        } catch { }
    },

    createGravitationalImplosion: function (dimension, x, y, z) {
        for (let i = 0; i < 20; i++) {
            system.runTimeout(() => {
                const radius = 5 - (i * 0.25);
                for (let j = 0; j < 12; j++) {
                    const angle = (j / 12) * Math.PI * 2;
                    const particleX = x + Math.cos(angle) * radius;
                    const particleZ = z + Math.sin(angle) * radius;
                    CarmotUtils.spawnCarmotParticle(dimension, particleX, y, particleZ, 'gravity');
                }

                dimension.getEntities().forEach(entity => {
                    if (CarmotUtils.isNear({ location: { x, y, z } }, entity, 5)) {
                        CarmotUtils.applyGravitationalForce(entity, x, y, z, 0.4);
                    }
                });
            }, i * 2);
        }

        // Explosión final
        system.runTimeout(() => {
            for (let i = 0; i < 30; i++) {
                const angle = Math.random() * Math.PI * 2;
                const strength = 0.8 + Math.random() * 0.7;
                const particleX = x + Math.cos(angle) * strength;
                const particleZ = z + Math.sin(angle) * strength;
                const particleY = y + (Math.random() - 0.5) * 2;
                CarmotUtils.spawnCarmotParticle(dimension, particleX, particleY, particleZ, 'standard');
            }
        }, 40);
    },

    applyGravitySnakeEffect: function (target) {
        let snakeTime = 0;
        const snakeInterval = system.runInterval(() => {
            snakeTime++;

            try {
                const { x, y, z } = target.location;
                const radius = 1.5;
                const segments = 8;

                for (let i = 0; i < segments; i++) {
                    const angle = (i / segments) * Math.PI * 2 + snakeTime * 0.2;
                    const offsetX = Math.cos(angle) * radius;
                    const offsetZ = Math.sin(angle) * radius;
                    const segmentY = y + 0.5 + Math.sin(snakeTime * 0.1 + i * 0.3) * 0.5;
                    CarmotUtils.spawnCarmotParticle(target.dimension, x + offsetX, segmentY, z + offsetZ, 'serpentine');
                }

                if (snakeTime % 20 === 0) {
                    try {
                        target.applyImpulse({ x: 0, y: 0.5, z: 0 });
                    } catch { }
                }

                if (snakeTime >= 60) {
                    system.clearRun(snakeInterval);
                }
            } catch {
                system.clearRun(snakeInterval);
            }
        }, 3);
    },

    createGravityField: function (player) {
        const { x, y, z } = player.location;
        const dimension = player.dimension;
        let fieldTime = 0;

        const fieldInterval = system.runInterval(() => {
            fieldTime++;

            // Anillos concéntricos más potentes
            for (let ring = 1; ring <= 4; ring++) {
                const radius = ring * 2.2;
                const particles = ring * 12;

                for (let i = 0; i < particles; i++) {
                    const angle = (i / particles) * Math.PI * 2 + fieldTime * 0.15;
                    const ringX = x + Math.cos(angle) * radius;
                    const ringZ = z + Math.sin(angle) * radius;
                    const ringY = y + 1 + Math.sin(fieldTime * 0.3 + angle) * 0.7;
                    CarmotUtils.spawnCarmotParticle(dimension, ringX, ringY, ringZ, 'gravity');
                }
            }

            // Efectos a entidades
            dimension.getEntities().forEach(entity => {
                if (entity.id !== player.id && CarmotUtils.isNear(player, entity, 10)) {
                    CarmotUtils.applyGravitationalForce(entity, x, y, z, 0.5);

                    if (fieldTime % 20 === 0) {
                        try {
                            entity.applyDamage(3, { cause: EntityDamageCause.magic });
                            entity.addEffect('blindness', 40, { amplifier: 1, showParticles: true });
                        } catch { }
                    }
                }
            });

            if (fieldTime >= 100) {
                system.clearRun(fieldInterval);
                this.collapseGravityField(dimension, x, y, z);
            }
        }, 2);
    },

    collapseGravityField: function (dimension, x, y, z) {
        for (let collapse = 0; collapse < 15; collapse++) {
            system.runTimeout(() => {
                const radius = 8 - (collapse * 0.5);
                for (let i = 0; i < 20; i++) {
                    const angle = (i / 20) * Math.PI * 2;
                    const collapseX = x + Math.cos(angle) * radius;
                    const collapseZ = z + Math.sin(angle) * radius;
                    const collapseY = y + 1 + (Math.random() - 0.5);
                    CarmotUtils.spawnCarmotParticle(dimension, collapseX, collapseY, collapseZ, 'gravity');
                }

                dimension.getEntities().forEach(entity => {
                    if (CarmotUtils.isNear({ location: { x, y, z } }, entity, 10)) {
                        CarmotUtils.applyGravitationalForce(entity, x, y, z, 0.8);
                    }
                });
            }, collapse * 3);
        }

        // Explosión final
        system.runTimeout(() => {
            for (let i = 0; i < 50; i++) {
                const angle = Math.random() * Math.PI * 2;
                const strength = 1 + Math.random() * 2;
                const explosionX = x + Math.cos(angle) * strength;
                const explosionZ = z + Math.sin(angle) * strength;
                const explosionY = y + 1 + (Math.random() - 0.5) * 2;
                CarmotUtils.spawnCarmotParticle(dimension, explosionX, explosionY, explosionZ, 'standard');
            }
        }, 50);
    },

    createGravitationalCollapse: function (player) {
        const { x, y, z } = player.location;
        const dimension = player.dimension;

        for (let i = 0; i < 100; i++) {
            system.runTimeout(() => {
                const angle = Math.random() * Math.PI * 2;
                const distance = 5 + Math.random() * 5;
                const particleX = x + Math.cos(angle) * distance;
                const particleZ = z + Math.sin(angle) * distance;
                const particleY = y + Math.random() * 3;
                CarmotUtils.spawnCarmotParticle(dimension, particleX, particleY, particleZ, 'gravity');
            }, i * 2);
        }

        system.runTimeout(() => {
            dimension.getEntities().forEach(entity => {
                if (CarmotUtils.isNear(player, entity, 10)) {
                    CarmotUtils.applyGravitationalForce(entity, x, y, z, 1.2);
                    try {
                        entity.applyDamage(12, { cause: EntityDamageCause.magic });
                    } catch { }
                }
            });
        }, 30);

        player.onScreenDisplay.setActionBar('§4§l GRAVITATIONAL COLLAPSE - CARMOT SWORD SHATTERED ');
    }
};

export function registerCarmotSword(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_sword', {
        onHitEntity(eventData) {
            const { attackingEntity, hitEntity, itemStack } = eventData;
            if (attackingEntity.getGameMode() === GameMode.survival) {
                CarmotUtils.durability(attackingEntity, itemStack, EquipmentSlot.Mainhand);
            }
            CarmotMagic.onHitEffects(attackingEntity, hitEntity);
        },

        onUse({ itemStack, source }) {
            if (source.getGameMode() === GameMode.survival) {
                CarmotUtils.durability(source, itemStack, EquipmentSlot.Mainhand);
            }
            CarmotMagic.activateSpecialAbility(source);
        }
    });
}

export function initializeCarmotPassiveEffects() {
    system.runInterval(() => {
        try {
            world.getAllPlayers().forEach(player => {
                const mainhand = player.getComponent('minecraft:equippable')?.getEquipment(EquipmentSlot.Mainhand);

                if (mainhand?.typeId === 'myw:carmot_sword') {
                    const { x, y, z } = player.location;

                    if (Math.random() < 0.5) {
                        const orbitRadius = 1.5;
                        const orbitAngle = Date.now() / 1000;
                        const orbitX = x + Math.cos(orbitAngle) * orbitRadius;
                        const orbitZ = z + Math.sin(orbitAngle) * orbitRadius;
                        CarmotUtils.spawnCarmotParticle(player.dimension, orbitX, y + 1, orbitZ, 'gravity');
                    }

                    if (Math.random() < 0.1) {
                        const serpentX = x + (Math.random() - 0.5) * 3;
                        const serpentZ = z + (Math.random() - 0.5) * 3;
                        const serpentY = y + Math.random() * 2;
                        CarmotUtils.spawnCarmotParticle(player.dimension, serpentX, serpentY, serpentZ, 'serpentine');
                    }
                }
            });
        } catch { }
    }, 10);
}
