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

export const FairyConstellationSystem = {
    config: {
        // Sistema de constelaciones
        constellation: {
            minFairies: 3,
            maxDistance: 15,
            scanInterval: 20,
            formationDuration: 200, // 10 segundos
            blessingRadius: 20,
            particleIntensity: 3
        },
        
        // Rastro de bendiciones
        blessingTrail: {
            dropInterval: 10, // cada 0.5 segundos
            trailLifetime: 100, // 5 segundos
            healAmount: 1,
            buffDuration: 60
        },
        
        // Transformación mágica
        transformation: {
            cooldown: 400, // 20 segundos
            successChance: 0.3,
            radius: 5
        },
        
        // Tipos de constelaciones
        constellations: {
            triangle: {
                name: '§6✦ Trinity Constellation',
                fairies: 3,
                buffs: ['regeneration', 'speed'],
                particles: 'myw:mythril_particle',
                color: '§e'
            },
            square: {
                name: '§b✦ Harmony Constellation',
                fairies: 4,
                buffs: ['regeneration', 'resistance', 'speed'],
                particles: 'myw:mythril_particle_serpentine',
                color: '§b'
            },
            pentagon: {
                name: '§d✦ Divine Constellation',
                fairies: 5,
                buffs: ['regeneration', 'resistance', 'speed', 'jump_boost', 'night_vision'],
                particles: 'myw:mythril_flight_particle',
                color: '§d'
            }
        }
    },

    activeConstellations: new Map(),
    blessingTrails: new Set(),
    fairyStates: new Map(),

    initialize() {
        // Sistema principal de constelaciones
        system.runInterval(() => {
            this.scanForConstellations();
        }, this.config.constellation.scanInterval);

        // Sistema de rastros de bendición
        system.runInterval(() => {
            this.updateBlessingTrails();
        }, this.config.blessingTrail.dropInterval);

        // Sistema de transformaciones mágicas
        system.runInterval(() => {
            this.checkTransformations();
        }, 20);

        world.sendMessage('§d[FAIRY] §5Constellation & Blessing System initialized ✨');
    },

    // ==================== SISTEMA DE CONSTELACIONES ====================

    scanForConstellations() {
        try {
            const dimensions = [world.getDimension('overworld')];
            
            dimensions.forEach(dimension => {
                const fairies = dimension.getEntities({
                    type: 'myw:fairy'
                });

                if (fairies.length < 3) return;

                // Buscar grupos de hadas cercanas
                const fairyGroups = this.findNearbyFairyGroups(fairies);
                
                fairyGroups.forEach(group => {
                    if (group.length >= 3) {
                        this.formConstellation(group, dimension);
                    }
                });
            });
        } catch (error) {
            // Error scanning
        }
    },

    findNearbyFairyGroups(fairies) {
        const groups = [];
        const processed = new Set();

        fairies.forEach(fairy => {
            if (processed.has(fairy.id)) return;

            const group = [fairy];
            processed.add(fairy.id);

            fairies.forEach(otherFairy => {
                if (processed.has(otherFairy.id)) return;
                
                const distance = this.getDistance(fairy.location, otherFairy.location);
                if (distance <= this.config.constellation.maxDistance) {
                    group.push(otherFairy);
                    processed.add(otherFairy.id);
                }
            });

            if (group.length >= 3) {
                groups.push(group);
            }
        });

        return groups;
    },

    formConstellation(fairies, dimension) {
        try {
            const constellationId = `const_${Date.now()}_${Math.random()}`;
            
            // Determinar tipo de constelación
            let constellationType;
            if (fairies.length >= 5) {
                constellationType = this.config.constellations.pentagon;
            } else if (fairies.length >= 4) {
                constellationType = this.config.constellations.square;
            } else {
                constellationType = this.config.constellations.triangle;
            }

            const constellation = {
                id: constellationId,
                fairies: fairies.slice(0, constellationType.fairies),
                type: constellationType,
                startTime: system.currentTick,
                dimension: dimension,
                centerPoint: this.calculateCenter(fairies)
            };

            this.activeConstellations.set(constellationId, constellation);

            // Efectos visuales y sonoros
            this.createConstellationFormation(constellation);
            
            // Aplicar buffs en área
            this.applyConstellationBlessings(constellation);

            // Mensaje a jugadores cercanos
            this.notifyNearbyPlayers(constellation);

            // Limpiar constelación después de duración
            system.runTimeout(() => {
                this.dissolveConstellation(constellationId);
            }, this.config.constellation.formationDuration);

        } catch (error) {
            // Error forming constellation
        }
    },

    createConstellationFormation(constellation) {
        try {
            const { fairies, type, dimension, centerPoint } = constellation;
            
            // Animar formación con partículas (reducido 80%)
            for (let i = 0; i < 3; i++) {
                system.runTimeout(() => {
                    // Solo algunas veces mostrar rayos
                    if (i % 2 === 0) {
                        // Conectar hadas con rayos de luz
                        for (let j = 0; j < fairies.length; j++) {
                            if (!fairies[j].isValid()) continue;
                            
                            const nextIndex = (j + 1) % fairies.length;
                            if (!fairies[nextIndex].isValid()) continue;
                            
                            this.createLightBeam(
                                fairies[j].location,
                                fairies[nextIndex].location,
                                dimension,
                                type.particles
                            );
                        }
                    }

                    // Efecto central menos frecuente
                    if (i % 3 === 0) {
                        this.createCenterEffect(centerPoint, dimension, type);
                    }

                }, i * 20);
            }

            // Sonido mágico
            try {
                dimension.playSound('beacon.power', centerPoint, {
                    volume: 0.5,
                    pitch: 1.5
                });
            } catch (e) { }

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

    createLightBeam(start, end, dimension, particleType) {
        try {
            const steps = 3; // Reducido 80%
            for (let i = 0; i <= steps; i++) {
                const t = i / steps;
                const beamPoint = {
                    x: start.x + (end.x - start.x) * t,
                    y: start.y + (end.y - start.y) * t + Math.sin(t * Math.PI) * 0.5,
                    z: start.z + (end.z - start.z) * t
                };

                dimension.spawnParticle(particleType, beamPoint);
            }
        } catch (e) { }
    },

    createCenterEffect(center, dimension, type) {
        try {
            const particleCount = 2; // Reducido 80%
            for (let i = 0; i < particleCount; i++) {
                const angle = (i / particleCount) * Math.PI * 2;
                const radius = 0.8;
                
                dimension.spawnParticle(type.particles, {
                    x: center.x + Math.cos(angle) * radius,
                    y: center.y + 1,
                    z: center.z + Math.sin(angle) * radius
                });
            }
        } catch (e) { }
    },

    applyConstellationBlessings(constellation) {
        try {
            const { centerPoint, type, dimension } = constellation;
            const radius = this.config.constellation.blessingRadius;

            const nearbyPlayers = dimension.getPlayers({
                location: centerPoint,
                maxDistance: radius
            });

            nearbyPlayers.forEach(player => {
                // Aplicar todos los buffs del tipo de constelación
                type.buffs.forEach(buff => {
                    player.addEffect(buff, 200, {
                        amplifier: type.fairies >= 5 ? 1 : 0,
                        showParticles: false
                    });
                });

                // Mensaje personalizado
                try {
                    player.onScreenDisplay.setActionBar(
                        `${type.color}${type.name} §8▸ §fBlessed by fairy magic ✨`
                    );
                } catch (e) { }
            });

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

    dissolveConstellation(constellationId) {
        try {
            const constellation = this.activeConstellations.get(constellationId);
            if (!constellation) return;

            // Efecto de disolución (reducido 80%)
            const { centerPoint, dimension, type } = constellation;
            
            for (let i = 0; i < 2; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const radius = Math.random() * 3;
                    const height = Math.random() * 2;
                    
                    dimension.spawnParticle(type.particles, {
                        x: centerPoint.x + Math.cos(angle) * radius,
                        y: centerPoint.y + height,
                        z: centerPoint.z + Math.sin(angle) * radius
                    });
                }, i * 5);
            }

            this.activeConstellations.delete(constellationId);

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

    notifyNearbyPlayers(constellation) {
        try {
            const { centerPoint, type, dimension } = constellation;
            
            dimension.getPlayers({
                location: centerPoint,
                maxDistance: 30
            }).forEach(player => {
                try {
                    player.sendMessage(
                        `${type.color}✦ ${type.name} has formed! ${type.color}✦`
                    );
                } catch (e) { }
            });
        } catch (error) {
            // Error notifying
        }
    },

    // ==================== SISTEMA DE RASTRO DE BENDICIONES ====================

    updateBlessingTrails() {
        try {
            // Crear nuevos rastros donde vuelan las hadas
            world.getDimension('overworld').getEntities({
                type: 'myw:fairy'
            }).forEach(fairy => {
                if (!fairy.isValid()) return;
                
                this.createBlessingTrail(fairy);
            });

            // Actualizar rastros existentes
            const trailsToRemove = new Set();
            
            this.blessingTrails.forEach(trail => {
                trail.age++;
                
                if (trail.age >= this.config.blessingTrail.trailLifetime) {
                    trailsToRemove.add(trail);
                } else {
                    this.updateTrailEffects(trail);
                    this.checkTrailInteraction(trail);
                }
            });

            trailsToRemove.forEach(trail => this.blessingTrails.delete(trail));

        } catch (error) {
            // Error updating trails
        }
    },

    createBlessingTrail(fairy) {
        try {
            const location = fairy.location;
            const dimension = fairy.dimension;
            
            const trail = {
                id: `trail_${Date.now()}_${Math.random()}`,
                location: { ...location },
                dimension: dimension,
                age: 0,
                blessed: new Set() // Jugadores ya bendecidos
            };

            this.blessingTrails.add(trail);

            // Partículas del rastro
            dimension.spawnParticle('myw:mythril_particle_minimalist', location);

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

    updateTrailEffects(trail) {
        try {
            if (trail.age % 25 !== 0) return; // Reducido 80%
            
            // Partículas flotantes (mucho menos)
            const particleLocation = {
                x: trail.location.x + (Math.random() - 0.5) * 0.5,
                y: trail.location.y + Math.random() * 0.5,
                z: trail.location.z + (Math.random() - 0.5) * 0.5
            };
            
            trail.dimension.spawnParticle('myw:mythril_heal_particle', particleLocation);

        } catch (e) { }
    },

    checkTrailInteraction(trail) {
        try {
            const nearbyPlayers = trail.dimension.getPlayers({
                location: trail.location,
                maxDistance: 1.5
            });

            nearbyPlayers.forEach(player => {
                if (trail.blessed.has(player.id)) return;
                
                // Bendecir jugador
                this.applyBlessingToPlayer(player, trail);
                trail.blessed.add(player.id);
            });

        } catch (error) {
            // Error checking interaction
        }
    },

    applyBlessingToPlayer(player, trail) {
        try {
            // Curación instantánea
            const health = player.getComponent('minecraft:health');
            if (health && health.currentValue < health.effectiveMax) {
                player.applyDamage(-this.config.blessingTrail.healAmount);
            }

            // Buff corto
            player.addEffect('regeneration', this.config.blessingTrail.buffDuration, {
                amplifier: 0,
                showParticles: false
            });

            // Efecto visual (reducido 80%)
            for (let i = 0; i < 1; i++) {
                const angle = (i / 4) * Math.PI * 2;
                trail.dimension.spawnParticle('myw:mythril_heal_particle', {
                    x: player.location.x + Math.cos(angle),
                    y: player.location.y + 1,
                    z: player.location.z + Math.sin(angle)
                });
            }

            // Mensaje sutil
            try {
                player.onScreenDisplay.setActionBar('§d✨ Blessed by fairy trail');
            } catch (e) { }

            // Sonido
            try {
                trail.dimension.playSound('random.orb', player.location, {
                    volume: 0.3,
                    pitch: 1.8
                });
            } catch (e) { }

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

    // ==================== SISTEMA DE TRANSFORMACIÓN MÁGICA ====================

    checkTransformations() {
        try {
            world.getDimension('overworld').getEntities({
                type: 'myw:fairy'
            }).forEach(fairy => {
                if (!fairy.isValid()) return;
                
                const fairyId = fairy.id;
                let state = this.fairyStates.get(fairyId) || this.createFairyState(fairyId);

                const currentTick = system.currentTick;
                if (currentTick - state.lastTransformCheck < this.config.transformation.cooldown) {
                    return;
                }

                state.lastTransformCheck = currentTick;
                this.fairyStates.set(fairyId, state);

                // Buscar items cercanos en el suelo
                this.attemptTransformation(fairy);
            });

        } catch (error) {
            // Error checking transformations
        }
    },

    attemptTransformation(fairy) {
        try {
            const nearbyItems = fairy.dimension.getEntities({
                type: 'minecraft:item',
                location: fairy.location,
                maxDistance: this.config.transformation.radius
            });

            nearbyItems.forEach(itemEntity => {
                if (Math.random() > this.config.transformation.successChance) return;
                
                const itemStack = itemEntity.getComponent('minecraft:item')?.itemStack;
                if (!itemStack) return;

                const transformed = this.getTransformedItem(itemStack.typeId);
                if (!transformed) return;

                // Animación de transformación
                this.createTransformationEffect(fairy.dimension, itemEntity.location);

                // Dar el item transformado
                try {
                    itemEntity.dimension.runCommand(
                        `summon item ${itemEntity.location.x} ${itemEntity.location.y} ${itemEntity.location.z} 0 ${transformed}`
                    );
                } catch (e) { }

                // Eliminar item original
                try {
                    itemEntity.kill();
                } catch (e) { }
            });

        } catch (error) {
            // Error attempting transformation
        }
    },

    getTransformedItem(originalItem) {
        const transformations = {
            'minecraft:iron_ingot': 'myw:mythril_nugget',
            'minecraft:gold_ingot': 'myw:mythril_nugget',
            'minecraft:coal': 'myw:mythril_dust',
            'minecraft:redstone': 'myw:crystal_mythril',
            'minecraft:lapis_lazuli': 'myw:fairy_dust',
            'minecraft:wheat': 'minecraft:bread',
            'minecraft:apple': 'minecraft:golden_apple'
        };

        return transformations[originalItem] || null;
    },

    createTransformationEffect(dimension, location) {
        try {
            // Espiral de transformación (reducida 80%)
            for (let i = 0; i < 3; i++) {
                system.runTimeout(() => {
                    const angle = (i / 12) * Math.PI * 4;
                    const radius = 1 - (i / 12);
                    const height = i * 0.15;
                    
                    dimension.spawnParticle('myw:mythril_particle_serpentine', {
                        x: location.x + Math.cos(angle) * radius,
                        y: location.y + height,
                        z: location.z + Math.sin(angle) * radius
                    });
                }, i * 2);
            }

            // Sonido mágico
            system.runTimeout(() => {
                try {
                    dimension.playSound('random.levelup', location, {
                        volume: 0.4,
                        pitch: 1.8
                    });
                } catch (e) { }
            }, 15);

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

    // ==================== UTILIDADES ====================

    createFairyState(fairyId) {
        return {
            id: fairyId,
            lastTransformCheck: 0
        };
    },

    calculateCenter(entities) {
        const sum = entities.reduce((acc, entity) => ({
            x: acc.x + entity.location.x,
            y: acc.y + entity.location.y,
            z: acc.z + entity.location.z
        }), { x: 0, y: 0, z: 0 });

        return {
            x: sum.x / entities.length,
            y: sum.y / entities.length,
            z: sum.z / entities.length
        };
    },

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

// Exportar función de inicialización
export function initializeFairyConstellationSystem() {
    FairyConstellationSystem.initialize();
    return FairyConstellationSystem;
}

