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

// Sistema de Rituales de Mythril Optimizado
export class MythrilRitualSystem {
    constructor() {
        this.activeRituals = new Map();
        this.ritualCooldowns = new Map();
        this.particleHeight = 23; // Altura de la columna de partículas
    }

    initialize() {
        system.runInterval(() => {
            this.scanForRitualSetups();
            this.updateActiveRituals();
        }, 200);

        world.sendMessage('§b[MYTHRIL] §9Ritual System §binitialized');
    }

    scanForRitualSetups() {
        try {
            world.getAllPlayers().forEach(player => {
                const dimension = player.dimension;
                const { x, y, z } = player.location;

                const searchRadius = 60;

                for (let dx = -searchRadius; dx <= searchRadius; dx++) {
                    for (let dz = -searchRadius; dz <= searchRadius; dz++) {
                        const checkX = Math.floor(x + dx);
                        const checkY = Math.floor(y);
                        const checkZ = Math.floor(z + dz);

                        try {
                            const block = dimension.getBlock({ x: checkX, y: checkY, z: checkZ });

                            if (block?.typeId === 'myw:mythril_block') {
                                const ritualKey = `${checkX},${checkY},${checkZ}`;

                                if (!this.activeRituals.has(ritualKey)) {
                                    this.checkRitualConfiguration(dimension, checkX, checkY, checkZ);
                                }
                            }
                        } catch (error) {
                        }
                    }
                }
            });
        } catch (error) {
        }
    }

    checkRitualConfiguration(dimension, centerX, centerY, centerZ) {
        const ritualKey = `${centerX},${centerY},${centerZ}`;

        if (this.ritualCooldowns.has(ritualKey)) {
            const cooldownEnd = this.ritualCooldowns.get(ritualKey);
            if (Date.now() < cooldownEnd) {
                return;
            }
        }

        const rawMythrilBlocks = [];
        const searchRange = 8;

        for (let dx = -searchRange; dx <= searchRange; dx++) {
            for (let dz = -searchRange; dz <= searchRange; dz++) {
                if (dx === 0 && dz === 0) continue;

                try {
                    const block = dimension.getBlock({
                        x: centerX + dx,
                        y: centerY,
                        z: centerZ + dz
                    });

                    if (block?.typeId === 'myw:raw_mythril_block') {
                        rawMythrilBlocks.push({
                            x: centerX + dx,
                            y: centerY,
                            z: centerZ + dz
                        });
                    }
                } catch (error) {
                }
            }
        }

        if (rawMythrilBlocks.length >= 6) {
            const ritualBlocks = rawMythrilBlocks
                .sort((a, b) => {
                    const distA = Math.sqrt(
                        Math.pow(a.x - centerX, 2) +
                        Math.pow(a.z - centerZ, 2)
                    );
                    const distB = Math.sqrt(
                        Math.pow(b.x - centerX, 2) +
                        Math.pow(b.z - centerZ, 2)
                    );
                    return distA - distB;
                })
                .slice(0, 6);

            this.activateRitual(dimension, centerX, centerY, centerZ, ritualBlocks);
        }
    }

    // Activar el ritual
    activateRitual(dimension, centerX, centerY, centerZ, ritualBlocks) {
        const ritualKey = `${centerX},${centerY},${centerZ}`;

        this.activeRituals.set(ritualKey, {
            dimension: dimension,
            center: { x: centerX, y: centerY, z: centerZ },
            blocks: ritualBlocks,
            startTime: Date.now(),
            phase: 'connecting',
            connectionProgress: 0,
            hasRewarded: false
        });
        world.sendMessage(`§b✦ §9Mythril Ritual §bstarted§9 ✦`);

        this.startDirectConnectionPhase(ritualKey);
    }

