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

export const AncientRuneSystem = {
    // ==================== SIMPLIFIED CONFIGURATION ====================
    config: {
        detection: {
            maxRange: 10,
            minRuneCount: 5,
            maxRuneCount: 5,
            scanInterval: 20,
        },


        // 6 BASIC RITUALS
        rituals: {
            summon: {
                runeType: 'myw:ancient_mythril_summon_rune',
                name: '§4Summon Ritual',
                cooldown: 120,
                particles: ['myw:mythril_particle']
            },

            tree: {
                runeType: 'myw:ancient_mythril_tree_rune',
                name: '§2Nature Ritual',
                cooldown: 60,
                particles: ['myw:mythril_particle_minimalist']
            },

            ascension: {
                runeType: 'myw:ancient_mythril_ascension_rune',
                name: '§bAscension Ritual',
                cooldown: 180,
                particles: ['myw:mythril_flight_particle']
            },

            pet: {
                runeType: 'myw:ancient_mythril_pet_rune',
                name: '§6Companion Ritual',
                cooldown: 240,
                particles: ['myw:mythril_heal_particle']
            },

            destruction: {
                runeType: 'myw:ancient_mythril_destruction_rune',
                name: '§cDestruction Ritual',
                cooldown: 300,
                particles: ['myw:mythril_particle']
            },

            night: {
                runeType: 'myw:ancient_mythril_night_rune',
                name: '§8Night Ritual',
                cooldown: 150,
                particles: ['myw:mythril_particle_minimalist']
            }
        }
    },

    // ==================== SYSTEM STATE ====================
    state: {
        activeRituals: new Map(),
        playerCooldowns: new Map(),
        detectedPatterns: new Map(),
        scanTimer: 0
    },

    // ==================== PATTERN DETECTION ====================
    scanForRunes(dimension, center, range = 10) {
        const runes = [];

        for (let x = center.x - range; x <= center.x + range; x++) {
            for (let z = center.z - range; z <= center.z + range; z++) {
                for (let y = center.y - 2; y <= center.y + 2; y++) {
                    try {
                        const block = dimension.getBlock({ x, y, z });
                        if (block && this.isRuneBlock(block.typeId)) {
                            runes.push({
                                position: { x, y, z },
                                runeType: block.typeId,
                                block: block
                            });
                        }
                    } catch (error) {
                        // Block out of range or invalid
                    }
                }
            }
        }

        return runes;
    },

    isRuneBlock(blockTypeId) {
        return Object.values(this.config.rituals).some(ritual =>
            ritual.runeType === blockTypeId
        );
    },

    detectPattern(runes) {
        // Only detect exactly 5 runes of same type
        if (runes.length !== 5) {
            return null;
        }
        
        // Check all runes are same type
        const runeType = runes[0].runeType;
        const allSameType = runes.every(r => r.runeType === runeType);
        
        if (!allSameType) {
            return null;
        }
        
        return {
            type: 'star',
            runes: runes,
            runeType: runeType,
            confidence: 1.0
        };
    },


    detectLinePattern(runes) {
        if (runes.length < 3) return null;

        const sortedByX = [...runes].sort((a, b) => a.position.x - b.position.x);
        const sortedByZ = [...runes].sort((a, b) => a.position.z - b.position.z);

        if (this.checkLinearAlignment(sortedByX, 'x')) {
            const centerY = runes.reduce((sum, r) => sum + r.position.y, 0) / runes.length;
            return {
                type: 'line',
                runes: sortedByX,
                direction: 'x',
                center: {
                    x: sortedByX[Math.floor(sortedByX.length / 2)].position.x,
                    y: Math.round(centerY * 100) / 100,
                    z: sortedByX[0].position.z
                },
                confidence: 0.8
            };
        }

        if (this.checkLinearAlignment(sortedByZ, 'z')) {
            const centerY = runes.reduce((sum, r) => sum + r.position.y, 0) / runes.length;
            return {
                type: 'line',
                runes: sortedByZ,
                direction: 'z',
                center: {
                    x: sortedByZ[0].position.x,
                    y: Math.round(centerY * 100) / 100,
                    z: sortedByZ[Math.floor(sortedByZ.length / 2)].position.z
                },
                confidence: 0.8
            };
        }

        return null;
    },

    checkLinearAlignment(sortedRunes, axis) {
        const tolerance = 1;
        const oppositeAxis = axis === 'x' ? 'z' : 'x';
        const firstPos = sortedRunes[0].position[oppositeAxis];
        return sortedRunes.every(rune =>
            Math.abs(rune.position[oppositeAxis] - firstPos) <= tolerance
        );
    },

    detectCrossPattern(runes) {
        if (runes.length !== 5) return null;

        for (let i = 0; i < runes.length; i++) {
            const centerRune = runes[i];
            const others = runes.filter((_, index) => index !== i);

            const arms = {
                north: others.find(r => r.position.x === centerRune.position.x && r.position.z === centerRune.position.z - 2),
                south: others.find(r => r.position.x === centerRune.position.x && r.position.z === centerRune.position.z + 2),
                east: others.find(r => r.position.x === centerRune.position.x + 2 && r.position.z === centerRune.position.z),
                west: others.find(r => r.position.x === centerRune.position.x - 2 && r.position.z === centerRune.position.z)
            };

            if (arms.north && arms.south && arms.east && arms.west) {
                return {
                    type: 'cross',
                    runes: runes,
                    center: {
                        x: centerRune.position.x,
                        y: centerRune.position.y,
                        z: centerRune.position.z
                    },
                    arms: arms,
                    confidence: 0.95
                };
            }
        }

        return null;
    },

    detectStarPattern(runes) {
        if (runes.length !== 7) return null;

        for (let i = 0; i < runes.length; i++) {
            const centerRune = runes[i];
            const others = runes.filter((_, index) => index !== i);

            const distances = others.map(rune =>
                Math.sqrt(
                    Math.pow(rune.position.x - centerRune.position.x, 2) +
                    Math.pow(rune.position.z - centerRune.position.z, 2)
                )
            );

            const avgDistance = distances.reduce((sum, d) => sum + d, 0) / distances.length;
            const tolerance = 0.5;

            if (distances.every(d => Math.abs(d - avgDistance) <= tolerance)) {
                return {
                    type: 'star',
                    runes: runes,
                    center: {
                        x: centerRune.position.x,
                        y: centerRune.position.y,
                        z: centerRune.position.z
                    },
                    points: others,
                    confidence: 0.9
                };
            }
        }

        return null;
    },

    // ==================== SIMPLIFIED RITUAL SYSTEM ====================
    async startRitual(player, pattern, primaryRune) {
        try {
            const ritualType = this.getRitualType(primaryRune.runeType);
            if (!ritualType) {
                this.sendRuneMessage(player, `§cUnknown rune: ${primaryRune.runeType}`);
                return false;
            }

            if (this.isPlayerOnCooldown(player, ritualType.name)) {
                const remaining = this.getRemainingCooldown(player, ritualType.name);
                this.sendRuneMessage(player, `§cCooldown: ${Math.ceil(remaining / 20)}s`);
                return false;
            }

            this.setPlayerCooldown(player, ritualType.name, ritualType.cooldown * 20);

            this.state.activeRituals.set(player.id, {
                type: ritualType,
                pattern: pattern,
                startTime: system.currentTick,
                phase: 0
            });

            this.executeRitualSimple(player, ritualType, pattern);

            return true;

        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message || 'Unknown error'}`);
            this.state.activeRituals.delete(player.id);
            console.error('[RUNE SYSTEM ERROR]', error);
            return false;
        }
    },

    getRitualType(runeTypeId) {
        const ritual = Object.values(this.config.rituals).find(ritual =>
            ritual.runeType === runeTypeId
        );
        console.log(`[RUNE SYSTEM] Looking for ritual with runeType: ${runeTypeId}, found: ${ritual?.name || 'None'}`);
        return ritual;
    },

    // Simplified function to determine ritual based on rune type
    determineRitualType(runes) {
        if (runes.length !== 5) {
            return null;
        }
        
        // All runes must be same type
        const runeType = runes[0].runeType;
        const allSameType = runes.every(r => r.runeType === runeType);
        
        if (!allSameType) {
            return null;
        }
        
        const ritualType = this.getRitualType(runeType);
        console.log(`[RUNE SYSTEM] Detected ritual type: ${ritualType?.name || 'Unknown'} for rune: ${runeType}`);
        return ritualType;
    },

    // Simplified material check (always passes for testing)
    checkMaterials(player, materials) {
        return true; // Simplified for testing
    },

    // ==================== SIMPLIFIED RITUAL EXECUTION ====================
    executeRitualSimple(player, ritualType, pattern) {
        try {
            console.log(`[RUNE SYSTEM] Executing ritual: ${ritualType.name} with runeType: ${ritualType.runeType}`);
            
            const center = pattern.center || pattern.runes[0].position;
            const dimension = player.dimension;

            console.log(`[RUNE SYSTEM] Center position:`, center);

            // Preparation effects
            this.createRitualPreparation(dimension, center, ritualType);

            system.runTimeout(() => {
                try {
                    // Execute specific ritual
                    console.log(`[RUNE SYSTEM] Switching to ritual type: ${ritualType.runeType}`);
                    switch (ritualType.runeType) {
                        case 'myw:ancient_mythril_summon_rune':
                            this.executeSummonRitual(player, dimension, center, pattern);
                            break;

                        case 'myw:ancient_mythril_tree_rune':
                            console.log(`[RUNE SYSTEM] Executing Nature Ritual`);
                            this.executeNatureRitual(player, dimension, center, pattern);
                            break;

                        case 'myw:ancient_mythril_ascension_rune':
                            console.log(`[RUNE SYSTEM] Executing Ascension Ritual`);
                            this.executeAscensionRitual(player, dimension, center, pattern);
                            break;

                        case 'myw:ancient_mythril_pet_rune':
                            this.executeCompanionRitual(player, dimension, center, pattern);
                            break;

                        case 'myw:ancient_mythril_destruction_rune':
                            console.log(`[RUNE SYSTEM] Executing Destruction Ritual`);
                            this.executeDestructionRitual(player, dimension, center, pattern);
                            break;

                        case 'myw:ancient_mythril_night_rune':
                            console.log(`[RUNE SYSTEM] Executing Night Ritual`);
                            this.executeNightRitual(player, dimension, center, pattern);
                            break;

                        default:
                            this.sendRuneMessage(player, `§c⚠️ Unknown ritual type: ${ritualType.runeType}`);
                    }

                    system.runTimeout(() => {
                        this.createRitualCompletion(dimension, center, ritualType);
                        this.breakRandomRunes(dimension, pattern.runes);
                        this.state.activeRituals.delete(player.id);
                    }, 40);

                } catch (error) {
                    this.sendRuneMessage(player, `§cError: ${error.message}`);
                    this.state.activeRituals.delete(player.id);
                }
            }, 20);

        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
            this.state.activeRituals.delete(player.id);
        }
    },

    // ==================== SIMPLIFIED RITUALS ====================
    
    // Preparation effects
    createRitualPreparation(dimension, center, ritualType) {
        try {
            for (let i = 0; i < 3; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_particle', {
                        x: center.x + 0.5,
                        y: center.y + 1,
                        z: center.z + 0.5
                    });
                }, i * 5);
            }
        } catch (error) {
            console.log('Preparation error:', error.message);
        }
    },

    // Completion effects
    createRitualCompletion(dimension, center, ritualType) {
        try {
            for (let i = 0; i < 5; i++) {
                system.runTimeout(() => {
                    dimension.spawnParticle('myw:mythril_heal_particle', {
                        x: center.x + (Math.random() - 0.5) * 2,
                        y: center.y + 1,
                        z: center.z + (Math.random() - 0.5) * 2
                    });
                }, i * 2);
            }
        } catch (error) {
            console.log('Completion error:', error.message);
        }
    },

    // Break 2-3 random runes after ritual completion
    breakRandomRunes(dimension, runes) {
        try {
            const runesToBreak = Math.floor(Math.random() * 2) + 2; // 2 or 3 runes
            const shuffledRunes = [...runes].sort(() => Math.random() - 0.5);
            
            for (let i = 0; i < runesToBreak && i < shuffledRunes.length; i++) {
                const rune = shuffledRunes[i];
                try {
                    const block = dimension.getBlock(rune.position);
                    if (block && this.isRuneBlock(block.typeId)) {
                        block.setType('minecraft:air');
                    }
                } catch (error) {
                    // Block might not exist anymore
                }
            }
        } catch (error) {
            console.log('Break runes error:', error.message);
        }
    },

    // Summon ritual
    executeSummonRitual(player, dimension, center, pattern) {
        try {
            
            const playerPos = player.location;
            const spawnPos = {
                x: playerPos.x + 1,
                y: playerPos.y + 1,
                z: playerPos.z + 1
            };
            
            const creature = dimension.spawnEntity('myw:mythril_blokkit', spawnPos);
            if (creature) {
            } else {
                this.sendRuneMessage(player, '§cSummon failed');
            }
        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Protection ritual
    executeProtectionRitual(player, dimension, center, pattern) {
        try {

            player.addEffect('resistance', 1200, {
                amplifier: 1,
                showParticles: true
            });

            player.addEffect('absorption', 1200, {
                amplifier: 1,
                showParticles: true
            });

        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Nature ritual - SPECTACULAR: Generates terrain and trees in 20 blocks radius
    executeNatureRitual(player, dimension, center, pattern) {
        try {
            this.sendRuneMessage(player, '§2🌳 EPIC NATURE RITUAL! Transforming terrain...');
            
            const centerPos = center.position || center;
            const radius = 20;
            
            // Phase 1: Transform base terrain
            this.transformTerrainInRadius(dimension, centerPos, radius, player);
            
            // Phase 2: Generate mystical trees
            system.runTimeout(() => {
                this.generateMysticalTrees(dimension, centerPos, radius, player);
            }, 40);
            
            // Phase 3: Final effects
            system.runTimeout(() => {
                this.createNatureFinale(dimension, centerPos, player);
            }, 200);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Transform terrain in 20 block radius
    transformTerrainInRadius(dimension, center, radius, player) {
        try {
            const conversions = {
                'minecraft:grass_block': 'myw:ancient_mythril_grass',
                'minecraft:dirt': 'myw:ancient_mythril_dirt',
                'minecraft:coarse_dirt': 'myw:ancient_mythril_dirt',
                'minecraft:podzol': 'myw:ancient_mythril_dirt',
                'minecraft:rooted_dirt': 'myw:ancient_mythril_dirt',
                'minecraft:mycelium': 'myw:ancient_mythril_grass',
                'minecraft:crimson_nylium': 'myw:ancient_mythril_grass',
                'minecraft:warped_nylium': 'myw:ancient_mythril_grass',
                'minecraft:stone': 'myw:ancient_mythril_bricks',
                'minecraft:cobblestone': 'myw:ancient_mythril_bricks_2',
                'minecraft:deepslate': 'myw:ancient_mythril_bricks'
            };

            let blocksTransformed = 0;
            
            for (let x = -radius; x <= radius; x++) {
                for (let z = -radius; z <= radius; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    if (distance <= radius) {
                        system.runTimeout(() => {
                            // Transform blocks in multiple levels
                            for (let y = -3; y <= 2; y++) {
                                const blockPos = {
                                    x: Math.floor(center.x + x),
                                    y: Math.floor(center.y + y),
                                    z: Math.floor(center.z + z)
                                };
                                
                                try {
                                    const block = dimension.getBlock(blockPos);
                                    if (block && conversions[block.typeId]) {
                                        block.setType(conversions[block.typeId]);
                                        blocksTransformed++;
                                        
                                        // Transformation particles
                                        if (Math.random() < 0.1) {
                                            dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                                x: blockPos.x + 0.5,
                                                y: blockPos.y + 1,
                                                z: blockPos.z + 0.5
                                            });
                                        }
                                    }
                                } catch (error) {
                                    // Error transforming block
                                }
                            }
                        }, Math.floor(distance * 2));
                    }
                }
            }
            
            this.sendRuneMessage(player, `§2✨ Terrain transformed: ${blocksTransformed} blocks`);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError transforming terrain: ${error.message}`);
        }
    },

    // Generate spectacular mystical trees
    generateMysticalTrees(dimension, center, radius, player) {
        try {
            const trunkBlock = 'myw:ancient_mythril_log';
            const leavesBlock = 'myw:ancient_mythril_leaves';
            
            // Distributed tree positions
            const treePositions = [
                { x: 8, z: 8, height: 12 },
                { x: -12, z: 10, height: 15 },
                { x: 15, z: -8, height: 10 },
                { x: -18, z: -12, height: 13 },
                { x: 0, z: 20, height: 16 },
                { x: -20, z: 5, height: 11 },
                { x: 18, z: -15, height: 9 },
                { x: 10, z: -20, height: 14 },
                { x: -8, z: 18, height: 12 },
                { x: 5, z: -5, height: 8 },
                { x: -15, z: -8, height: 13 },
                { x: 12, z: 15, height: 11 },
                { x: -5, z: -18, height: 10 },
                { x: 20, z: 3, height: 14 },
                { x: -3, z: 12, height: 9 }
            ];

            treePositions.forEach((tree, treeIndex) => {
                system.runTimeout(() => {
                    this.createMysticalTree(dimension, center, tree, trunkBlock, leavesBlock, player);
                }, treeIndex * 15);
            });
            
            this.sendRuneMessage(player, `§2🌲 Generating ${treePositions.length} mystical trees...`);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError generating trees: ${error.message}`);
        }
    },

    // Create an individual mystical tree
    createMysticalTree(dimension, center, treeData, trunkBlock, leavesBlock, player) {
        try {
            const treePos = {
                x: Math.floor(center.x + treeData.x),
                y: Math.floor(center.y),
                z: Math.floor(center.z + treeData.z)
            };
            
            // Find the surface
            let surfaceY = treePos.y;
            for (let y = treePos.y; y >= treePos.y - 10; y--) {
                const block = dimension.getBlock({ x: treePos.x, y: y, z: treePos.z });
                if (block && !block.typeId.includes('air')) {
                    surfaceY = y + 1;
                    break;
                }
            }
            
            // Create trunk
            for (let height = 0; height < treeData.height; height++) {
                system.runTimeout(() => {
                    const trunkPos = {
                        x: treePos.x,
                        y: surfaceY + height,
                        z: treePos.z
                    };
                    
                    try {
                        const block = dimension.getBlock(trunkPos);
                        if (block && block.typeId === 'minecraft:air') {
                            block.setType(trunkBlock);
                            
                            // Particles on trunk
                            dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                x: trunkPos.x + 0.5,
                                y: trunkPos.y + 0.5,
                                z: trunkPos.z + 0.5
                            });
                        }
                    } catch (error) {
                        // Error creating trunk
                    }
                }, height * 3);
            }
            
            // Create leaves in layers
            system.runTimeout(() => {
                this.createTreeLeaves(dimension, treePos, surfaceY, treeData.height, leavesBlock);
            }, treeData.height * 3 + 20);
            
        } catch (error) {
            // Error creating tree
        }
    },

    // Create tree leaves
    createTreeLeaves(dimension, treePos, surfaceY, height, leavesBlock) {
        try {
            const leafRadius = Math.min(4, Math.floor(height / 3));
            const topY = surfaceY + height;
            
            for (let y = topY - leafRadius; y <= topY + 2; y++) {
                for (let x = -leafRadius; x <= leafRadius; x++) {
                    for (let z = -leafRadius; z <= leafRadius; z++) {
                        const distance = Math.sqrt(x * x + z * z);
                        if (distance <= leafRadius && Math.random() < 0.7) {
                            const leafPos = {
                                x: treePos.x + x,
                                y: y,
                                z: treePos.z + z
                            };
                            
                            try {
                                const block = dimension.getBlock(leafPos);
                                if (block && block.typeId === 'minecraft:air') {
                                    block.setType(leavesBlock);
                                    
                                    // Particles on leaves
                                    if (Math.random() < 0.3) {
                                        dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                            x: leafPos.x + 0.5,
                                            y: leafPos.y + 0.5,
                                            z: leafPos.z + 0.5
                                        });
                                    }
                                }
                            } catch (error) {
                                // Error creating leaf
                            }
                        }
                    }
                }
            }
        } catch (error) {
            // Error creating leaves
        }
    },

    // Final effects of nature ritual
    createNatureFinale(dimension, center, player) {
        try {
            // Green particle explosion
            for (let i = 0; i < 50; i++) {
                system.runTimeout(() => {
                    const angle = (i / 50) * Math.PI * 2;
                    const radius = 15 + Math.random() * 10;
                    const particlePos = {
                        x: center.x + Math.cos(angle) * radius,
                        y: center.y + 5 + Math.random() * 10,
                        z: center.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_particle_minimalist', particlePos);
                }, i * 2);
            }
            
            this.sendRuneMessage(player, '§2🌿 NATURE RITUAL COMPLETED! The mystical forest has bloomed.');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError in final effects: ${error.message}`);
        }
    },

    // Elemental ritual
    executeElementalRitual(player, dimension, center, pattern) {
        try {

            const effects = [
                { effect: 'regeneration', duration: 1200, amplifier: 2 },
                { effect: 'strength', duration: 1200, amplifier: 2 },
                { effect: 'speed', duration: 1200, amplifier: 1 },
                { effect: 'fire_resistance', duration: 1200, amplifier: 0 }
            ];

            effects.forEach(e => {
                player.addEffect(e.effect, e.duration, {
                    amplifier: e.amplifier,
                    showParticles: true
                });
            });

        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Ascension ritual - SPECTACULAR: Mega spiral mythril tower with impulses
    executeAscensionRitual(player, dimension, center, pattern) {
        try {
            this.sendRuneMessage(player, '§b🏗️ EPIC ASCENSION RITUAL! Building mystical tower...');
            
            const centerPos = center.position || center;
            
            // Phase 1: Preparation and initial effects
            this.prepareAscensionRitual(dimension, centerPos, player);
            
            // Phase 2: Build mega spiral tower
            system.runTimeout(() => {
                this.buildMegaSpiralTower(dimension, centerPos, player);
            }, 40);
            
            // Phase 3: Apply impulses to player
            system.runTimeout(() => {
                this.applyAscensionImpulses(player, centerPos);
            }, 100);
            
            // Phase 4: Final effects
            system.runTimeout(() => {
                this.createAscensionFinale(dimension, centerPos, player);
            }, 300);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Prepare ascension ritual
    prepareAscensionRitual(dimension, center, player) {
        try {
            // Spiral preparation particles
            for (let i = 0; i < 50; i++) {
                system.runTimeout(() => {
                    const angle = (i / 50) * Math.PI * 2;
                    const radius = 8 + Math.sin(angle * 5) * 3;
                    const height = i * 0.3;
                    
                    const particlePos = {
                        x: center.x + Math.cos(angle) * radius,
                        y: center.y + height,
                        z: center.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_flight_particle', particlePos);
                }, i * 2);
            }
            
            this.sendRuneMessage(player, '§b✨ Ascension energy accumulating...');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError preparing ascension: ${error.message}`);
        }
    },

    // Build mega spiral tower
    buildMegaSpiralTower(dimension, center, player) {
        try {
            const towerHeight = 50;
            const baseRadius = 8;
            const spiralTurns = 3;
            
            this.sendRuneMessage(player, '§b🏗️ Building Mythril spiral tower...');
            
            // Build tower level by level
            for (let level = 0; level < towerHeight; level++) {
                system.runTimeout(() => {
                    this.buildTowerLevel(dimension, center, level, towerHeight, baseRadius, spiralTurns, player);
                }, level * 5);
            }
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError building tower: ${error.message}`);
        }
    },

    // Build a tower level
    buildTowerLevel(dimension, center, level, towerHeight, baseRadius, spiralTurns, player) {
        try {
            const levelY = center.y + level;
            const progress = level / towerHeight;
            
            // Radius that reduces upward
            const currentRadius = baseRadius * (1 - progress * 0.3);
            
            // Create spiral structure
            for (let angle = 0; angle < 360; angle += 10) {
                const spiralOffset = (angle / 360) * spiralTurns * Math.PI * 2;
                const radius = currentRadius + Math.sin(spiralOffset) * 2;
                
                const x = center.x + Math.cos(angle * Math.PI / 180) * radius;
                const z = center.z + Math.sin(angle * Math.PI / 180) * radius;
                
                const blockPos = {
                    x: Math.floor(x),
                    y: Math.floor(levelY),
                    z: Math.floor(z)
                };
                
                try {
                    const block = dimension.getBlock(blockPos);
                    if (block && block.typeId === 'minecraft:air') {
                        // Use different blocks according to level
                        let blockType = 'myw:ancient_mythril_bricks';
                        if (level % 10 === 0) {
                            blockType = 'myw:ancient_mythril_temple_block';
                        } else if (level % 5 === 0) {
                            blockType = 'myw:ancient_mythril_bricks_2';
                        }
                        
                        block.setType(blockType);
                        
                        // Construction particles
                        if (Math.random() < 0.2) {
                            dimension.spawnParticle('myw:mythril_flight_particle', {
                                x: blockPos.x + 0.5,
                                y: blockPos.y + 0.5,
                                z: blockPos.z + 0.5
                            });
                        }
                    }
                } catch (error) {
                    // Error placing block
                }
            }
            
            // Create special decorations every 10 levels
            if (level % 10 === 0 && level > 0) {
                this.createTowerDecoration(dimension, center, level, currentRadius);
            }
            
        } catch (error) {
            // Error building level
        }
    },

    // Create tower decorations
    createTowerDecoration(dimension, center, level, radius) {
        try {
            const levelY = center.y + level;
            
            // Create spiral balconies
            for (let angle = 0; angle < 360; angle += 90) {
                const x = center.x + Math.cos(angle * Math.PI / 180) * (radius + 2);
                const z = center.z + Math.sin(angle * Math.PI / 180) * (radius + 2);
                
                const balconyPos = {
                    x: Math.floor(x),
                    y: Math.floor(levelY),
                    z: Math.floor(z)
                };
                
                try {
                    const block = dimension.getBlock(balconyPos);
                    if (block && block.typeId === 'minecraft:air') {
                        block.setType('myw:ancient_mythril_temple_rune');
                    }
                } catch (error) {
                    // Error creating balcony
                }
            }
            
        } catch (error) {
            // Error creating decoration
        }
    },

    // Apply ascension impulses to player
    applyAscensionImpulses(player, center) {
        try {
            this.sendRuneMessage(player, '§b🚀 Applying ascension impulses...');
            
            // Flight and levitation effects
            player.addEffect('levitation', 600, {
                amplifier: 0,
                showParticles: true
            });
            
            player.addEffect('slow_falling', 1200, {
                amplifier: 0,
                showParticles: true
            });
            
            player.addEffect('jump_boost', 1200, {
                amplifier: 3,
                showParticles: true
            });
            
            // Periodic upward impulses
            for (let i = 0; i < 20; i++) {
                system.runTimeout(() => {
                    try {
                        // Apply upward impulse using teleportation
                        const currentPos = player.location;
                        player.teleport({
                            x: currentPos.x,
                            y: currentPos.y + 2,
                            z: currentPos.z
                        }, {
                            dimension: player.dimension,
                            rotation: player.getRotation()
                        });
                        
                        // Impulse particles
                        const playerPos = player.location;
                        for (let j = 0; j < 5; j++) {
                            player.dimension.spawnParticle('myw:mythril_flight_particle', {
                                x: playerPos.x + (Math.random() - 0.5) * 2,
                                y: playerPos.y,
                                z: playerPos.z + (Math.random() - 0.5) * 2
                            });
                        }
                    } catch (error) {
                        // Error applying impulse
                    }
                }, i * 30);
            }
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError applying impulses: ${error.message}`);
        }
    },

    // Final ascension effects
    createAscensionFinale(dimension, center, player) {
        try {
            // Particle explosion from tower top
            const towerTop = center.y + 50;
            
            for (let i = 0; i < 80; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const radius = Math.random() * 20;
                    const height = Math.random() * 30;
                    
                    const particlePos = {
                        x: center.x + Math.cos(angle) * radius,
                        y: towerTop + height,
                        z: center.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_flight_particle', particlePos);
                }, i * 2);
            }
            
            // Final effects on player
            player.addEffect('resistance', 1800, {
                amplifier: 1,
                showParticles: true
            });
            
            player.addEffect('regeneration', 1200, {
                amplifier: 1,
                showParticles: true
            });
            
            this.sendRuneMessage(player, '§b🏗️ ASCENSION RITUAL COMPLETED! The Mythril spiral tower rises majestically.');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError in final effects: ${error.message}`);
        }
    },

    // Companion ritual
    executeCompanionRitual(player, dimension, center, pattern) {
        try {
            this.sendRuneMessage(player, '§d🐾 MYSTICAL COMPANION RITUAL! Summoning loyal creatures...');
            
            const centerPos = center.position || center;
            
            // Spawn both types of blokkit
            const blokkitTypes = [
                { type: 'myw:mythril_blokkit', name: 'Mythril Blokkit' },
                { type: 'myw:raw_mythril_blokkit', name: 'Raw Mythril Blokkit' }
            ];
            
            blokkitTypes.forEach((blokkit, index) => {
                system.runTimeout(() => {
                    const spawnPos = {
                        x: centerPos.x + (index === 0 ? 2 : -2),
                        y: centerPos.y + 1,
                        z: centerPos.z + (index === 0 ? 2 : -2)
                    };
                    
                    try {
                        const companion = dimension.spawnEntity(blokkit.type, spawnPos);
                        if (companion) {
                            this.sendRuneMessage(player, `§d🐾 ${blokkit.name} summoned!`);
                            
                            // Effects for each blokkit
                            for (let i = 0; i < 15; i++) {
                                system.runTimeout(() => {
                                    dimension.spawnParticle('myw:mythril_particle', {
                                        x: spawnPos.x + (Math.random() - 0.5) * 3,
                                        y: spawnPos.y + Math.random() * 2,
                                        z: spawnPos.z + (Math.random() - 0.5) * 3
                                    });
                                }, i * 2);
                            }
                            
                            // Special effects for each type
                            if (blokkit.type === 'myw:mythril_blokkit') {
                                // Normal blokkit - healing particles
                                for (let h = 0; h < 10; h++) {
                                    system.runTimeout(() => {
                                        dimension.spawnParticle('myw:mythril_heal_particle', {
                                            x: spawnPos.x + (Math.random() - 0.5) * 2,
                                            y: spawnPos.y + h * 0.3,
                                            z: spawnPos.z + (Math.random() - 0.5) * 2
                                        });
                                    }, h * 3);
                                }
                            } else {
                                // Raw blokkit - flight particles
                                for (let f = 0; f < 10; f++) {
                                    system.runTimeout(() => {
                                        dimension.spawnParticle('myw:mythril_flight_particle', {
                                            x: spawnPos.x + (Math.random() - 0.5) * 2,
                                            y: spawnPos.y + f * 0.3,
                                            z: spawnPos.z + (Math.random() - 0.5) * 2
                                        });
                                    }, f * 3);
                                }
                            }
                        }
                    } catch (error) {
                        this.sendRuneMessage(player, `§cError summoning ${blokkit.name}`);
                    }
                }, index * 20);
            });
            
            // Final message
            system.runTimeout(() => {
                this.sendRuneMessage(player, '§d🐾 Both Mythril Blokkit companions are ready to serve!');
            }, 50);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Destruction ritual - SPECTACULAR: Massive destructive expansion wave
    executeDestructionRitual(player, dimension, center, pattern) {
        try {
            this.sendRuneMessage(player, '§c💥 APOCALYPTIC DESTRUCTION RITUAL! Preparing devastation...');
            
            const centerPos = center.position || center;
            
            // Phase 1: Preparation - Charging particles
            this.createDestructionChargeUp(dimension, centerPos, player);
            
            // Phase 2: Destructive expansion wave
            system.runTimeout(() => {
                this.executeDestructionWave(dimension, centerPos, player);
            }, 60);
            
            // Phase 3: Final effects
            system.runTimeout(() => {
                this.createDestructionFinale(dimension, centerPos, player);
            }, 200);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Create charging effects for destruction
    createDestructionChargeUp(dimension, center, player) {
        try {
            // Spiral charging particles
            for (let i = 0; i < 30; i++) {
                system.runTimeout(() => {
                    const angle = (i / 30) * Math.PI * 2;
                    const radius = 5 + (i * 0.5);
                    const height = 2 + Math.sin(angle * 3) * 2;
                    
                    const particlePos = {
                        x: center.x + Math.cos(angle) * radius,
                        y: center.y + height,
                        z: center.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_particle', particlePos);
                }, i * 2);
            }
            
            this.sendRuneMessage(player, '§c⚡ Destructive energy accumulating...');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError in charging: ${error.message}`);
        }
    },

    // Execute destructive expansion wave
    executeDestructionWave(dimension, center, player) {
        try {
            const maxRadius = 25;
            const waveCount = 5;
            
            this.sendRuneMessage(player, '§c💀 DESTRUCTION IN PROGRESS!');
            
            // Multiple expansion waves
            for (let wave = 0; wave < waveCount; wave++) {
                system.runTimeout(() => {
                    this.createDestructionRing(dimension, center, wave, maxRadius, player);
                }, wave * 15);
            }
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError in destructive wave: ${error.message}`);
        }
    },

    // Create destruction ring
    createDestructionRing(dimension, center, waveIndex, maxRadius, player) {
        try {
            const waveRadius = (maxRadius / 5) * (waveIndex + 1);
            const destructionIntensity = 0.8 - (waveIndex * 0.1); // Less intense in later waves
            
            for (let angle = 0; angle < 360; angle += 5) {
                system.runTimeout(() => {
                    const radian = (angle * Math.PI) / 180;
                    const x = center.x + Math.cos(radian) * waveRadius;
                    const z = center.z + Math.sin(radian) * waveRadius;
                    
                    // Destroy blocks at multiple heights
                    for (let y = -5; y <= 10; y++) {
                        const blockPos = {
                            x: Math.floor(x),
                            y: Math.floor(center.y + y),
                            z: Math.floor(z)
                        };
                        
                        try {
                            const block = dimension.getBlock(blockPos);
                            if (block && this.canDestroyBlock(block.typeId)) {
                                if (Math.random() < destructionIntensity) {
                                    block.setType('minecraft:air');
                                    
                                    // Mythril particles in destruction
                                    if (Math.random() < 0.3) {
                                        dimension.spawnParticle('myw:mythril_particle', {
                                            x: blockPos.x + 0.5,
                                            y: blockPos.y + 0.5,
                                            z: blockPos.z + 0.5
                                        });
                                    }
                                }
                            }
                        } catch (error) {
                            // Error destroying block
                        }
                    }
                    
                    // Damage entities in radius
                    this.damageEntitiesInRadius(dimension, { x, y: center.y, z }, 3, player);
                    
                }, Math.floor(angle / 5) * 2);
            }
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError in destruction ring: ${error.message}`);
        }
    },

    // Check if a block can be destroyed
    canDestroyBlock(blockType) {
        const indestructibleBlocks = [
            'minecraft:bedrock',
            'minecraft:barrier',
            'minecraft:command_block',
            'minecraft:structure_block',
            'minecraft:jigsaw',
            'minecraft:end_portal_frame',
            'minecraft:end_portal',
            'minecraft:nether_portal'
        ];
        
        return !indestructibleBlocks.some(indestructible => blockType.includes(indestructible));
    },

    // Damage entities in a radius
    damageEntitiesInRadius(dimension, center, radius, player) {
        try {
            const entities = dimension.getEntities({
                location: center,
                maxDistance: radius,
                excludeFamilies: ['player']
            });
            
            entities.forEach(entity => {
                try {
                    if (entity.hasComponent('minecraft:health')) {
                        entity.applyDamage(8, { cause: 'magic' });
                        
                        // Damage particles
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: entity.location.x,
                            y: entity.location.y + 1,
                            z: entity.location.z
                        });
                    }
                } catch (error) {
                    // Error damaging entity
                }
            });
            
        } catch (error) {
            // Error getting entities
        }
    },

    // Final destruction effects
    createDestructionFinale(dimension, center, player) {
        try {
            // Final particle explosion
            for (let i = 0; i < 100; i++) {
                system.runTimeout(() => {
                    const angle = Math.random() * Math.PI * 2;
                    const radius = Math.random() * 30;
                    const height = Math.random() * 20 - 5;
                    
                    const particlePos = {
                        x: center.x + Math.cos(angle) * radius,
                        y: center.y + height,
                        z: center.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_particle', particlePos);
                }, i * 3);
            }
            
            // Effects on player
            player.addEffect('strength', 1200, {
                amplifier: 2,
                showParticles: true
            });
            
            player.addEffect('resistance', 600, {
                amplifier: 1,
                showParticles: true
            });
            
            this.sendRuneMessage(player, '§c💀 DESTRUCTION COMPLETED! The area has been devastated.');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError in final effects: ${error.message}`);
        }
    },

    // Night ritual - SPECTACULAR: Night vision and mythril owl spawn
    executeNightRitual(player, dimension, center, pattern) {
        try {
            this.sendRuneMessage(player, '§8🌙 MYSTICAL NIGHT RITUAL! Invoking night powers...');
            
            const centerPos = center.position || center;
            
            // Phase 1: Create night environment
            this.createNightEnvironment(dimension, centerPos, player);
            
            // Phase 2: Apply enhanced night vision
            system.runTimeout(() => {
                this.applyEnhancedNightVision(player);
            }, 20);
            
            // Phase 3: Spawn mythril owl
            system.runTimeout(() => {
                this.spawnMythrilOwl(dimension, centerPos, player);
            }, 60);
            
            // Phase 4: Final effects
            system.runTimeout(() => {
                this.createNightFinale(dimension, centerPos, player);
            }, 120);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError: ${error.message}`);
        }
    },

    // Create night environment
    createNightEnvironment(dimension, center, player) {
        try {
            // Create mystical darkness in a radius
            const radius = 15;
            
            for (let x = -radius; x <= radius; x++) {
                for (let z = -radius; z <= radius; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    if (distance <= radius) {
                        system.runTimeout(() => {
                            // Darkness particles
                            for (let y = 0; y <= 10; y++) {
                                if (Math.random() < 0.1) {
                                    const particlePos = {
                                        x: center.x + x + Math.random(),
                                        y: center.y + y,
                                        z: center.z + z + Math.random()
                                    };
                                    
                                    dimension.spawnParticle('myw:mythril_particle_minimalist', particlePos);
                                }
                            }
                        }, Math.floor(distance * 2));
                    }
                }
            }
            
            this.sendRuneMessage(player, '§8✨ Mystical darkness enveloping the area...');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError creating night environment: ${error.message}`);
        }
    },

    // Apply enhanced night vision
    applyEnhancedNightVision(player) {
        try {
            // Long duration night vision
            player.addEffect('night_vision', 3600, { // 3 minutes
                amplifier: 0,
                showParticles: false
            });
            
            // Additional night effects
            player.addEffect('speed', 1800, {
                amplifier: 1,
                showParticles: true
            });
            
            player.addEffect('jump_boost', 1800, {
                amplifier: 1,
                showParticles: true
            });
            
            this.sendRuneMessage(player, '§8👁 Enhanced night vision activated - Duration: 3 minutes');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError applying night vision: ${error.message}`);
        }
    },

    // Spawn mythril owl
    spawnMythrilOwl(dimension, center, player) {
        try {
            // Positions to spawn multiple owls
            const owlPositions = [
                { x: 5, y: 3, z: 5 },
                { x: -8, y: 4, z: 3 },
                { x: 2, y: 5, z: -6 },
                { x: -3, y: 2, z: -4 }
            ];
            
            owlPositions.forEach((pos, index) => {
                system.runTimeout(() => {
                    const spawnPos = {
                        x: center.x + pos.x,
                        y: center.y + pos.y,
                        z: center.z + pos.z
                    };
                    
                    try {
                        const owl = dimension.spawnEntity('myw:ancient_mythril_owl', spawnPos);
                        if (owl) {
                            // Configure owl as nocturnal
                            owl.triggerEvent('myw:night_owl');
                            
                            // Spawn particles
                            for (let i = 0; i < 10; i++) {
                                system.runTimeout(() => {
                                    dimension.spawnParticle('myw:mythril_particle_minimalist', {
                                        x: spawnPos.x + (Math.random() - 0.5) * 2,
                                        y: spawnPos.y + Math.random() * 2,
                                        z: spawnPos.z + (Math.random() - 0.5) * 2
                                    });
                                }, i * 3);
                            }
                            
                            this.sendRuneMessage(player, `§8🦉 Mythril Owl #${index + 1} summoned`);
                        }
                    } catch (error) {
                        this.sendRuneMessage(player, `§cError spawning owl #${index + 1}`);
                    }
                }, index * 20);
            });
            
            this.sendRuneMessage(player, `§8🦉 Summoning ${owlPositions.length} Mythril Owls...`);
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError spawning owls: ${error.message}`);
        }
    },

    // Final effects of night ritual
    createNightFinale(dimension, center, player) {
        try {
            // Night particle explosion
            for (let i = 0; i < 40; i++) {
                system.runTimeout(() => {
                    const angle = (i / 40) * Math.PI * 2;
                    const radius = 10 + Math.random() * 15;
                    const height = Math.random() * 15;
                    
                    const particlePos = {
                        x: center.x + Math.cos(angle) * radius,
                        y: center.y + height,
                        z: center.z + Math.sin(angle) * radius
                    };
                    
                    dimension.spawnParticle('myw:mythril_particle_minimalist', particlePos);
                }, i * 2);
            }
            
            // Temporary invisibility effect
            player.addEffect('invisibility', 200, {
                amplifier: 0,
                showParticles: false
            });
            
            this.sendRuneMessage(player, '§8🌙 NIGHT RITUAL COMPLETED! The Mythril Owls watch over the night.');
            
        } catch (error) {
            this.sendRuneMessage(player, `§cError in final effects: ${error.message}`);
        }
    },



    // ==================== REWARD SYSTEM ====================
    giveRewards(player, rewardItems) {
        const inventory = player.getComponent('minecraft:inventory');
        if (!inventory) return;

        rewardItems.forEach(itemId => {
            try {
                const item = { typeId: itemId, amount: 1 };
                inventory.addItem(item);
            } catch (error) {
                // Error adding item
            }
        });
    },

    // ==================== COOLDOWN SYSTEM ====================
    isPlayerOnCooldown(player, ritualName) {
        const playerCooldowns = this.state.playerCooldowns.get(player.id) || {};
        const cooldownEnd = playerCooldowns[ritualName] || 0;
        return system.currentTick < cooldownEnd;
    },

    setPlayerCooldown(player, ritualName, durationTicks) {
        let playerCooldowns = this.state.playerCooldowns.get(player.id) || {};
        playerCooldowns[ritualName] = system.currentTick + durationTicks;
        this.state.playerCooldowns.set(player.id, playerCooldowns);
    },

    getRemainingCooldown(player, ritualName) {
        const playerCooldowns = this.state.playerCooldowns.get(player.id) || {};
        const cooldownEnd = playerCooldowns[ritualName] || 0;
        return Math.max(0, cooldownEnd - system.currentTick);
    },

    // ==================== UTILITIES ====================
    sendRuneMessage(player, message) {
        try {
            player.onScreenDisplay.setActionBar(`§5[RUNES] ${message}`);
        } catch (error) {
            // Error sending message
        }
    },

    // Show minimal info in top-left corner
    showRuneInfo(player, runeCount, ritualType = null) {
        try {
            let info = `§5◆${runeCount}/5`;
            if (ritualType) {
                info += ` §d${ritualType.name}`;
            }
            player.onScreenDisplay.setTitle(info, {
                stayDuration: 40,
                fadeInDuration: 5,
                fadeOutDuration: 10
            });
        } catch (error) {
            // Error showing info
        }
    },

    getDistance(pos1, pos2) {
        return Math.sqrt(
            Math.pow(pos1.x - pos2.x, 2) +
            Math.pow(pos1.y - pos2.y, 2) +
            Math.pow(pos1.z - pos2.z, 2)
        );
    }
};

// ==================== EVENTS AND DETECTION ====================
function handleRunePlacement(event) {
    const { block, player } = event;

    if (!AncientRuneSystem.isRuneBlock(block.typeId)) {
        return;
    }

    console.log(`[RUNE SYSTEM] Rune placed: ${block.typeId} at ${block.location.x}, ${block.location.y}, ${block.location.z}`);

    system.runTimeout(() => {
        const runes = AncientRuneSystem.scanForRunes(player.dimension, block.location, 10);
        console.log(`[RUNE SYSTEM] Found ${runes.length} runes nearby`);
        
        const pattern = AncientRuneSystem.detectPattern(runes);
        console.log(`[RUNE SYSTEM] Pattern detected:`, pattern ? pattern.type : 'None');

        if (pattern) {
            const ritualType = AncientRuneSystem.determineRitualType(runes);
            console.log(`[RUNE SYSTEM] Ritual type determined:`, ritualType?.name || 'None');
            
            if (ritualType) {
                AncientRuneSystem.showRuneInfo(player, 5, ritualType);
                AncientRuneSystem.sendRuneMessage(player, `§dStarting ${ritualType.name} in 3s...`);

                system.runTimeout(() => {
                    const newRunes = AncientRuneSystem.scanForRunes(player.dimension, block.location, 10);
                    const newPattern = AncientRuneSystem.detectPattern(newRunes);

                    if (newPattern && newRunes.length === runes.length) {
                        console.log(`[RUNE SYSTEM] Starting ritual: ${ritualType.name}`);
                        AncientRuneSystem.startRitual(player, newPattern, { runeType: ritualType.runeType, position: block.location });
                    } else {
                        AncientRuneSystem.sendRuneMessage(player, '§cFormation changed');
                    }
                }, 60); // 3 seconds
            } else {
                AncientRuneSystem.showRuneInfo(player, 5);
                AncientRuneSystem.sendRuneMessage(player, `§cDifferent rune types`);
            }
        } else if (runes.length > 0) {
            AncientRuneSystem.showRuneInfo(player, runes.length);
            AncientRuneSystem.sendRuneMessage(player, `§e${runes.length}/5 runes`);
        }
    }, 10);
}

function handleItemActivation(event) {
    const { source: player, itemStack } = event;

    if (!itemStack || itemStack.typeId !== 'myw:ancient_mythril_charge') {
        return;
    }

    if (AncientRuneSystem.state.activeRituals.has(player.id)) {
        AncientRuneSystem.sendRuneMessage(player, '§cActive ritual');
        return;
    }

    const runes = AncientRuneSystem.scanForRunes(player.dimension, player.location, 10);

    if (runes.length < AncientRuneSystem.config.detection.minRuneCount) {
        AncientRuneSystem.sendRuneMessage(player, '§cNot enough runes');
        return;
    }

    const pattern = AncientRuneSystem.detectPattern(runes);

    if (!pattern) {
        AncientRuneSystem.sendRuneMessage(player, '§cInvalid pattern');
        return;
    }

    const mainRuneType = runes[0].runeType;
    const allSameType = runes.every(rune => rune.runeType === mainRuneType);

    if (!allSameType) {
        AncientRuneSystem.sendRuneMessage(player, '§cSame type required');
        return;
    }

    AncientRuneSystem.sendRuneMessage(player, '§aActivating...');
    AncientRuneSystem.startRitual(player, pattern, { runeType: mainRuneType, position: runes[0].position });
}

// ==================== EXPORTS ====================
export function registerAncientRuneSystem() {
    console.log('[ANCIENT RUNE SYSTEM] Rune system registered - No Temple Runes');
}

export function initializeAncientRuneSystem() {
    world.afterEvents.playerPlaceBlock.subscribe(handleRunePlacement);
    world.afterEvents.itemUse.subscribe(handleItemActivation);

    system.runInterval(() => {
        AncientRuneSystem.state.scanTimer++;

        if (AncientRuneSystem.state.scanTimer % 200 === 0) {
            for (const [playerId, cooldowns] of AncientRuneSystem.state.playerCooldowns.entries()) {
                const cleanedCooldowns = {};
                for (const [ritualName, endTime] of Object.entries(cooldowns)) {
                    if (endTime > system.currentTick) {
                        cleanedCooldowns[ritualName] = endTime;
                    }
                }
                AncientRuneSystem.state.playerCooldowns.set(playerId, cleanedCooldowns);
            }
        }
    }, 20);

    console.log('[ANCIENT RUNE SYSTEM] Initialized - 6 basic rituals');
    console.log('[ANCIENT RUNE SYSTEM] Rituals: Summon, Nature, Ascension, Companion, Destruction, Night');
    console.log('[ANCIENT RUNE SYSTEM] Detection: 5 same runes');
}