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

export const AncientMythrilSummonStaffSystem = {

    config: {
        // Configuración del ritual de invocación
        summonRitual: {
            entityCount: 7, // Número de entidades por ritual
            circleRadius: 9, // Radio del círculo de invocación
            ritualDuration: 200, // Duración total del ritual (10 segundos)
            cooldownTime: 10000, // 10 segundos de cooldown
            maxActiveMinions: 12 // Máximo de minions activos
        },

        // Efectos visuales geométricos y precisos
        visualEffects: {
            preparationTime: 100, // 5 segundos de preparación
            particleIntensity: 1, // Intensidad reducida de partículas
            lightningCount: 7, // Rayos durante el ritual (igual a entidades)
            portalSize: 10 // Tamaño del portal
        },

        // Configuración de entidades
        entities: [
            'myw:mythril_blokkit',
            'myw:raw_mythril_blokkit'
        ],

        // Partículas del ritual - uso específico
        particles: {
            // Para geometría precisa (círculos, líneas, formas)
            geometric: [
                'myw:mythril_particle',
                'myw:mythril_particle_minimalist'
            ],
            // Para efectos aleatorios (explosiones, auras, ambiente)
            random: [
                'myw:mythril_heal_particle',
                'myw:mythril_flight_particle'
            ]
        }
    },

    playerStates: new Map(),
    activeMinions: new Map(),
    activeRituals: new Set(),

    // Sistema principal de invocación
    handleSummonStaff(player, itemStack) {
        try {
            const playerId = player.id;
            let state = this.playerStates.get(playerId) || this.createNewState(playerId);
            
            const currentTime = Date.now();
            
            // Verificar cooldown
            if (currentTime - state.lastSummon < this.config.summonRitual.cooldownTime) {
                const remainingCooldown = Math.ceil((this.config.summonRitual.cooldownTime - (currentTime - state.lastSummon)) / 1000);
                this.sendSummonMessage(player, `§c⌛ Cooldown: ${remainingCooldown}s remaining`);
                return;
            }

            // Verificar límite de minions
            const activeCount = this.getActiveMinionsCount(playerId);
            if (activeCount >= this.config.summonRitual.maxActiveMinions) {
                this.sendSummonMessage(player, `§c⚠ Maximum minions reached (${activeCount}/${this.config.summonRitual.maxActiveMinions})`);
                return;
            }

            // Iniciar ritual de invocación
            this.startSummonRitual(player, state);
            
            this.playerStates.set(playerId, state);

        } catch (error) {
            this.sendSummonMessage(player, '§c⚠ Error in summoning system');
        }
    },

    // Inicia el ritual de invocación espectacular
    startSummonRitual(player, state) {
        try {
            const playerId = player.id;
            const dimension = player.dimension;
            const origin = player.location;

            // Marcar ritual como activo
            this.activeRituals.add(playerId);
            state.lastSummon = Date.now();

            this.sendSummonMessage(player, '§5✦ §dINITIATING ANCIENT SUMMONING RITUAL §5✦');

            // FASE 1: PREPARACIÓN ESPECTACULAR (5 segundos)
            this.executeRitualPreparation(player, dimension, origin);

            // FASE 2: CÍRCULOS MÁGICOS (3 segundos después)
            system.runTimeout(() => {
                if (this.activeRituals.has(playerId)) {
                    this.createMagicCircles(dimension, origin);
                }
            }, 60);

            // FASE 3: PORTAL DIMENSIONAL (5 segundos después)
            system.runTimeout(() => {
                if (this.activeRituals.has(playerId)) {
                    this.openDimensionalPortal(dimension, origin);
                }
            }, 100);

            // FASE 4: INVOCACIÓN FINAL (7 segundos después)
            system.runTimeout(() => {
                if (this.activeRituals.has(playerId)) {
                    this.executeFinalSummoning(player, dimension, origin);
                    this.activeRituals.delete(playerId);
                }
            }, 140);

            // Mensaje de finalización (10 segundos después)
            system.runTimeout(() => {
                this.sendSummonMessage(player, '§a✓ §2Ancient ritual completed successfully!');
            }, 200);

        } catch (error) {
            this.activeRituals.delete(player.id);
        }
    },

    // FASE 1: Preparación ritual con geometría precisa
    executeRitualPreparation(player, dimension, origin) {
        try {
            this.sendSummonMessage(player, '§6⚡ Channeling ancient powers...');

            // Columna de energía geométrica (heptágono ascendente)
            for (let h = 0; h < 20; h++) {
                system.runTimeout(() => {
                    const columnPos = {
                        x: origin.x,
                        y: origin.y + h,
                        z: origin.z
                    };

                    // Núcleo central (aleatorio)
                    if (Math.random() < 0.3) {
                        const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                        dimension.spawnParticle(randomParticle, columnPos);
                    }

                    // Heptágono geométrico perfecto
                    const sides = 7;
                    const radius = 2 + h * 0.1;
                    
                    for (let i = 0; i < sides; i++) {
                        const angle = (i / sides) * Math.PI * 2 + h * 0.1;
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: origin.x + Math.cos(angle) * radius,
                            y: origin.y + h,
                            z: origin.z + Math.sin(angle) * radius
                        });
                    }

                    // Anillos geométricos cada 4 niveles
                    if (h % 4 === 0) {
                        this.createGeometricRing(dimension, {
                            x: origin.x,
                            y: origin.y + h,
                            z: origin.z
                        }, 3 + h * 0.15, 14); // 14 lados para mayor precisión
                    }

                }, h * 3);
            }

            // Pulsos geométricos concéntricos
            for (let pulse = 0; pulse < 7; pulse++) {
                system.runTimeout(() => {
                    this.createGeometricPulse(dimension, origin, pulse * 2 + 4);
                }, pulse * 12);
            }

        } catch (error) {
            // Error en preparación
        }
    },

    // FASE 2: Crear círculos mágicos geométricos perfectos
    createMagicCircles(dimension, origin) {
        try {
            this.sendSummonMessage(world.getAllPlayers()[0], '§d⭐ Creating mystical summoning circles...');

            // Heptágono exterior perfecto (28 puntos = 4×7)
            this.createPerfectCircle(dimension, origin, this.config.summonRitual.circleRadius, 'myw:mythril_particle_minimalist', 28);

            // Círculo medio con geometría dodecagonal
            system.runTimeout(() => {
                this.createPerfectCircle(dimension, origin, this.config.summonRitual.circleRadius * 0.65, 'myw:mythril_particle', 21);
            }, 15);

            // Círculo interior heptagonal
            system.runTimeout(() => {
                this.createPerfectCircle(dimension, origin, this.config.summonRitual.circleRadius * 0.35, 'myw:mythril_particle_minimalist', 14);
            }, 30);

            // Símbolos geométricos en las 7 posiciones
            const entityPositions = this.calculateSummonPositions(origin);
            entityPositions.forEach((pos, index) => {
                system.runTimeout(() => {
                    this.createGeometricSymbol(dimension, pos, index);
                }, index * 7);
            });

            // Conexiones geométricas perfectas (estrella heptagonal)
            system.runTimeout(() => {
                this.createHeptagonalConnections(dimension, origin, entityPositions);
            }, 50);

        } catch (error) {
            // Error en círculos
        }
    },

    // FASE 3: Abrir portal dimensional geométrico
    openDimensionalPortal(dimension, origin) {
        try {
            this.sendSummonMessage(world.getAllPlayers()[0], '§5🌀 Opening dimensional portal...');

            const portalRadius = this.config.visualEffects.portalSize;
            const portalDuration = 70;

            // Portal geométrico con heptágonos concéntricos ascendentes
            for (let t = 0; t < portalDuration; t++) {
                system.runTimeout(() => {
                    const portalHeight = t * 0.4;
                    const currentRadius = portalRadius * (1 - t / portalDuration * 0.4);
                    const rotationAngle = t * 0.1;

                    // Heptágono principal geométrico
                    for (let i = 0; i < 7; i++) {
                        const angle = (i / 7) * Math.PI * 2 + rotationAngle;
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: origin.x + Math.cos(angle) * currentRadius,
                            y: origin.y + portalHeight,
                            z: origin.z + Math.sin(angle) * currentRadius
                        });
                    }

                    // Dodecágono interno
                    if (t % 2 === 0) {
                        for (let i = 0; i < 12; i++) {
                            const angle = (i / 12) * Math.PI * 2 - rotationAngle;
                            dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                x: origin.x + Math.cos(angle) * currentRadius * 0.6,
                                y: origin.y + portalHeight,
                                z: origin.z + Math.sin(angle) * currentRadius * 0.6
                            });
                        }
                    }

                    // Vórtice central aleatorio
                    if (t % 4 === 0) {
                        for (let v = 0; v < 3; v++) {
                            const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                            dimension.spawnParticle(randomParticle, {
                                x: origin.x + (Math.random() - 0.5) * 1.5,
                                y: origin.y + portalHeight + v * 0.5,
                                z: origin.z + (Math.random() - 0.5) * 1.5
                            });
                        }
                    }

                }, t * 1);
            }

            // Flash geométrico final
            system.runTimeout(() => {
                this.createGeometricFlash(dimension, origin);
            }, portalDuration);

        } catch (error) {
            // Error en portal
        }
    },

    // FASE 4: Invocación final y spawn de entidades
    executeFinalSummoning(player, dimension, origin) {
        try {
            this.sendSummonMessage(player, '§c⚔ §4SUMMONING ANCIENT GUARDIANS §c⚔');

            const summonPositions = this.calculateSummonPositions(origin);
            const entityTypes = this.config.entities;

            summonPositions.forEach((position, index) => {
                system.runTimeout(() => {
                    try {
                        // Efectos de pre-spawn
                        this.createPreSpawnEffects(dimension, position);

                        // Spawn efectivo después de los efectos
                        system.runTimeout(() => {
                            const entityType = entityTypes[index % entityTypes.length];
                            
                            try {
                                // Spawn de la entidad
                                const entity = dimension.spawnEntity(entityType, position);
                                
                                // Registrar minion
                                this.registerMinion(player.id, entity);

                                // Efectos post-spawn
                                this.createPostSpawnEffects(dimension, position, index);

                                this.sendSummonMessage(player, `§a✓ Summoned: §e${entityType.replace('myw:', '')} §7at position ${index + 1}`);

                            } catch (spawnError) {
                                this.sendSummonMessage(player, `§c⚠ Failed to spawn ${entityType}`);
                                // Crear efectos fallback
                                this.createFailedSpawnEffects(dimension, position);
                            }

                        }, 20);

                    } catch (error) {
                        // Error en spawn individual
                    }
                }, index * 25);
            });

            // Efectos finales del ritual
            system.runTimeout(() => {
                this.createRitualFinale(dimension, origin);
            }, summonPositions.length * 25 + 40);

        } catch (error) {
            this.sendSummonMessage(player, '§c⚠ Error in final summoning');
        }
    },

    // Calcular posiciones de invocación en círculo
    calculateSummonPositions(origin) {
        const positions = [];
        const entityCount = this.config.summonRitual.entityCount;
        const radius = this.config.summonRitual.circleRadius;

        for (let i = 0; i < entityCount; i++) {
            const angle = (i / entityCount) * Math.PI * 2;
            positions.push({
                x: origin.x + Math.cos(angle) * radius,
                y: origin.y,
                z: origin.z + Math.sin(angle) * radius
            });
        }

        return positions;
    },

    // EFECTOS VISUALES ESPECTACULARES

    createGeometricRing(dimension, center, radius, sides) {
        try {
            // Polígono regular perfecto
            for (let i = 0; i < sides; i++) {
                const angle = (i / sides) * Math.PI * 2;
                dimension.spawnParticle('myw:mythril_particle_minimalist', {
                    x: center.x + Math.cos(angle) * radius,
                    y: center.y,
                    z: center.z + Math.sin(angle) * radius
                });
            }
        } catch (error) {
            // Error en ring
        }
    },

    createGeometricPulse(dimension, origin, radius) {
        try {
            // Heptágono perfecto
            for (let i = 0; i < 7; i++) {
                const angle = (i / 7) * Math.PI * 2;
                
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle', {
                        x: origin.x + Math.cos(angle) * radius,
                        y: origin.y + 0.1,
                        z: origin.z + Math.sin(angle) * radius
                    });
                }, i * 1);
            }

            // Efectos aleatorios en el centro
            if (Math.random() < 0.4) {
                const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                dimension.spawnParticle(randomParticle, {
                    x: origin.x + (Math.random() - 0.5) * 1,
                    y: origin.y + 1,
                    z: origin.z + (Math.random() - 0.5) * 1
                });
            }
        } catch (error) {
            // Error en pulse
        }
    },

    createPerfectCircle(dimension, center, radius, particle, pointCount) {
        try {
            // Círculo geométrico perfecto
            for (let i = 0; i < pointCount; i++) {
                const angle = (i / pointCount) * Math.PI * 2;
                
                system.runTimeout(() => {
                    dimension.spawnParticle(particle, {
                        x: center.x + Math.cos(angle) * radius,
                        y: center.y + 0.1,
                        z: center.z + Math.sin(angle) * radius
                    });
                }, i * 1);
            }

            // Pilares geométricos en puntos específicos (cada 7 puntos)
            system.runTimeout(() => {
                for (let i = 0; i < pointCount; i += 7) {
                    const angle = (i / pointCount) * Math.PI * 2;
                    
                    for (let h = 0; h < 2; h++) {
                        system.runTimeout(() => {
                            // Usar partículas aleatorias para los pilares
                            const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                            dimension.spawnParticle(randomParticle, {
                                x: center.x + Math.cos(angle) * radius,
                                y: center.y + h + 1,
                                z: center.z + Math.sin(angle) * radius
                            });
                        }, h * 5);
                    }
                }
            }, pointCount + 10);

        } catch (error) {
            // Error en círculo perfecto
        }
    },

    createGeometricSymbol(dimension, position, symbolIndex) {
        try {
            // 7 símbolos geométricos diferentes para las 7 posiciones
            const symbolPatterns = [
                this.createHeptagonSymbol,        // 0 - Heptágono
                this.createHexagramSymbol,        // 1 - Hexagrama (estrella de 6 puntas)
                this.createPentagramSymbol,       // 2 - Pentagrama
                this.createOctagonSymbol,         // 3 - Octágono
                this.createTriangleSymbol,        // 4 - Triángulo
                this.createSquareSymbol,          // 5 - Cuadrado
                this.createDodecagonSymbol        // 6 - Dodecágono
            ];

            const pattern = symbolPatterns[symbolIndex % symbolPatterns.length];
            pattern.call(this, dimension, position);

        } catch (error) {
            // Error en símbolo
        }
    },

    createHeptagonSymbol(dimension, center) {
        try {
            const radius = 1.8;
            const sides = 7;
            
            // Heptágono perfecto
            for (let i = 0; i < sides; i++) {
                const angle1 = (i / sides) * Math.PI * 2;
                const angle2 = ((i + 1) % sides / sides) * Math.PI * 2;
                
                const start = {
                    x: center.x + Math.cos(angle1) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle1) * radius
                };
                
                const end = {
                    x: center.x + Math.cos(angle2) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle2) * radius
                };

                this.createGeometricLine(dimension, start, end, 5);
            }
        } catch (error) {
            // Error en heptágono
        }
    },

    createHexagramSymbol(dimension, center) {
        try {
            const radius = 1.8;
            
            // Estrella de 6 puntas (dos triángulos)
            for (let triangle = 0; triangle < 2; triangle++) {
                const angleOffset = triangle * Math.PI / 3;
                
                for (let i = 0; i < 3; i++) {
                    const angle1 = (i / 3) * Math.PI * 2 + angleOffset;
                    const angle2 = ((i + 1) % 3 / 3) * Math.PI * 2 + angleOffset;
                    
                    const start = {
                        x: center.x + Math.cos(angle1) * radius,
                        y: center.y + 0.1,
                        z: center.z + Math.sin(angle1) * radius
                    };
                    
                    const end = {
                        x: center.x + Math.cos(angle2) * radius,
                        y: center.y + 0.1,
                        z: center.z + Math.sin(angle2) * radius
                    };

                    this.createGeometricLine(dimension, start, end, 4);
                }
            }
        } catch (error) {
            // Error en hexagrama
        }
    },

    createPentagramSymbol(dimension, center) {
        try {
            const radius = 1.8;
            const points = 5;
            
            // Pentagrama perfecto (estrella de 5 puntas)
            for (let i = 0; i < points; i++) {
                const angle1 = (i / points) * Math.PI * 2;
                const angle2 = ((i + 2) % points / points) * Math.PI * 2;
                
                const start = {
                    x: center.x + Math.cos(angle1) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle1) * radius
                };
                
                const end = {
                    x: center.x + Math.cos(angle2) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle2) * radius
                };

                this.createGeometricLine(dimension, start, end, 6);
            }
        } catch (error) {
            // Error en pentagrama
        }
    },

    createOctagonSymbol(dimension, center) {
        try {
            const radius = 1.8;
            const sides = 8;
            
            // Octágono perfecto
            for (let i = 0; i < sides; i++) {
                const angle1 = (i / sides) * Math.PI * 2;
                const angle2 = ((i + 1) % sides / sides) * Math.PI * 2;
                
                const start = {
                    x: center.x + Math.cos(angle1) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle1) * radius
                };
                
                const end = {
                    x: center.x + Math.cos(angle2) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle2) * radius
                };

                this.createGeometricLine(dimension, start, end, 4);
            }
        } catch (error) {
            // Error en octágono
        }
    },

    createSquareSymbol(dimension, center) {
        try {
            const size = 1.6;
            
            // Cuadrado perfecto
            const corners = [
                { x: center.x - size, z: center.z - size },
                { x: center.x + size, z: center.z - size },
                { x: center.x + size, z: center.z + size },
                { x: center.x - size, z: center.z + size }
            ];
            
            for (let i = 0; i < 4; i++) {
                const start = {
                    x: corners[i].x,
                    y: center.y + 0.1,
                    z: corners[i].z
                };
                
                const end = {
                    x: corners[(i + 1) % 4].x,
                    y: center.y + 0.1,
                    z: corners[(i + 1) % 4].z
                };

                this.createGeometricLine(dimension, start, end, 5);
            }
        } catch (error) {
            // Error en cuadrado
        }
    },

    createDodecagonSymbol(dimension, center) {
        try {
            const radius = 1.8;
            const sides = 12;
            
            // Dodecágono perfecto (cada 3 lados)
            for (let i = 0; i < sides; i += 3) {
                const angle1 = (i / sides) * Math.PI * 2;
                const angle2 = ((i + 3) % sides / sides) * Math.PI * 2;
                
                const start = {
                    x: center.x + Math.cos(angle1) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle1) * radius
                };
                
                const end = {
                    x: center.x + Math.cos(angle2) * radius,
                    y: center.y + 0.1,
                    z: center.z + Math.sin(angle2) * radius
                };

                this.createGeometricLine(dimension, start, end, 3);
            }
        } catch (error) {
            // Error en dodecágono
        }
    },

    createTriangleSymbol(dimension, center) {
        try {
            const radius = 1.8;
            const points = [
                { x: center.x, y: center.y + 0.1, z: center.z + radius },
                { x: center.x - radius * 0.866, y: center.y + 0.1, z: center.z - radius * 0.5 },
                { x: center.x + radius * 0.866, y: center.y + 0.1, z: center.z - radius * 0.5 }
            ];

            // Líneas del triángulo
            for (let i = 0; i < 3; i++) {
                const start = points[i];
                const end = points[(i + 1) % 3];
                this.createGeometricLine(dimension, start, end, 6);
            }
        } catch (error) {
            // Error en triángulo
        }
    },


    createGeometricLine(dimension, start, end, steps) {
        try {
            for (let step = 0; step <= steps; step++) {
                system.runTimeout(() => {
                    const progress = step / steps;
                    const linePos = {
                        x: start.x + (end.x - start.x) * progress,
                        y: start.y + (end.y - start.y) * progress,
                        z: start.z + (end.z - start.z) * progress
                    };

                    // Alternar entre las dos partículas geométricas
                    const particle = step % 2 === 0 ? 'myw:mythril_particle' : 'myw:mythril_particle_minimalist';
                    dimension.spawnParticle(particle, linePos);
                }, step * 2);
            }
        } catch (error) {
            // Error en línea
        }
    },

    createHeptagonalConnections(dimension, center, positions) {
        try {
            // Conectar centro con cada posición (líneas rectas geométricas)
            positions.forEach((pos, index) => {
                system.runTimeout(() => {
                    this.createGeometricConnection(dimension, center, pos);
                }, index * 3);
            });

            // Crear estrella heptagonal (conectar cada posición con la 2ª siguiente)
            for (let i = 0; i < positions.length; i++) {
                const targetIndex = (i + 2) % positions.length;
                system.runTimeout(() => {
                    this.createGeometricConnection(dimension, positions[i], positions[targetIndex]);
                }, positions.length * 3 + i * 4);
            }
        } catch (error) {
            // Error en conexiones
        }
    },

    createGeometricConnection(dimension, start, end) {
        try {
            const steps = 8;

            for (let step = 0; step <= steps; step++) {
                system.runTimeout(() => {
                    const progress = step / steps;
                    const connectionPos = {
                        x: start.x + (end.x - start.x) * progress,
                        y: start.y + (end.y - start.y) * progress + 0.3,
                        z: start.z + (end.z - start.z) * progress
                    };

                    // Línea geométrica perfecta
                    const particle = step % 2 === 0 ? 'myw:mythril_particle' : 'myw:mythril_particle_minimalist';
                    dimension.spawnParticle(particle, connectionPos);

                    // Efectos aleatorios ocasionales en puntos específicos
                    if (step % 4 === 0 && Math.random() < 0.3) {
                        const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                        dimension.spawnParticle(randomParticle, {
                            x: connectionPos.x + (Math.random() - 0.5) * 0.5,
                            y: connectionPos.y + 0.5,
                            z: connectionPos.z + (Math.random() - 0.5) * 0.5
                        });
                    }

                }, step * 1);
            }
        } catch (error) {
            // Error en conexión
        }
    },

    createGeometricFlash(dimension, origin) {
        try {
            // Flash geométrico en anillos heptagonales
            const flashRadius = 12;

            for (let ring = 0; ring < 4; ring++) {
                system.runTimeout(() => {
                    const ringRadius = flashRadius * ((ring + 1) / 4);
                    
                    // Heptágono geométrico
                    for (let i = 0; i < 7; i++) {
                        const angle = (i / 7) * Math.PI * 2;
                        const particle = ring % 2 === 0 ? 'myw:mythril_particle' : 'myw:mythril_particle_minimalist';
                        
                        dimension.spawnParticle(particle, {
                            x: origin.x + Math.cos(angle) * ringRadius,
                            y: origin.y + ring * 0.5,
                            z: origin.z + Math.sin(angle) * ringRadius
                        });
                    }

                    // Efectos aleatorios dispersos
                    for (let i = 0; i < 5; i++) {
                        const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                        dimension.spawnParticle(randomParticle, {
                            x: origin.x + (Math.random() - 0.5) * ringRadius * 2,
                            y: origin.y + Math.random() * 6,
                            z: origin.z + (Math.random() - 0.5) * ringRadius * 2
                        });
                    }
                }, ring * 3);
            }
        } catch (error) {
            // Error en flash
        }
    },

    createPreSpawnEffects(dimension, position) {
        try {
            // Columna geométrica de invocación (más eficiente)
            for (let h = 0; h < 6; h++) {
                system.runTimeout(() => {
                    // Heptágono ascendente
                    for (let i = 0; i < 7; i++) {
                        const angle = (i / 7) * Math.PI * 2 + h * 0.3;
                        const radius = 1 + h * 0.15;
                        
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: position.x + Math.cos(angle) * radius,
                            y: position.y + h,
                            z: position.z + Math.sin(angle) * radius
                        });
                    }

                    // Efectos aleatorios centrales
                    if (h % 2 === 0) {
                        const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                        dimension.spawnParticle(randomParticle, {
                            x: position.x + (Math.random() - 0.5) * 0.5,
                            y: position.y + h + 1,
                            z: position.z + (Math.random() - 0.5) * 0.5
                        });
                    }
                }, h * 3);
            }
        } catch (error) {
            // Error en pre-spawn
        }
    },

    createPostSpawnEffects(dimension, position, entityIndex) {
        try {
            // Explosión geométrica de bienvenida (heptágono)
            for (let i = 0; i < 7; i++) {
                system.runTimeout(() => {
                    const angle = (i / 7) * Math.PI * 2;
                    const radius = 2.5;
                    
                    dimension.spawnParticle('myw:mythril_particle_minimalist', {
                        x: position.x + Math.cos(angle) * radius,
                        y: position.y + 1,
                        z: position.z + Math.sin(angle) * radius
                    });
                }, i * 2);
            }

            // Efectos aleatorios dispersos
            system.runTimeout(() => {
                for (let i = 0; i < 4; i++) {
                    const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                    dimension.spawnParticle(randomParticle, {
                        x: position.x + (Math.random() - 0.5) * 3,
                        y: position.y + Math.random() * 2,
                        z: position.z + (Math.random() - 0.5) * 3
                    });
                }
            }, 15);

        } catch (error) {
            // Error en post-spawn
        }
    },

    createInitialAura(dimension, position) {
        try {
            const auraRadius = 2;

            // Heptágono de aura
            for (let i = 0; i < 7; i++) {
                system.runTimeout(() => {
                    const angle = (i / 7) * Math.PI * 2;
                    const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                    dimension.spawnParticle(randomParticle, {
                        x: position.x + Math.cos(angle) * auraRadius,
                        y: position.y + 1,
                        z: position.z + Math.sin(angle) * auraRadius
                    });
                }, i * 4);
            }
        } catch (error) {
            // Error en aura
        }
    },

    createFailedSpawnEffects(dimension, position) {
        try {
            // Efectos de fallo
            for (let i = 0; i < 8; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle', {
                        x: position.x + (Math.random() - 0.5) * 2,
                        y: position.y + Math.random() * 2,
                        z: position.z + (Math.random() - 0.5) * 2
                    });
                }, i * 2);
            }
        } catch (error) {
            // Error en failed effects
        }
    },

    createRitualFinale(dimension, origin) {
        try {
            // Finale geométrico elegante
            const finaleRadius = 15;

            // 4 ondas heptagonales expansivas
            for (let wave = 0; wave < 4; wave++) {
                system.runTimeout(() => {
                    const waveRadius = (wave + 1) * 4;
                    
                    // Heptágono perfecto
                    for (let i = 0; i < 7; i++) {
                        const angle = (i / 7) * Math.PI * 2;
                        const particle = wave % 2 === 0 ? 'myw:mythril_particle' : 'myw:mythril_particle_minimalist';

                        dimension.spawnParticle(particle, {
                            x: origin.x + Math.cos(angle) * waveRadius,
                            y: origin.y + wave * 0.5,
                            z: origin.z + Math.sin(angle) * waveRadius
                        });
                    }

                    // Efectos aleatorios dispersos por onda
                    for (let r = 0; r < 6; r++) {
                        const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                        dimension.spawnParticle(randomParticle, {
                            x: origin.x + (Math.random() - 0.5) * waveRadius * 2,
                            y: origin.y + Math.random() * 4,
                            z: origin.z + (Math.random() - 0.5) * waveRadius * 2
                        });
                    }
                }, wave * 8);
            }

            // Columna final heptagonal ascendente
            system.runTimeout(() => {
                for (let h = 0; h < 20; h++) {
                    system.runTimeout(() => {
                        const columnRadius = 2.5 * (1 - h / 20);
                        
                        // Heptágono ascendente
                        for (let i = 0; i < 7; i++) {
                            const angle = (i / 7) * Math.PI * 2 + h * 0.2;
                            const particle = h % 2 === 0 ? 'myw:mythril_particle' : 'myw:mythril_particle_minimalist';

                            dimension.spawnParticle(particle, {
                                x: origin.x + Math.cos(angle) * columnRadius,
                                y: origin.y + h,
                                z: origin.z + Math.sin(angle) * columnRadius
                            });
                        }

                        // Efectos aleatorios centrales
                        if (h % 4 === 0) {
                            const randomParticle = this.config.particles.random[Math.floor(Math.random() * this.config.particles.random.length)];
                            dimension.spawnParticle(randomParticle, {
                                x: origin.x + (Math.random() - 0.5),
                                y: origin.y + h + 2,
                                z: origin.z + (Math.random() - 0.5)
                            });
                        }
                    }, h * 2);
                }
            }, 40);

        } catch (error) {
            // Error en finale
        }
    },

    // SISTEMA DE GESTIÓN DE MINIONS

    registerMinion(playerId, entity) {
        try {
            if (!this.activeMinions.has(playerId)) {
                this.activeMinions.set(playerId, new Set());
            }

            this.activeMinions.get(playerId).add(entity.id);

            // Limpieza automática cuando la entidad muere
            system.runInterval(() => {
                if (!entity.isValid()) {
                    if (this.activeMinions.has(playerId)) {
                        this.activeMinions.get(playerId).delete(entity.id);
                    }
                    return; // Para el interval
                }
            }, 100);

        } catch (error) {
            // Error registrando minion
        }
    },

    getActiveMinionsCount(playerId) {
        try {
            if (!this.activeMinions.has(playerId)) {
                return 0;
            }

            const minions = this.activeMinions.get(playerId);
            
            // Limpiar minions inválidos
            const validMinions = new Set();
            minions.forEach(entityId => {
                try {
                    // Intenta encontrar la entidad (método básico de validación)
                    validMinions.add(entityId);
                } catch (error) {
                    // Entidad ya no existe
                }
            });

            this.activeMinions.set(playerId, validMinions);
            return validMinions.size;

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

    // UTILIDADES

    createNewState(playerId) {
        return {
            playerId: playerId,
            lastSummon: 0,
            totalSummons: 0,
            activeRitualId: null
        };
    },

    sendSummonMessage(player, message) {
        try {
            player.onScreenDisplay.setActionBar(message);
        } catch (error) {
            try {
                player.sendMessage(message);
            } catch (e) {
                // Error enviando mensaje
            }
        }
    }
};

// Registrar el componente del Summon Staff
export function registerAncientMythrilSummonStaff(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:ancient_mythril_summon_staff', {
        onUse(eventData) {
            const { itemStack, source } = eventData;
            AncientMythrilSummonStaffSystem.handleSummonStaff(source, itemStack);
        }
    });
}

// Inicializar el sistema
export function initializeAncientSummonStaffSystems() {
    system.runTimeout(() => {
        world.sendMessage('§5═══════════════════════════════════════');
        world.sendMessage('§5⚔ §dANCIENT MYTHRIL SUMMON STAFF §5⚔');
        world.sendMessage('§7Master of ancient summoning arts...');
        world.sendMessage('§bRitual System §8▸ §7Spectacular summoning circles');
        world.sendMessage('§dMinion Control §8▸ §7Command your guardians');
        world.sendMessage('§cDimensional Magic §8▸ §7Breach reality itself');
        world.sendMessage('§5═══════════════════════════════════════');
    }, 80);

    world.sendMessage('[OK] Ancient Mythril Summon Staff System initialized');
}