    // Fase de conexión con rayos directos de partículas
    startDirectConnectionPhase(ritualKey) {
        const ritual = this.activeRituals.get(ritualKey);
        if (!ritual) return;

        let connectionTime = 0;
        const maxConnectionTime = 60; // 3 segundos

        const connectionInterval = system.runInterval(() => {
            connectionTime++;

            if (!this.activeRituals.has(ritualKey)) {
                system.clearRun(connectionInterval);
                return;
            }

            const progress = connectionTime / maxConnectionTime;
            ritual.connectionProgress = progress;

            const { dimension, center, blocks } = ritual;

            // Crear rayos directos desde cada bloque al centro
            blocks.forEach((block, index) => {
                // Calcular dirección del rayo
                const dx = center.x - block.x;
                const dy = center.y - block.y;
                const dz = center.z - block.z;
                const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

                // Número de partículas basado en la distancia
                const particleCount = Math.floor(distance * 4);

                // Crear rayo de partículas
                for (let i = 0; i <= particleCount * progress; i++) {
                    const t = i / particleCount;

                    // Posición de la partícula en el rayo
                    const particleX = block.x + dx * t + 0.5;
                    const particleY = block.y + dy * t + 0.5;
                    const particleZ = block.z + dz * t + 0.5;

                    // Alternar tipos de partículas para crear efecto de rayo
                    try {
                        if (i % 3 === 0) {
                            dimension.spawnParticle('myw:mythril_particle',
                                { x: particleX, y: particleY, z: particleZ });
                        } else if (i % 3 === 1) {
                            dimension.spawnParticle('myw:mythril_particle_minimalist',
                                { x: particleX, y: particleY, z: particleZ });
                        }
                    } catch (error) {
                        // Fallback a partículas vanilla si las custom fallan
                        dimension.spawnParticle('minecraft:end_rod',
                            { x: particleX, y: particleY, z: particleZ });
                    }
                }

                // Efecto pulsante en los bloques externos
                if (connectionTime % 10 === 0) {
                    for (let j = 0; j < 3; j++) {
                        const offsetY = j * 0.3;
                        try {
                            dimension.spawnParticle('myw:mythril_particle_serpentine',
                                { x: block.x + 0.5, y: block.y + 1 + offsetY, z: block.z + 0.5 });
                        } catch (error) {
                        }
                    }
                }
            });

            // Efecto en el centro
            const pulseSize = Math.sin(connectionTime * 0.2) * 0.5 + 1;
            for (let angle = 0; angle < Math.PI * 2; angle += Math.PI / 6) {
                const pulseX = center.x + 0.5 + Math.cos(angle) * pulseSize;
                const pulseZ = center.z + 0.5 + Math.sin(angle) * pulseSize;

                try {
                    dimension.spawnParticle('myw:mythril_particle',
                        { x: pulseX, y: center.y + 0.5, z: pulseZ });
                } catch (error) {
                    // Continuar
                }
            }

            // Transición a fase activa
            if (connectionTime >= maxConnectionTime) {
                system.clearRun(connectionInterval);
                ritual.phase = 'active';
                this.startActivePhase(ritualKey);
            }
        }, 1);

        ritual.activeInterval = connectionInterval;
    }

