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

export const AncientRelicSystem = {
    config: {
        // Floating island configuration
        island: {
            baseRadius: 25,      // Base radius of the island
            maxRadius: 35,       // Maximum radius
            baseHeight: 120,     // Base floating height HIGHER
            baseDepth: 12,       // Base depth (INVERTED PYRAMID)
            surfaceHeight: 3,    // Surface height (grass/dirt)
            cooldown: 10000,     // 10 seconds cooldown (reduced for testing)
            generationTime: 300, // 15 seconds to generate
            particleIntensity: 3 // Particle intensity
        },

        // Available addon blocks
        blocks: {
            // Rocky and structural base
            foundation: [
                'myw:ancient_mythril_bricks',
                'myw:ancient_mythril_bricks_2'
            ],
            
            // Island surface
            terrain: {
                dirt: 'myw:ancient_mythril_dirt',
                grass: 'myw:ancient_mythril_grass'
            },
            
            // Decoration and temples
            temple: [
                'myw:ancient_mythril_temple_block',
                'myw:ancient_mythril_temple_block_2',
                'myw:ancient_mythril_temple_rune',
                'myw:ancient_mythril_temple_rune_2'
            ],
            
            // Vegetation
            vegetation: {
                trunk: 'myw:ancient_mythril_log',
                leaves: 'myw:ancient_mythril_leaves'
            },
            
            // Magical runes (layer)
            runes: [
                'myw:ancient_mythril_summon_rune',
                'myw:ancient_mythril_tree_rune',
                'myw:ancient_mythril_ascension_rune',
                'myw:ancient_mythril_pet_rune',
                'myw:ancient_mythril_destruction_rune',
                'myw:ancient_mythril_night_rune'
            ],
            
            // Magical plants (cross)
            plants: [
                'myw:ancient_mythril_emberlon',
                'myw:ancient_mythril_talor',
                'myw:ancient_mythril_sapplig'
            ]
        },

        // Particles for effects
        particles: {
            creation: [
                'myw:mythril_particle',
                'myw:mythril_particle_minimalist',
                'myw:mythril_heal_particle',
                'myw:mythril_flight_particle'
            ]
        },

        // Island dragons
        dragons: [
            'myw:mythril_dragon', // THE TRUE MYTHRIL DRAGON!
            'myw:mythril_dragon'  // Two real mythical dragons
        ]
    },

    // Player cooldown states
    playerCooldowns: new Map(),
    activeGenerations: new Set(),

    handleRelicUse(player, itemStack) {
        try {
            // Verificar cooldown
            const lastUse = this.playerCooldowns.get(player.id) || 0;
            const currentTime = Date.now();

            if (currentTime - lastUse < this.config.island.cooldown) {
                const remainingSeconds = Math.ceil((this.config.island.cooldown - (currentTime - lastUse)) / 1000);
                this.sendRelicMessage(player, `§c⏰ Ancient Relic on cooldown: ${remainingSeconds} seconds remaining`);
                return false;
            }

            // Check that there's no other active generation
            if (this.activeGenerations.has(player.id)) {
                this.sendRelicMessage(player, '§c🏝️ You already have an island under construction...');
                return false;
            }

            // Update cooldown - FIXED
            this.playerCooldowns.set(player.id, currentTime);

            // Calculate island location - HIGHER IN THE SKY
            const playerLocation = player.location;
            const islandCenter = {
                x: Math.floor(playerLocation.x),
                y: this.config.island.baseHeight, // Y=120 floating
                z: Math.floor(playerLocation.z)
            };

            // Start island generation
            this.startIslandGeneration(player, islandCenter);

            return true;
        } catch (error) {
            world.sendMessage(`§c[Relic Error] ${error}`);
            return false;
        }
    },

    startIslandGeneration(player, centerLocation) {
        try {
            this.activeGenerations.add(player.id);
            const dimension = player.dimension;

            this.sendRelicMessage(player, '§d🌟 §5SUMMONING ANCIENT FLOATING ISLAND §d🌟');
            this.sendRelicMessage(player, '§7Preparing ancient magic...');

            // Phase 1: Preparation effects
            this.createPreGenerationEffects(dimension, centerLocation);

            // Phase 2: Generate base structure (after 3 seconds)
            system.runTimeout(() => {
                this.generateIslandFoundation(dimension, centerLocation, player);
            }, 60);

            // Phase 3: Add vegetation (after 6 seconds)
            system.runTimeout(() => {
                this.generateIslandVegetation(dimension, centerLocation, player);
            }, 120);

            // Phase 4: Place runes and magical plants (after 9 seconds)
            system.runTimeout(() => {
                this.generateMagicalElements(dimension, centerLocation, player);
            }, 180);

            // Phase 5: Spawn mystical dragons
            system.runTimeout(() => {
                this.spawnIslandDragons(dimension, centerLocation, player);
            }, 240);

            // Phase 6: Finish with spectacular effects
            system.runTimeout(() => {
                this.completeIslandGeneration(dimension, centerLocation, player);
                this.activeGenerations.delete(player.id);
            }, 300);

        } catch (error) {
            this.activeGenerations.delete(player.id);
            world.sendMessage(`§c[Island Generation Error] ${error}`);
        }
    },

    createPreGenerationEffects(dimension, center) {
        try {
            this.sendRelicMessage(world.getAllPlayers()[0], '§6⚡ Channeling ancient energy...');

            // Ascending energy column
            for (let h = 0; h < 40; h++) {
                system.runTimeout(() => {
                    // Energy heptagon
                    for (let i = 0; i < 7; i++) {
                        const angle = (i / 7) * Math.PI * 2 + h * 0.1;
                        const radius = 3 + Math.sin(h * 0.2) * 2;
                        
                        dimension.spawnParticle('myw:mythril_flight_particle', {
                            x: center.x + Math.cos(angle) * radius,
                            y: center.y - 20 + h,
                            z: center.z + Math.sin(angle) * radius
                        });
                    }

                    // Central core
                    if (h % 3 === 0) {
                        dimension.spawnParticle('myw:mythril_heal_particle', {
                            x: center.x + (Math.random() - 0.5) * 2,
                            y: center.y - 20 + h,
                            z: center.z + (Math.random() - 0.5) * 2
                        });
                    }
                }, h * 1);
            }

            // Expansive waves on the ground
            for (let wave = 0; wave < 8; wave++) {
                system.runTimeout(() => {
                    const waveRadius = (wave + 1) * 5;
                    
                    for (let i = 0; i < 14; i++) {
                        const angle = (i / 14) * Math.PI * 2;
                        dimension.spawnParticle('myw:mythril_particle', {
                            x: center.x + Math.cos(angle) * waveRadius,
                            y: center.y - 25,
                            z: center.z + Math.sin(angle) * waveRadius
                        });
                    }
                }, wave * 8);
            }

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

    generateIslandFoundation(dimension, center, player) {
        try {
            this.sendRelicMessage(player, '§a🗿 Materializing ancient foundations...');

            const baseRadius = this.config.island.baseRadius;
            const foundationBlocks = this.config.blocks.foundation;
            const dirtBlock = this.config.blocks.terrain.dirt;
            const grassBlock = this.config.blocks.terrain.grass;
            
            // Generate FLAT AND CIRCULAR base
            for (let x = -baseRadius; x <= baseRadius; x++) {
                for (let z = -baseRadius; z <= baseRadius; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    
                    // Perfect circle (not organic)
                    if (distance <= baseRadius) {
                        // FLAT ISLAND - fixed height
                        const baseDepth = this.config.island.baseDepth;
                        const surfaceHeight = this.config.island.surfaceHeight;
                        
                        // 1. STONE BASE (INVERTED PYRAMID)
                        for (let y = -baseDepth; y < 0; y++) {
                            // Each layer downward is 1 block smaller in radius
                            const layerRadiusReduction = Math.abs(y);
                            const layerRadius = baseRadius - layerRadiusReduction;
                            
                            // Only place if within this layer's radius
                            if (distance <= layerRadius && layerRadius > 0) {
                                const blockLocation = {
                                    x: center.x + x,
                                    y: center.y + y,
                                    z: center.z + z
                                };

                                const blockType = foundationBlocks[Math.abs(y) % foundationBlocks.length];
                                
                                const delay = Math.floor(distance * 1.5 + Math.abs(y) * 2);
                                system.runTimeout(() => {
                                    try {
                                        dimension.setBlockType(blockLocation, blockType);
                                    } catch (error) {
                                        // Error placing block
                                    }
                                }, delay);
                            }
                        }
                        
                        // 2. DIRT LAYER (1-2 blocks)
                        for (let y = 0; y < surfaceHeight - 1; y++) {
                            const blockLocation = {
                                x: center.x + x,
                                y: center.y + y,
                                z: center.z + z
                            };
                            
                            const delay = Math.floor(distance * 1.5 + baseDepth * 2 + y * 2);
                            system.runTimeout(() => {
                                try {
                                    dimension.setBlockType(blockLocation, dirtBlock);
                                } catch (error) {
                                    // Error placing dirt
                                }
                            }, delay);
                        }
                        
                        // 3. GRASS LAYER (surface)
                        const grassLocation = {
                            x: center.x + x,
                            y: center.y + surfaceHeight - 1,
                            z: center.z + z
                        };
                        
                        const delay = Math.floor(distance * 1.5 + baseDepth * 2 + surfaceHeight * 2);
                        system.runTimeout(() => {
                            try {
                                dimension.setBlockType(grassLocation, grassBlock);
                                
                                // Particle effects when placing surface
                                if (Math.random() < 0.05) {
                                    dimension.spawnParticle('myw:mythril_heal_particle', {
                                        x: grassLocation.x + 0.5,
                                        y: grassLocation.y + 1,
                                        z: grassLocation.z + 0.5
                                    });
                                }
                            } catch (error) {
                                // Error placing grass
                            }
                        }, delay);
                    }
                }
            }

            // Create temple structures (after base)
            system.runTimeout(() => {
                this.generateTempleStructures(dimension, center);
            }, baseRadius * 3);

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

    generateTempleStructures(dimension, center) {
        try {
            const templeBlocks = this.config.blocks.temple;
            const foundationBlocks = this.config.blocks.foundation;
            const surfaceY = center.y + this.config.island.surfaceHeight;

            // STRUCTURE 1: GRAND CENTRAL TEMPLE
            system.runTimeout(() => {
                this.buildGrandTemple(dimension, center, surfaceY, templeBlocks);
            }, 20);

            // STRUCTURE 2: WATCH TOWER
            system.runTimeout(() => {
                this.buildWatchTower(dimension, { x: center.x + 18, z: center.z + 12 }, surfaceY, templeBlocks);
            }, 60);

            // STRUCTURE 3: CEREMONIAL ALTAR
            system.runTimeout(() => {
                this.buildCeremonialAltar(dimension, { x: center.x - 20, z: center.z - 8 }, surfaceY, templeBlocks, foundationBlocks);
            }, 100);

            // STRUCTURE 4: ARCANE LIBRARY
            system.runTimeout(() => {
                this.buildArcaneLibrary(dimension, { x: center.x + 15, z: center.z - 18 }, surfaceY, templeBlocks);
            }, 140);

            // STRUCTURE 5: RUNE SHRINE
            system.runTimeout(() => {
                this.buildRuneShrine(dimension, { x: center.x - 12, z: center.z + 16 }, surfaceY, templeBlocks);
            }, 180);

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

    buildGrandTemple(dimension, center, surfaceY, templeBlocks) {
        try {
            // GRAND CENTRAL TEMPLE 9x9
            const size = 4; // radius
            
            // TEMPLE BASE (elevated platform)
            for (let x = -size; x <= size; x++) {
                for (let z = -size; z <= size; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    if (distance <= size) {
                        const baseLocation = {
                            x: center.x + x,
                            y: surfaceY,
                            z: center.z + z
                        };
                        
                        system.runTimeout(() => {
                            try {
                                dimension.setBlockType(baseLocation, templeBlocks[0]);
                            } catch (error) {
                                // Error
                            }
                        }, Math.floor(distance * 5));
                    }
                }
            }

            // EXTERIOR WALLS (8x8)
            for (let x = -3; x <= 3; x++) {
                for (let z = -3; z <= 3; z++) {
                    if (Math.abs(x) === 3 || Math.abs(z) === 3) {
                        // Columns at corners
                        const isCorner = Math.abs(x) === 3 && Math.abs(z) === 3;
                        const height = isCorner ? 6 : 4;
                        
                        for (let y = 1; y <= height - 1; y++) {
                            const wallLocation = {
                                x: center.x + x,
                                y: surfaceY + y,
                                z: center.z + z
                            };
                            
                            system.runTimeout(() => {
                                try {
                                    dimension.setBlockType(wallLocation, templeBlocks[1]);
                                } catch (error) {
                                    // Error
                                }
                            }, 40 + y * 5);
                        }
                    }
                }
            }

            // CENTRAL ALTAR
            const altarLocation = {
                x: center.x,
                y: surfaceY + 1,
                z: center.z
            };
            
            system.runTimeout(() => {
                try {
                    dimension.setBlockType(altarLocation, templeBlocks[2]);
                } catch (error) {
                    // Error
                }
            }, 80);

            // INTERIOR PILLARS
            const pillarPositions = [
                { x: -1, z: -1 }, { x: 1, z: -1 },
                { x: -1, z: 1 }, { x: 1, z: 1 }
            ];

            pillarPositions.forEach((pos, index) => {
                for (let y = 1; y <= 4; y++) {
                    const pillarLocation = {
                        x: center.x + pos.x,
                        y: surfaceY + y,
                        z: center.z + pos.z
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(pillarLocation, templeBlocks[3]);
                        } catch (error) {
                            // Error
                        }
                    }, 60 + index * 10 + y * 3);
                }
            });

        } catch (error) {
            // Error en gran templo
        }
    },

    buildWatchTower(dimension, pos, surfaceY, templeBlocks) {
        try {
            // WATCH TOWER 3x3x12
            const towerSize = 1;
            
            // SOLID BASE
            for (let x = -towerSize; x <= towerSize; x++) {
                for (let z = -towerSize; z <= towerSize; z++) {
                    for (let y = 0; y <= 1; y++) {
                        const baseLocation = {
                            x: pos.x + x,
                            y: surfaceY + y,
                            z: pos.z + z
                        };
                        
                        system.runTimeout(() => {
                            try {
                                dimension.setBlockType(baseLocation, templeBlocks[0]);
                            } catch (error) {
                                // Error
                            }
                        }, y * 5);
                    }
                }
            }

            // TOWER WALLS (hollow)
            for (let y = 2; y <= 11; y++) {
                for (let x = -towerSize; x <= towerSize; x++) {
                    for (let z = -towerSize; z <= towerSize; z++) {
                        if (Math.abs(x) === towerSize || Math.abs(z) === towerSize) {
                            const wallLocation = {
                                x: pos.x + x,
                                y: surfaceY + y,
                                z: pos.z + z
                            };
                            
                            system.runTimeout(() => {
                                try {
                                    dimension.setBlockType(wallLocation, templeBlocks[1]);
                                } catch (error) {
                                    // Error
                                }
                            }, y * 3);
                        }
                    }
                }
            }

            // ROOF (pyramid)
            const roofLocation = {
                x: pos.x,
                y: surfaceY + 12,
                z: pos.z
            };
            
            system.runTimeout(() => {
                try {
                    dimension.setBlockType(roofLocation, templeBlocks[2]);
                } catch (error) {
                    // Error
                }
            }, 150);

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

    buildCeremonialAltar(dimension, pos, surfaceY, templeBlocks, foundationBlocks) {
        try {
            // CEREMONIAL ALTAR with steps
            
            // BASE PLATFORM (7x7)
            for (let x = -3; x <= 3; x++) {
                for (let z = -3; z <= 3; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    if (distance <= 3) {
                        const baseLocation = {
                            x: pos.x + x,
                            y: surfaceY,
                            z: pos.z + z
                        };
                        
                        system.runTimeout(() => {
                            try {
                                dimension.setBlockType(baseLocation, foundationBlocks[0]);
                            } catch (error) {
                                // Error
                            }
                        }, Math.floor(distance * 3));
                    }
                }
            }

            // STEPS (5x5)
            for (let x = -2; x <= 2; x++) {
                for (let z = -2; z <= 2; z++) {
                    const distance = Math.sqrt(x * x + z * z);
                    if (distance <= 2) {
                        const stepLocation = {
                            x: pos.x + x,
                            y: surfaceY + 1,
                            z: pos.z + z
                        };
                        
                        system.runTimeout(() => {
                            try {
                                dimension.setBlockType(stepLocation, templeBlocks[0]);
                            } catch (error) {
                                // Error
                            }
                        }, 30 + Math.floor(distance * 3));
                    }
                }
            }

            // CENTRAL ALTAR (3x3)
            for (let x = -1; x <= 1; x++) {
                for (let z = -1; z <= 1; z++) {
                    const altarLocation = {
                        x: pos.x + x,
                        y: surfaceY + 2,
                        z: pos.z + z
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(altarLocation, templeBlocks[2]);
                        } catch (error) {
                            // Error
                        }
                    }, 60);
                }
            }

            // CENTRAL CEREMONIAL PILLAR
            for (let y = 3; y <= 6; y++) {
                const pillarLocation = {
                    x: pos.x,
                    y: surfaceY + y,
                    z: pos.z
                };
                
                system.runTimeout(() => {
                    try {
                        dimension.setBlockType(pillarLocation, templeBlocks[3]);
                    } catch (error) {
                        // Error
                    }
                }, 80 + y * 5);
            }

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

    spawnIslandDragons(dimension, center, player) {
        try {
            this.sendRelicMessage(player, '§4🐉 Ancient dragons awaken...');

            const surfaceY = center.y + this.config.island.surfaceHeight;
            const dragons = this.config.dragons;

            // STRATEGIC POSITIONS for the 2 dragons
            const dragonPositions = [
                { x: center.x + 15, y: surfaceY + 8, z: center.z + 10 },  // Dragon 1: Tower area
                { x: center.x - 18, y: surfaceY + 6, z: center.z - 12 }   // Dragon 2: Altar area
            ];

            dragonPositions.forEach((pos, index) => {
                system.runTimeout(() => {
                    try {
                        // Pre-spawn effects
                        for (let effect = 0; effect < 10; effect++) {
                            system.runTimeout(() => {
                                const effectRadius = 3;
                                for (let i = 0; i < 8; i++) {
                                    const angle = (i / 8) * Math.PI * 2;
                                    dimension.spawnParticle('myw:mythril_flight_particle', {
                                        x: pos.x + Math.cos(angle) * effectRadius,
                                        y: pos.y + effect * 0.5,
                                        z: pos.z + Math.sin(angle) * effectRadius
                                    });
                                }
                                
                                // Central particles
                                dimension.spawnParticle('myw:mythril_heal_particle', {
                                    x: pos.x + (Math.random() - 0.5) * 2,
                                    y: pos.y + effect * 0.5 + 2,
                                    z: pos.z + (Math.random() - 0.5) * 2
                                });
                            }, effect * 3);
                        }

                        // Spawn dragon after effects
                        system.runTimeout(() => {
                            try {
                                const dragonType = dragons[index % dragons.length];
                                const spawnedDragon = dimension.spawnEntity(dragonType, pos);
                                
                                if (spawnedDragon) {
                                    this.sendRelicMessage(player, `§4🐉 ${index === 0 ? 'First' : 'Second'} ancient dragon has awakened!`);
                                    
                                    // Post-spawn effects
                                    for (let postEffect = 0; postEffect < 5; postEffect++) {
                                        system.runTimeout(() => {
                                            // Power ring around dragon
                                            for (let i = 0; i < 12; i++) {
                                                const angle = (i / 12) * Math.PI * 2;
                                                dimension.spawnParticle('myw:mythril_particle', {
                                                    x: pos.x + Math.cos(angle) * (4 + postEffect),
                                                    y: pos.y + 1,
                                                    z: pos.z + Math.sin(angle) * (4 + postEffect)
                                                });
                                            }
                                        }, postEffect * 8);
                                    }
                                }
                            } catch (spawnError) {
                                this.sendRelicMessage(player, `§c⚠️ Error spawning dragon ${index + 1}`);
                            }
                        }, 40);

                    } catch (error) {
                        // Error in dragon spawn
                    }
                }, index * 30);
            });

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

    buildArcaneLibrary(dimension, pos, surfaceY, templeBlocks) {
        try {
            // ARCANE LIBRARY 6x4
            
            // BASE
            for (let x = -2; x <= 3; x++) {
                for (let z = -2; z <= 1; z++) {
                    const baseLocation = {
                        x: pos.x + x,
                        y: surfaceY,
                        z: pos.z + z
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(baseLocation, templeBlocks[0]);
                        } catch (error) {
                            // Error
                        }
                    }, (Math.abs(x) + Math.abs(z)) * 2);
                }
            }

            // WALLS
            for (let y = 1; y <= 4; y++) {
                // North wall
                for (let x = -2; x <= 3; x++) {
                    const wallLocation = {
                        x: pos.x + x,
                        y: surfaceY + y,
                        z: pos.z + 1
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(wallLocation, templeBlocks[1]);
                        } catch (error) {
                            // Error
                        }
                    }, 20 + y * 3);
                }

                // South wall
                for (let x = -2; x <= 3; x++) {
                    const wallLocation = {
                        x: pos.x + x,
                        y: surfaceY + y,
                        z: pos.z - 2
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(wallLocation, templeBlocks[1]);
                        } catch (error) {
                            // Error
                        }
                    }, 20 + y * 3);
                }

                // East and west walls
                for (let z = -2; z <= 1; z++) {
                    // East
                    const eastLocation = {
                        x: pos.x + 3,
                        y: surfaceY + y,
                        z: pos.z + z
                    };
                    
                    // West
                    const westLocation = {
                        x: pos.x - 2,
                        y: surfaceY + y,
                        z: pos.z + z
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(eastLocation, templeBlocks[1]);
                            dimension.setBlockType(westLocation, templeBlocks[1]);
                        } catch (error) {
                            // Error
                        }
                    }, 25 + y * 3);
                }
            }

            // SHELVES (interior pillars simulating books)
            const shelfPositions = [
                { x: -1, z: -1 }, { x: 0, z: -1 }, { x: 1, z: -1 },
                { x: -1, z: 0 }, { x: 1, z: 0 }
            ];

            shelfPositions.forEach((shelf, index) => {
                for (let y = 1; y <= 3; y++) {
                    const shelfLocation = {
                        x: pos.x + shelf.x,
                        y: surfaceY + y,
                        z: pos.z + shelf.z
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(shelfLocation, templeBlocks[3]);
                        } catch (error) {
                            // Error
                        }
                    }, 40 + index * 5 + y * 2);
                }
            });

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

    buildRuneShrine(dimension, pos, surfaceY, templeBlocks) {
        try {
            // Circular RUNE SHRINE
            const radius = 2;

            // CIRCULAR PLATFORM
            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) {
                        const baseLocation = {
                            x: pos.x + x,
                            y: surfaceY,
                            z: pos.z + z
                        };
                        
                        system.runTimeout(() => {
                            try {
                                dimension.setBlockType(baseLocation, templeBlocks[0]);
                            } catch (error) {
                                // Error
                            }
                        }, Math.floor(distance * 4));
                    }
                }
            }

            // CIRCULAR PILLARS
            const pillarPositions = [
                { x: 2, z: 0 }, { x: -2, z: 0 },
                { x: 0, z: 2 }, { x: 0, z: -2 },
                { x: 1, z: 1 }, { x: -1, z: 1 },
                { x: 1, z: -1 }, { x: -1, z: -1 }
            ];

            pillarPositions.forEach((pillar, index) => {
                for (let y = 1; y <= 3; y++) {
                    const pillarLocation = {
                        x: pos.x + pillar.x,
                        y: surfaceY + y,
                        z: pos.z + pillar.z
                    };
                    
                    system.runTimeout(() => {
                        try {
                            dimension.setBlockType(pillarLocation, templeBlocks[2]);
                        } catch (error) {
                            // Error
                        }
                    }, 30 + index * 3 + y * 2);
                }
            });

            // ELEVATED CENTRAL CORE
            for (let y = 1; y <= 5; y++) {
                const coreLocation = {
                    x: pos.x,
                    y: surfaceY + y,
                    z: pos.z
                };
                
                system.runTimeout(() => {
                    try {
                        dimension.setBlockType(coreLocation, templeBlocks[3]);
                    } catch (error) {
                        // Error
                    }
                }, 60 + y * 5);
            }

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

    generateIslandVegetation(dimension, center, player) {
        try {
            this.sendRelicMessage(player, '§2🌳 Cultivating mystical forest...');

            const trunkBlock = this.config.blocks.vegetation.trunk;
            const leavesBlock = this.config.blocks.vegetation.leaves;
            const surfaceY = center.y + this.config.island.surfaceHeight;

            // BETTER TREES - more distributed and varied
            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 }
            ];

            treePositions.forEach((tree, treeIndex) => {
                system.runTimeout(() => {
                    // Generate trunk from surface
                    for (let y = 0; y < tree.height; y++) {
                        const trunkLocation = {
                            x: center.x + tree.x,
                            y: surfaceY + y, // FROM THE SURFACE
                            z: center.z + tree.z
                        };

                        system.runTimeout(() => {
                            try {
                                dimension.setBlockType(trunkLocation, trunkBlock);
                            } catch (error) {
                                // Error placing trunk
                            }
                        }, y * 2);
                    }

                    // Generate IMPROVED leaves
                    system.runTimeout(() => {
                        const leafRadius = 4 + Math.floor(tree.height / 4);
                        const leafTop = surfaceY + tree.height;

                        for (let x = -leafRadius; x <= leafRadius; x++) {
                            for (let z = -leafRadius; z <= leafRadius; z++) {
                                for (let y = -3; y <= 4; y++) {
                                    const distance = Math.sqrt(x * x + z * z);
                                    const verticalDistance = Math.abs(y);
                                    
                                    // More natural spherical shape
                                    const totalDistance = Math.sqrt(x * x + z * z + y * y * 0.8);
                                    
                                    if (totalDistance <= leafRadius && Math.random() < (1 - totalDistance / leafRadius) * 0.9) {
                                        const leafLocation = {
                                            x: center.x + tree.x + x,
                                            y: leafTop + y,
                                            z: center.z + tree.z + z
                                        };

                                        const delay = Math.floor(totalDistance * 2);
                                        system.runTimeout(() => {
                                            try {
                                                dimension.setBlockType(leafLocation, leavesBlock);
                                            } catch (error) {
                                                // Error placing leaves
                                            }
                                        }, delay);
                                    }
                                }
                            }
                        }
                    }, tree.height * 2 + 20);

                }, treeIndex * 20);
            });

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

    generateMagicalElements(dimension, center, player) {
        try {
            this.sendRelicMessage(player, '§5🔮 Placing ancient magical elements...');

            const surfaceY = center.y + this.config.island.surfaceHeight;
            
            // MAGICAL RUNES - need solid block below
            const runes = this.config.blocks.runes;
            const runeRadius = 22;

            runes.forEach((rune, index) => {
                const angle = (index / runes.length) * Math.PI * 2;
                const runeBaseLocation = {
                    x: center.x + Math.floor(Math.cos(angle) * runeRadius),
                    y: surfaceY, // ON THE SURFACE
                    z: center.z + Math.floor(Math.sin(angle) * runeRadius)
                };
                
                const runeLocation = {
                    x: runeBaseLocation.x,
                    y: runeBaseLocation.y, // DIRECTLY on the grass
                    z: runeBaseLocation.z
                };

                system.runTimeout(() => {
                    try {
                        // CRITICAL: Runes need solid block below
                        dimension.setBlockType(runeLocation, rune);
                        
                        // Particle effects on runes
                        for (let p = 0; p < 7; p++) {
                            system.runTimeout(() => {
                                dimension.spawnParticle('myw:mythril_particle', {
                                    x: runeLocation.x + 0.5,
                                    y: runeLocation.y + 1 + p * 0.3,
                                    z: runeLocation.z + 0.5
                                });
                            }, p * 8);
                        }
                    } catch (error) {
                        // Error placing rune
                    }
                }, index * 12);
            });

            // MASSIVE MAGICAL PLANTS - MANY MORE
            const plants = this.config.blocks.plants;
            const plantPositions = [
                // Outer ring (radius ~20-24)
                { x: 22, z: 8 }, { x: -24, z: 6 }, { x: 20, z: -12 }, { x: -22, z: -10 },
                { x: 8, z: 23 }, { x: -6, z: -24 }, { x: 12, z: -20 }, { x: -10, z: 22 },
                { x: 24, z: 0 }, { x: -24, z: 0 }, { x: 0, z: 24 }, { x: 0, z: -24 },
                
                // Middle ring (radius ~15-19)
                { x: 18, z: 12 }, { x: -19, z: 11 }, { x: 17, z: -13 }, { x: -18, z: -12 },
                { x: 12, z: 18 }, { x: -11, z: -19 }, { x: 13, z: -17 }, { x: -12, z: 18 },
                { x: 19, z: 4 }, { x: -19, z: -4 }, { x: 4, z: 19 }, { x: -4, z: -19 },
                { x: 15, z: 15 }, { x: -15, z: 15 }, { x: 15, z: -15 }, { x: -15, z: -15 },
                
                // Intermediate ring (radius ~10-14)
                { x: 14, z: 8 }, { x: -14, z: 7 }, { x: 13, z: -9 }, { x: -13, z: -8 },
                { x: 8, z: 14 }, { x: -7, z: -14 }, { x: 9, z: -13 }, { x: -8, z: 13 },
                { x: 14, z: 0 }, { x: -14, z: 0 }, { x: 0, z: 14 }, { x: 0, z: -14 },
                { x: 12, z: 10 }, { x: -12, z: 10 }, { x: 12, z: -10 }, { x: -12, z: -10 },
                { x: 10, z: 12 }, { x: -10, z: 12 }, { x: 10, z: -12 }, { x: -10, z: -12 },
                
                // Inner ring (radius ~5-9)
                { x: 9, z: 5 }, { x: -9, z: 4 }, { x: 8, z: -6 }, { x: -8, z: -5 },
                { x: 5, z: 9 }, { x: -4, z: -9 }, { x: 6, z: -8 }, { x: -5, z: 8 },
                { x: 9, z: 0 }, { x: -9, z: 0 }, { x: 0, z: 9 }, { x: 0, z: -9 },
                { x: 7, z: 7 }, { x: -7, z: 7 }, { x: 7, z: -7 }, { x: -7, z: -7 },
                
                // Plants near center (radius ~2-4)
                { x: 4, z: 2 }, { x: -4, z: 1 }, { x: 3, z: -3 }, { x: -3, z: -2 },
                { x: 2, z: 4 }, { x: -1, z: -4 }, { x: 3, z: -3 }, { x: -2, z: 3 },
                { x: 4, z: 0 }, { x: -4, z: 0 }, { x: 0, z: 4 }, { x: 0, z: -4 },
                
                // Additional scattered plants
                { x: 16, z: 3 }, { x: -16, z: -3 }, { x: 3, z: 16 }, { x: -3, z: -16 },
                { x: 11, z: 6 }, { x: -11, z: -6 }, { x: 6, z: 11 }, { x: -6, z: -11 },
                { x: 21, z: 2 }, { x: -21, z: -2 }, { x: 2, z: 21 }, { x: -2, z: -21 },
                { x: 17, z: 9 }, { x: -17, z: -9 }, { x: 9, z: 17 }, { x: -9, z: -17 }
            ];

            plantPositions.forEach((pos, index) => {
                const plant = plants[index % plants.length];
                const plantLocation = {
                    x: center.x + pos.x,
                    y: surfaceY, // DIRECTLY on the grass
                    z: center.z + pos.z
                };

                system.runTimeout(() => {
                    try {
                        dimension.setBlockType(plantLocation, plant);
                        
                        // Magical effects on plants
                        dimension.spawnParticle('myw:mythril_heal_particle', {
                            x: plantLocation.x + 0.5,
                            y: plantLocation.y + 1,
                            z: plantLocation.z + 0.5
                        });
                    } catch (error) {
                        // Error placing plant
                    }
                }, index * 5);
            });

        } catch (error) {
            // Error en elementos mágicos
        }
    },

    completeIslandGeneration(dimension, center, player) {
        try {
            this.sendRelicMessage(player, '§d✨ §5ANCIENT FLOATING ISLAND COMPLETED! §d✨');
            this.sendRelicMessage(player, '§7A majestic island now floats in the sky...');

            // Spectacular final effects
            this.createCompletionEffects(dimension, center);

            // Teleport player to the island
            system.runTimeout(() => {
                const surfaceY = center.y + this.config.island.surfaceHeight;
                const teleportLocation = {
                    x: center.x,
                    y: surfaceY + 1, // Just above the surface
                    z: center.z
                };

                try {
                    player.teleport(teleportLocation, {
                        dimension: dimension,
                        rotation: { x: 0, y: 0 }
                    });

                    this.sendRelicMessage(player, '§a🏝️ Welcome to your ancient island!');
                    this.sendRelicMessage(player, '§7Radius: 25 blocks | Height: Y=' + center.y + ' | Flat surface');
                } catch (error) {
                    this.sendRelicMessage(player, '§c⚠️ Teleport error, use /tp to reach the island');
                }
            }, 60);

            // CLEAN player state - CRITICAL FIX
            system.runTimeout(() => {
                this.activeGenerations.delete(player.id);
            }, 80);

        } catch (error) {
            // SIEMPRE limpiar estado en caso de error
            this.activeGenerations.delete(player.id);
        }
    },

    createCompletionEffects(dimension, center) {
        try {
            // Celebration explosion in multiple rings
            for (let ring = 0; ring < 6; ring++) {
                system.runTimeout(() => {
                    const ringRadius = (ring + 1) * 8;
                    
                    // Heptagonal ring of particles
                    for (let i = 0; i < 21; i++) {
                        const angle = (i / 21) * Math.PI * 2;
                        const particle = this.config.particles.creation[i % this.config.particles.creation.length];
                        
                        dimension.spawnParticle(particle, {
                            x: center.x + Math.cos(angle) * ringRadius,
                            y: center.y + 15 + ring * 2,
                            z: center.z + Math.sin(angle) * ringRadius
                        });
                    }
                }, ring * 8);
            }

            // Victory column
            system.runTimeout(() => {
                for (let h = 0; h < 30; h++) {
                    system.runTimeout(() => {
                        const columnRadius = 5 * (1 - h / 30);
                        
                        for (let i = 0; i < 7; i++) {
                            const angle = (i / 7) * Math.PI * 2 + h * 0.3;
                            dimension.spawnParticle('myw:mythril_flight_particle', {
                                x: center.x + Math.cos(angle) * columnRadius,
                                y: center.y + 15 + h,
                                z: center.z + Math.sin(angle) * columnRadius
                            });
                        }
                    }, h * 2);
                }
            }, 50);

        } catch (error) {
            // Error en efectos finales
        }
    },

    sendRelicMessage(player, message) {
        try {
            if (player && player.sendMessage) {
                player.sendMessage(message);
            } else {
                world.sendMessage(message);
            }
        } catch (error) {
            world.sendMessage(message);
        }
    },

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

// Register the relic component
export function registerAncientRelic(itemComponentRegistry) {
    itemComponentRegistry.registerCustomComponent('myw:ancient_mythril_relic', {
        onUse(eventData) {
            const { itemStack, source } = eventData;
            if (source && source.typeId === 'minecraft:player') {
                AncientRelicSystem.handleRelicUse(source, itemStack);
            }
        }
    });
}

// Initialize relic system
export function initializeAncientRelicSystem() {
    world.sendMessage('§d[OK] Ancient Relic System initialized');
    world.sendMessage('§7Floating island generator ready');
}
