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

export const CarmotDustSystem = {

    config: {
        useCooldown: 80, // ticks (4 seconds) - longer cooldown for dimensional powers
        baseDashPower: 5.5, // Stronger forward momentum
        verticalLift: 0.8, // Increased upward boost
        phaseRadius: 6.0, // Area for phasing through entities
        temporalDamage: 8, // Higher base damage due to temporal disruption
        dimensionalRadius: 7, // Area for dimensional effects
        carmotBoostMultiplier: 1.8, // Bonus with carmot armor
        particleCount: 40, // Moderate particle count
        trailDuration: 120, // Longer dimensional trail
        landingEffectRadius: 6,
        phaseDuration: 60, // 3 seconds of brief intangibility to projectiles
        temporalShieldDuration: 100, // 5 seconds of temporal shielding
        dashDistance: 15, // Maximum dash distance
        dimensionalRiftRadius: 8 // Area of dimensional instability
    },

    handleDustUse(player, itemStack) {
        try {
            // Check cooldown
            const lastUse = player.getDynamicProperty('myw:last_carmot_dust_use') || 0;
            const currentTime = Date.now();

            if (currentTime - lastUse < this.config.useCooldown * 50) {
                return false; // Silent cooldown
            }

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

            // Check carmot armor for bonuses
            const carmotPower = this.getCarmotArmorCount(player);
            const hasFullSet = carmotPower >= 4;

            // Apply dimensional dash effect
            this.applyDimensionalDash(player, carmotPower, hasFullSet);

            // Create visual and dimensional effects
            this.createDashEffects(player, hasFullSet);

            // Create dimensional rift effect
            this.createDimensionalRift(player, carmotPower, hasFullSet);

            // Handle temporal effects on nearby entities
            this.handleTemporalEffects(player, carmotPower, hasFullSet);

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

            // Apply temporal phase protection
            this.applyTemporalPhase(player, carmotPower);

            return true;

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

    applyDimensionalDash(player, carmotPower, hasFullSet) {
        try {
            // Calculate dash power based on carmot armor
            const basePower = this.config.baseDashPower;
            const armorBonus = carmotPower * 0.3; // Each armor piece adds 30% more power
            const totalDashPower = basePower + armorBonus;

            // Get player's view direction for forward dash
            const viewDirection = player.getViewDirection();

            // Calculate dash velocities (primarily horizontal)
            const dashPower = totalDashPower * (hasFullSet ? this.config.carmotBoostMultiplier : 1.0);
            const verticalComponent = this.config.verticalLift * (hasFullSet ? 1.3 : 1.0);

            // Apply dimensional dash (forward-focused)
            const finalVelocity = {
                x: viewDirection.x * dashPower,
                y: verticalComponent, // Minimal upward movement
                z: viewDirection.z * dashPower
            };

            // Apply the dash
            player.applyKnockback(
                finalVelocity.x,
                finalVelocity.z,
                Math.abs(finalVelocity.x) + Math.abs(finalVelocity.z),
                finalVelocity.y
            );

            // Add temporal effects
            if (hasFullSet) {
                player.addEffect('speed', 200, {
                    amplifier: 3, // Speed IV for dimensional traversal
                    showParticles: false
                });
                player.addEffect('invisibility', 40, {
                    amplifier: 0, // Brief phase invisibility
                    showParticles: false
                });
                player.addEffect('fire_resistance', 160, {
                    amplifier: 0, // Dimensional protection
                    showParticles: false
                });
            } else if (carmotPower >= 2) {
                player.addEffect('speed', 120, {
                    amplifier: 2, // Speed III
                    showParticles: false
                });
                player.addEffect('night_vision', 200, {
                    amplifier: 0, // Enhanced perception
                    showParticles: false
                });
            }

            // Create dimensional particle trail
            this.createDimensionalTrail(player, hasFullSet);

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

    createDimensionalTrail(player, hasFullSet) {
        try {
            let trailTicks = 0;
            const maxTrailTicks = this.config.trailDuration;

            const trailInterval = system.runInterval(() => {
                try {
                    if (trailTicks >= maxTrailTicks || !player.isValid()) {
                        system.clearRun(trailInterval);
                        return;
                    }

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

                    // Create dimensional trailing particles
                    const particleCount = hasFullSet ? 10 : 6;
                    for (let i = 0; i < particleCount; i++) {
                        const offset = {
                            x: (Math.random() - 0.5) * 3.0, // Wider spread for dimensional effect
                            y: (Math.random() - 0.5) * 2.0,
                            z: (Math.random() - 0.5) * 3.0
                        };

                        const particleLocation = {
                            x: playerLocation.x + offset.x,
                            y: playerLocation.y + offset.y + 1,
                            z: playerLocation.z + offset.z
                        };

                        const particleType = hasFullSet ?
                            (Math.random() > 0.5 ? 'myw:carmot_particle_serpentine' : 'myw:carmot_particle_gravity') :
                            (Math.random() > 0.7 ? 'myw:carmot_particle' : 'myw:carmot_particle_gravity');

                        dimension.spawnParticle(particleType, particleLocation);
                    }

                    // Create gravitational distortion effects
                    if (trailTicks % 8 === 0) {
                        this.createGravityDistortion(dimension, playerLocation, hasFullSet);
                    }

                    // Create dimensional rifts
                    if (hasFullSet && trailTicks % 20 === 0) {
                        this.createMiniRifts(dimension, playerLocation);
                    }

                    trailTicks++;

                } catch (error) {
                    system.clearRun(trailInterval);
                }
            }, 2); // Every 2 ticks

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

    createGravityDistortion(dimension, location, hasFullSet) {
        try {
            const distortionParticles = hasFullSet ? 12 : 8;

            for (let i = 0; i < distortionParticles; i++) {
                const angle = (i / distortionParticles) * Math.PI * 2;
                const radius = 1.5 + Math.random() * 2.0;

                const distortionLocation = {
                    x: location.x + Math.cos(angle) * radius,
                    y: location.y + (Math.random() - 0.5) * 2.0,
                    z: location.z + Math.sin(angle) * radius
                };

                system.runTimeout(() => {
                    try {
                        const particleType = hasFullSet ? 'myw:carmot_particle_gravity' : 'myw:carmot_particle';
                        dimension.spawnParticle(particleType, distortionLocation);
                    } catch (error) {
                        // Error with distortion particles
                    }
                }, Math.random() * 15);
            }
        } catch (error) {
            // Error creating distortion
        }
    },

    createMiniRifts(dimension, location) {
        try {
            // Create small dimensional rifts
            for (let rift = 0; rift < 3; rift++) {
                for (let i = 0; i < 4; i++) {
                    const angle = (i / 4) * Math.PI * 2 + (rift * Math.PI * 0.5);
                    const radius = 1.0 + (rift * 0.5);
                    const height = (Math.random() - 0.5) * 1.5;

                    const riftLocation = {
                        x: location.x + Math.cos(angle) * radius,
                        y: location.y + height,
                        z: location.z + Math.sin(angle) * radius
                    };

                    system.runTimeout(() => {
                        try {
                            dimension.spawnParticle('myw:carmot_particle_serpentine', riftLocation);
                        } catch (error) {
                            // Error with rift particles
                        }
                    }, i * 4 + rift * 10);
                }
            }
        } catch (error) {
            // Error creating rifts
        }
    },

    createDimensionalRift(player, carmotPower, hasFullSet) {
        try {
            const location = player.location;
            const dimension = player.dimension;

            // Create expanding dimensional rift
            for (let ring = 1; ring <= 4; ring++) {
                const ringRadius = ring * 1.8;
                const particlesInRing = ring * 10;
                const delay = ring * 8;

                system.runTimeout(() => {
                    try {
                        for (let i = 0; i < particlesInRing; i++) {
                            const angle = (i / particlesInRing) * Math.PI * 2;
                            const ringLocation = {
                                x: location.x + Math.cos(angle) * ringRadius,
                                y: location.y + (Math.random() - 0.5) * 1.0,
                                z: location.z + Math.sin(angle) * ringRadius
                            };

                            const particleType = hasFullSet ? 'myw:carmot_particle_serpentine' : 'myw:carmot_particle_gravity';
                            dimension.spawnParticle(particleType, ringLocation);
                        }

                        // Create dimensional distortion bursts
                        for (let j = 0; j < 6; j++) {
                            const burstAngle = (j / 6) * Math.PI * 2;
                            const burstLocation = {
                                x: location.x + Math.cos(burstAngle) * ringRadius * 0.7,
                                y: location.y + (Math.random() - 0.5) * 2.0,
                                z: location.z + Math.sin(burstAngle) * ringRadius * 0.7
                            };
                            dimension.spawnParticle('myw:carmot_particle', burstLocation);
                        }

                    } catch (error) {
                        // Error with rift particles
                    }
                }, delay);
            }

            // Sound effect for dimensional rift
            try {
                dimension.playSound('block.portal.ambient', location, {
                    volume: hasFullSet ? 1.2 : 0.8,
                    pitch: hasFullSet ? 0.8 : 1.0
                });
            } catch (error) {
                // No sound available
            }

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

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

            // Dimensional launch effect
            const burstParticles = hasFullSet ? this.config.particleCount * 1.3 : this.config.particleCount;

            for (let i = 0; i < burstParticles; i++) {
                const angle = (i / burstParticles) * Math.PI * 2;
                const elevation = (Math.random() - 0.5) * Math.PI * 0.3; // More horizontal spread
                const distance = Math.random() * 3.0;

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

                const delay = Math.random() * 10;
                system.runTimeout(() => {
                    try {
                        const particleType = hasFullSet ?
                            'myw:carmot_particle_serpentine' :
                            'myw:carmot_particle_gravity';
                        dimension.spawnParticle(particleType, particleLocation);
                    } catch (error) {
                        // Error with particles
                    }
                }, delay);
            }

            // Create dimensional anchor effect
            this.createDimensionalAnchor(dimension, location, hasFullSet);

            // Sound effect
            try {
                dimension.playSound('block.portal.travel', location, {
                    volume: hasFullSet ? 1.0 : 0.7,
                    pitch: hasFullSet ? 1.3 : 1.1
                });
            } catch (error) {
                // No sound available
            }

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

    createDimensionalAnchor(dimension, location, hasFullSet) {
        try {
            // Create dimensional anchor effect at origin point
            const anchorY = Math.floor(location.y);

            for (let ring = 1; ring <= 3; ring++) {
                const radius = ring * 1.2;
                const particlesInRing = ring * 6;

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

                    system.runTimeout(() => {
                        try {
                            dimension.spawnParticle('myw:carmot_particle', anchorLocation);
                        } catch (error) {
                            // Error with anchor particles
                        }
                    }, ring * 8);
                }
            }

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

    handleTemporalEffects(player, carmotPower, hasFullSet) {
        try {
            const location = player.location;
            const dimension = player.dimension;
            const temporalRadius = this.config.dimensionalRadius;

            // Find nearby entities for temporal effects
            const nearbyEntities = dimension.getEntities({
                location: location,
                maxDistance: temporalRadius,
                excludeTypes: ['minecraft:item']
            });

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

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

                // Apply temporal disruption to hostile entities
                if (distance <= temporalRadius) {
                    if (this.isHostileEntity(entity)) {
                        const falloff = Math.max(0.3, 1 - (distance / temporalRadius));
                        const baseDamage = this.config.temporalDamage;
                        const bonusDamage = carmotPower * 0.4;
                        const finalDamage = (baseDamage + bonusDamage) * falloff;

                        try {
                            entity.applyDamage(finalDamage, { cause: EntityDamageCause.magic });

                            // Apply temporal slow instead of knockback
                            entity.addEffect('slowness', 80, {
                                amplifier: hasFullSet ? 2 : 1,
                                showParticles: false
                            });

                            // Chance to confuse enemies with full set
                            if (hasFullSet && Math.random() < 0.3) {
                                entity.addEffect('nausea', 60, {
                                    amplifier: 0,
                                    showParticles: false
                                });
                            }

                            // Create temporal disruption effect
                            this.createTemporalEffect(dimension, entity.location);

                        } catch (entityError) {
                            // Error affecting entity
                        }
                    }
                }

                // Enhance allied players with carmot resonance
                if (distance <= temporalRadius && entity.typeId === 'minecraft:player') {
                    const allyCarmotCount = this.getCarmotArmorCount(entity);
                    if (allyCarmotCount > 0) {
                        // Apply temporal acceleration
                        entity.addEffect('speed', 80, {
                            amplifier: allyCarmotCount >= 4 ? 2 : 1,
                            showParticles: false
                        });

                        // Enhanced perception for full set users
                        if (allyCarmotCount >= 4) {
                            entity.addEffect('night_vision', 200, {
                                amplifier: 0,
                                showParticles: false
                            });
                        }

                        // Resonance particles
                        this.createResonanceEffect(dimension, entity.location);
                    }
                }
            });

        } catch (error) {
            // Error handling temporal effects
        }
    },

    applyTemporalPhase(player, carmotPower) {
        try {
            // Apply brief intangibility and temporal shielding
            const phaseDuration = this.config.phaseDuration + (carmotPower * 15);
            const shieldDuration = this.config.temporalShieldDuration + (carmotPower * 25);

            // Resistance to projectiles and some damage
            player.addEffect('resistance', shieldDuration, {
                amplifier: carmotPower >= 4 ? 2 : 1,
                showParticles: false
            });

            // Enhanced movement during phase
            player.addEffect('jump_boost', phaseDuration, {
                amplifier: carmotPower >= 4 ? 3 : 2,
                showParticles: false
            });

            // Store temporal phase data
            player.setDynamicProperty('myw:temporal_phase', Date.now() + (phaseDuration * 50));
            player.setDynamicProperty('myw:dimensional_shield', Date.now() + (shieldDuration * 50));

        } catch (error) {
            // Error applying temporal phase
        }
    },

    // VISUAL EFFECTS
    createTemporalEffect(dimension, location) {
        try {
            // Create temporal disruption spirals
            for (let i = 0; i < 6; i++) {
                const angle = (i / 6) * Math.PI * 2;
                const radius = 1.0 + Math.random() * 0.5;
                const height = Math.random() * 1.5;

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

    createResonanceEffect(dimension, location) {
        try {
            // Create resonance waves
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                const radius = 1.2;
                const height = i * 0.2;

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

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

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

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

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

    isHostileEntity(entity) {
        const hostileTypes = [
            'zombie', 'skeleton', 'creeper', 'spider', 'enderman', 'witch',
            'slime', 'magma_cube', 'blaze', 'ghast', 'piglin', 'hoglin',
            'zoglin', 'vindicator', 'evoker', 'pillager', 'ravager'
        ];

        return hostileTypes.some(type => entity.typeId.includes(type)) ||
            entity.hasComponent('minecraft:angry');
    },

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

// Register carmot dust component
export function registerCarmotDust(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:carmot_dust', {
        onUse(eventData) {
            const { itemStack, source } = eventData;
            CarmotDustSystem.handleDustUse(source, itemStack);
        }
    });
}

// Initialize carmot dust systems
export function initializeCarmotDustSystems() {
    // Temporal damage reduction system
    world.afterEvents.entityHurt.subscribe(eventData => {
        const entity = eventData.hurtEntity;

        if (entity.typeId === 'minecraft:player') {
            try {
                const shieldTime = entity.getDynamicProperty('myw:dimensional_shield') || 0;
                const phaseTime = entity.getDynamicProperty('myw:temporal_phase') || 0;
                const currentTime = Date.now();

                if (currentTime < shieldTime) {
                    // Temporal shield active
                    if (eventData.cause === EntityDamageCause.projectile ||
                        eventData.cause === EntityDamageCause.magic) {

                        const originalDamage = eventData.damage;
                        const shieldReduction = 0.6; // 60% damage reduction
                        const reducedDamage = originalDamage * (1 - shieldReduction);
                        const healAmount = originalDamage - reducedDamage;

                        system.runTimeout(() => {
                            try {
                                entity.applyDamage(-healAmount);

                                // Create shield effect
                                const dimension = entity.dimension;
                                for (let i = 0; i < 5; i++) {
                                    system.runTimeout(() => {
                                        try {
                                            dimension.spawnParticle('myw:carmot_particle_serpentine', {
                                                x: entity.location.x + (Math.random() - 0.5) * 2.0,
                                                y: entity.location.y + Math.random() * 2.0,
                                                z: entity.location.z + (Math.random() - 0.5) * 2.0
                                            });
                                        } catch (error) {
                                            // Error with shield particles
                                        }
                                    }, i * 3);
                                }
                            } catch (error) {
                                // Error with shield effect
                            }
                        }, 1);
                    }
                }

                // Phase intangibility to some attacks
                if (currentTime < phaseTime) {
                    if (eventData.cause === EntityDamageCause.entityAttack && Math.random() < 0.3) {
                        // 30% chance to phase through melee attacks
                        const healAmount = eventData.damage;
                        system.runTimeout(() => {
                            try {
                                entity.applyDamage(-healAmount);

                                // Phase effect
                                entity.dimension.spawnParticle('myw:carmot_particle_gravity', {
                                    x: entity.location.x,
                                    y: entity.location.y + 1,
                                    z: entity.location.z
                                });
                            } catch (error) {
                                // Error with phase effect
                            }
                        }, 1);
                    }
                }

            } catch (error) {
                // Error checking temporal protection
            }
        }
    });

    world.sendMessage('[OK] Carmot Dust System initialized - Dimensional Control Version');
}