    // Fase activa del ritual con efectos creativos
    startActivePhase(ritualKey) {
        const ritual = this.activeRituals.get(ritualKey);
        if (!ritual) return;

        world.sendMessage('§b✦ §9Ritual active §b✦');

        let activeTime = 0;
        const activeInterval = system.runInterval(() => {
            activeTime++;

            if (!this.activeRituals.has(ritualKey)) {
                system.clearRun(activeInterval);
                return;
            }

            const { dimension, center, blocks } = ritual;

            // Mantener rayos conectados
            if (activeTime % 5 === 0) {
                blocks.forEach((block) => {
                    const dx = center.x - block.x;
                    const dy = center.y - block.y;
                    const dz = center.z - block.z;
                    const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
                    const particleCount = Math.floor(distance * 2);

                    for (let i = 0; i < particleCount; i++) {
                        const t = i / particleCount;
                        const wobble = Math.sin(activeTime * 0.1 + i * 0.5) * 0.1;

                        const particleX = block.x + dx * t + 0.5 + wobble;
                        const particleY = block.y + dy * t + 0.5;
                        const particleZ = block.z + dz * t + 0.5 + wobble;

                        try {
                            dimension.spawnParticle('myw:mythril_particle_minimalist',
                                { x: particleX, y: particleY, z: particleZ });
                        } catch (error) {
                            // Continuar
                        }
                    }
                });
            }

            // Columna central ascendente con espirales
            for (let height = 0; height < this.particleHeight; height++) {
                const spiralAngle = (height * 0.3) + (activeTime * 0.1);
                const spiralRadius = 0.5 + Math.sin(height * 0.2) * 0.3;

                // Triple espiral
                for (let spiral = 0; spiral < 3; spiral++) {
                    const angle = spiralAngle + (spiral * Math.PI * 2 / 3);
                    const particleX = center.x + 0.5 + Math.cos(angle) * spiralRadius;
                    const particleZ = center.z + 0.5 + Math.sin(angle) * spiralRadius;
                    const particleY = center.y + height * 0.5 + Math.sin(activeTime * 0.05) * 0.5;

                    try {
                        if (height % 3 === 0) {
                            dimension.spawnParticle('myw:mythril_particle',
                                { x: particleX, y: particleY, z: particleZ });
                        } else if (height % 3 === 1) {
                            dimension.spawnParticle('myw:mythril_particle_serpentine',
                                { x: particleX, y: particleY, z: particleZ });
                        } else {
                            dimension.spawnParticle('myw:mythril_particle_minimalist',
                                { x: particleX, y: particleY, z: particleZ });
                        }
                    } catch (error) {
                        // Continuar
                    }
                }
            }

            // Anillos rotatorios horizontales
            if (activeTime % 20 === 0) {
                for (let ring = 1; ring <= 3; ring++) {
                    const ringRadius = ring * 1.5;
                    const ringHeight = center.y + ring * 2;

                    for (let i = 0; i < 16; i++) {
                        const angle = (i / 16) * Math.PI * 2 + activeTime * 0.05;
                        const ringX = center.x + 0.5 + Math.cos(angle) * ringRadius;
                        const ringZ = center.z + 0.5 + Math.sin(angle) * ringRadius;

                        try {
                            dimension.spawnParticle('myw:mythril_particle_serpentine',
                                { x: ringX, y: ringHeight, z: ringZ });
                        } catch (error) {
                            // Continuar
                        }
                    }
                }
            }

            // Partículas flotantes aleatorias
            if (Math.random() < 0.3) {
                for (let i = 0; i < 5; i++) {
                    const randomAngle = Math.random() * Math.PI * 2;
                    const randomRadius = Math.random() * 4;
                    const randomHeight = Math.random() * 10;

                    const floatX = center.x + 0.5 + Math.cos(randomAngle) * randomRadius;
                    const floatZ = center.z + 0.5 + Math.sin(randomAngle) * randomRadius;
                    const floatY = center.y + randomHeight;

                    try {
                        dimension.spawnParticle('myw:mythril_particle',
                            { x: floatX, y: floatY, z: floatZ });
                    } catch (error) {
                        // Continuar
                    }
                }
            }

            // Duración máxima del ritual activo (30 segundos)
            if (activeTime >= 600 && !ritual.hasRewarded) {
                ritual.hasRewarded = true;
                this.grantRitualReward(ritual);
                system.clearRun(activeInterval);
                this.deactivateRitual(ritualKey);
            }
        }, 1);

        ritual.activeInterval = activeInterval;
    }

    // Otorgar recompensa al completar el ritual
    grantRitualReward(ritual) {
        try {
            const { dimension, center } = ritual;

            // Posición encima del bloque central
            const rewardLocation = {
                x: center.x + 0.5,
                y: center.y + 1.2,
                z: center.z + 0.5
            };

            // Crear recompensa
            this.spawnMythrilItem(dimension, rewardLocation, 'myw:ancient_mythril_relic');

            this.createTransformationEffect(dimension, center);
            world.sendMessage('§b✦ §9Ritual completed §bsuccessfully§9 ✦');

            this.createSuccessExplosion(dimension, center);

        } catch (error) {
            world.sendMessage('§cError en la recompensa del ritual: ' + error.message);
        }
    }

    // Función para spawnear items
    spawnMythrilItem(dimension, location, itemId) {
        try {
            const dropLocation = {
                x: Math.floor(location.x) + 0.5,
                y: Math.floor(location.y) + 0.1,
                z: Math.floor(location.z) + 0.5
            };

            const itemSpawn = dimension.spawnItem(new ItemStack(itemId, 1), dropLocation);
        } catch (error) {
            try {
                // Fallback con comando
                dimension.runCommand(`summon item ${location.x} ${location.y} ${location.z} ~ ~ ~ minecraft:item 1 0 {"Item":{"id":"${itemId}","Count":1}}`);
            } catch (cmdError) {
                try {
                    // Fallback final: dar directamente al primer jugador
                    const players = world.getAllPlayers();
                    if (players.length > 0) {
                        dimension.runCommand(`give "${players[0].name}" ${itemId} 1`);
                    }
                } catch (giveError) {
                    world.sendMessage(`§c[MYTHRIL DEBUG] Fallo total spawneando ${itemId}: ` + giveError.message);
                }
            }
        }
    }

    // Efecto de transformación mejorado
    createTransformationEffect(dimension, center) {
        // Explosión de partículas en espiral ascendente
        for (let i = 0; i < 50; i++) {
            system.runTimeout(() => {
                const angle = i * 0.3;
                const radius = (50 - i) * 0.1;
                const height = i * 0.2;

                for (let j = 0; j < 3; j++) {
                    const offsetAngle = angle + (j * Math.PI * 2 / 3);
                    const particleX = center.x + 0.5 + Math.cos(offsetAngle) * radius;
                    const particleZ = center.z + 0.5 + Math.sin(offsetAngle) * radius;
                    const particleY = center.y + 0.5 + height;

                    try {
                        const particleType = ['myw:mythril_particle',
                            'myw:mythril_particle_serpentine',
                            'myw:mythril_particle_minimalist'][j];
                        dimension.spawnParticle(particleType,
                            { x: particleX, y: particleY, z: particleZ });
                    } catch (error) {
                        // Continuar
                    }
                }
            }, i);
        }
    }

    // Explosión de éxito
    createSuccessExplosion(dimension, center) {
        // Ondas expansivas
        for (let wave = 1; wave <= 5; wave++) {
            system.runTimeout(() => {
                const waveRadius = wave * 1.5;
                const particleCount = wave * 12;

                for (let i = 0; i < particleCount; i++) {
                    const angle = (i / particleCount) * Math.PI * 2;
                    const particleX = center.x + 0.5 + Math.cos(angle) * waveRadius;
                    const particleZ = center.z + 0.5 + Math.sin(angle) * waveRadius;
                    const particleY = center.y + 0.5 + Math.sin(wave * 0.5);

                    try {
                        dimension.spawnParticle('myw:mythril_particle',
                            { x: particleX, y: particleY, z: particleZ });
                    } catch (error) {
                        // Continuar
                    }
                }
            }, wave * 3);
        }

        // Lluvia de partículas
        for (let i = 0; i < 100; i++) {
            system.runTimeout(() => {
                const randomAngle = Math.random() * Math.PI * 2;
                const randomRadius = Math.random() * 3;
                const randomHeight = 5 + Math.random() * 5;

                const particleX = center.x + 0.5 + Math.cos(randomAngle) * randomRadius;
                const particleZ = center.z + 0.5 + Math.sin(randomAngle) * randomRadius;
                const particleY = center.y + randomHeight;

                try {
                    const types = ['myw:mythril_particle',
                        'myw:mythril_particle_serpentine',
                        'myw:mythril_particle_minimalist'];
                    const randomType = types[Math.floor(Math.random() * 3)];
                    dimension.spawnParticle(randomType,
                        { x: particleX, y: particleY, z: particleZ });
                } catch (error) {
                    // Continuar
                }
            }, Math.floor(i / 5));
        }
    }

    // Actualizar rituales activos
    updateActiveRituals() {
        this.activeRituals.forEach((ritual, key) => {
            // Verificar si los bloques siguen en su lugar
            try {
                const centerBlock = ritual.dimension.getBlock(ritual.center);
                if (!centerBlock || centerBlock.typeId !== 'myw:mythril_block') {
                    this.deactivateRitual(key);
                    return;
                }
            } catch (error) {
                this.deactivateRitual(key);
            }
        });
    }

    // Desactivar ritual
    deactivateRitual(ritualKey) {
        const ritual = this.activeRituals.get(ritualKey);
        if (!ritual) return;

        // Limpiar intervalos
        if (ritual.activeInterval) {
            system.clearRun(ritual.activeInterval);
        }

        // Efecto de cierre
        this.createClosingEffect(ritual.dimension, ritual.center);

        // Eliminar ritual activo
        this.activeRituals.delete(ritualKey);

        this.ritualCooldowns.set(ritualKey, Date.now() + 30000);

        world.sendMessage('§9✦ §bMythril Ritual §9completed ✦');
    }

    // Efecto de cierre
    createClosingEffect(dimension, center) {
        // Implosión de partículas
        for (let radius = 5; radius > 0; radius -= 0.5) {
            system.runTimeout(() => {
                const particleCount = Math.floor(radius * 8);

                for (let i = 0; i < particleCount; i++) {
                    const angle = (i / particleCount) * Math.PI * 2;
                    const particleX = center.x + 0.5 + Math.cos(angle) * radius;
                    const particleZ = center.z + 0.5 + Math.sin(angle) * radius;

                    try {
                        dimension.spawnParticle('myw:mythril_particle_minimalist',
                            { x: particleX, y: center.y + 1, z: particleZ });
                    } catch (error) {
                        // Continuar
                    }
                }
            }, Math.floor((5 - radius) * 2));
        }
    }
}

// Exportar la función de inicialización
export function initializeMythrilRituals() {
    const ritualSystem = new MythrilRitualSystem();
    ritualSystem.initialize();

    // Exponer el sistema globalmente para debug
    world.mythrilRitualSystem = ritualSystem;

    return ritualSystem;
}