let ritualActive = false;
LevelEvents.tick(event => {
    if (event.level.time % 20 != 0 || ritualActive) return;
    event.level.getPlayers().forEach(player => {
        let x = Math.floor(player.x);
        let y = Math.floor(player.y);
        let z = Math.floor(player.z);
        let trigger = event.level.getBlock(x, y - 1, z);
        if (trigger.id != 'minecraft:diamond_block') return;
        // EXACT LAYOUT DETECTION
        let isRitual = (
            event.level.getBlock(x + 1, y - 1, z).id == 'minecraft:obsidian' &&
            event.level.getBlock(x - 1, y - 1, z).id == 'minecraft:obsidian' &&
            event.level.getBlock(x, y - 1, z + 1).id == 'minecraft:obsidian' &&
            event.level.getBlock(x, y - 1, z - 1).id == 'minecraft:obsidian' &&
            event.level.getBlock(x + 1, y - 1, z + 1).id == 'minecraft:gold_block' &&
            event.level.getBlock(x - 1, y - 1, z - 1).id == 'minecraft:gold_block' &&
            event.level.getBlock(x + 1, y - 1, z - 1).id == 'minecraft:gold_block' &&
            event.level.getBlock(x - 1, y - 1, z + 1).id == 'minecraft:gold_block' &&
            event.level.getBlock(x + 2, y - 1, z).id == 'cataclysm:void_stone' &&
            event.level.getBlock(x - 2, y - 1, z).id == 'cataclysm:void_stone' &&
            event.level.getBlock(x, y - 1, z + 2).id == 'cataclysm:void_stone' &&
            event.level.getBlock(x, y - 1, z - 2).id == 'cataclysm:void_stone'
        );
        if (isRitual) {
            ritualActive = true;
            trigger.set('minecraft:bedrock');
            player.tell("§5§lThe Ritual is sealed. The Overlord awakens...");
            event.level.spawnLightning(x, y, z, true);
            // Vault Generation (50x50x20)
            for (let ix = -25; ix <= 25; ix++) {
                for (let iz = -25; iz <= 25; iz++) {
                    event.level.getBlock(x + ix, y - 6, z + iz).set('minecraft:obsidian');
                    event.level.getBlock(x + ix, y + 16, z + iz).set('minecraft:obsidian');
                    if (Math.abs(ix) == 25 || Math.abs(iz) == 25) {
                        for (let iy = -5; iy <= 15; iy++) {
                            event.level.getBlock(x + ix, y + iy, z + iz).set('minecraft:obsidian');
                        }
                    } else {
                        for (let iy = -5; iy <= 15; iy++) {
                            let target = event.level.getBlock(x + ix, y + iy, z + iz);
                            if (target.id != 'minecraft:bedrock') target.set('minecraft:air');
                        }
                    }
                }
            }
            event.server.scheduleInTicks(100, callback => {
                let boss = event.level.createEntity('minecraft:giant');
                boss.setPosition(x + 5, y - 5, z);
                boss.maxHealth = 2000;
                boss.health = 2000;
                boss.setAttributeBaseValue('minecraft:generic.knockback_resistance', 1.0);
                boss.customName = "§f§lZombie Overlord";
                boss.addTag('ritual_boss');
                boss.spawn();
                event.level.getBlock(x, y - 1, z).set('minecraft:air');
                event.server.scheduleInTicks(200, () => { ritualActive = false; });
            });
        }
    });
});
ServerEvents.tick(event => {
    if (event.server.tickCount % 20 != 0) return;
    let server = event.server;
    server.entities.filter(e => e.type == 'minecraft:giant' && e.tags.contains('ritual_boss') && e.isAlive()).forEach(boss => {
        let healthPct = boss.health / boss.maxHealth;
        let level = boss.level;
        // Regen while shielded
        if (boss.tags.contains('phase_shielded') && boss.health < boss.maxHealth) {
            boss.health = Math.min(boss.maxHealth, boss.health + 5);
            level.spawnParticles('minecraft:happy_villager', true, boss.x, boss.y + 2, boss.z, 0.5, 1, 0.5, 5, 0.1);
        }
        // Phase 1: 75% (Felsteeds)
        if (healthPct <= 0.75 && !boss.tags.contains('phase1_done')) {
            boss.addTag('phase1_done');
            boss.addTag('phase_shielded');
            for (let i = 0; i < 10; i++) {
                let m = level.createEntity('born_in_chaos_v1:felsteed');
                m.setPosition(boss.x + (Math.random() * 8 - 4), boss.y, boss.z + (Math.random() * 8 - 4));
                m.addTag('ritual_minion');
                m.spawn();
            }
            server.tell("§6§lThe Overlord summons his steeds!");
        }
        // Phase 2: 50% (Infernal Zombies)
        if (healthPct <= 0.50 && !boss.tags.contains('phase2_done')) {
            boss.addTag('phase2_done');
            boss.addTag('phase_shielded');
            for (let i = 0; i < 3; i++) {
                let m = level.createEntity('minecraft:zombie');
                m.setPosition(boss.x + (Math.random() * 6 - 3), boss.y, boss.z + (Math.random() * 6 - 3));
                m.addTag('ritual_minion');
                m.addTag('infernal');
                m.maxHealth = 150; m.health = 150;
                m.setAttributeBaseValue('minecraft:generic.attack_damage', 18.0);
                m.setAttributeBaseValue('minecraft:generic.movement_speed', 0.35);
                m.customName = "§6§lInfernal Guard";
                m.spawn();
            }
            server.tell("§6§lInfernal guards have arrived!");
        }
        // Phase 3: 25% (Ultra Spider)
        if (healthPct <= 0.25 && !boss.tags.contains('phase3_done')) {
            boss.addTag('phase3_done');
            boss.addTag('phase_shielded');
            let m = level.createEntity('minecraft:spider');
            m.setPosition(boss.x, boss.y, boss.z);
            m.addTag('ritual_minion');
            m.addTag('infernal');
            m.maxHealth = 400; m.health = 400;
            m.setAttributeBaseValue('minecraft:generic.attack_damage', 30.0);
            m.setAttributeBaseValue('minecraft:generic.movement_speed', 0.45);
            m.customName = "§4§lULTRA INFERNAL WEAVER";
            m.spawn();
            server.tell("§4§lTHE INFERNAL WEAVER HAS AWAKENED!");
        }
        // Shield Logic
        if (boss.tags.contains('phase_shielded')) {
            let minions = level.getEntities().filter(e => e.tags.contains('ritual_minion') && e.isAlive());
            if (minions.length == 0) {
                boss.removeTag('phase_shielded');
                server.tell("§a§lThe shield has shattered!");
            } else {
                server.getPlayers().forEach(p => p.setStatusMessage(`§cMinions Remaining: ${minions.length} | Boss Health: ${Math.floor(boss.health)}/${boss.maxHealth}`));
            }
        }
    });
});
EntityEvents.spawned(event => {
    if (event.entity.tags.contains('ritual_minion')) {
        event.entity.addPotionEffect('minecraft:glowing', 999999, 0, false, false);
    }
});
EntityEvents.hurt('minecraft:giant', event => {
    if (event.entity.tags.contains('phase_shielded')) {
        event.cancel();
    }
});
EntityEvents.death(event => {
    if (event.entity.tags.contains('ritual_minion')) {
        event.server.scheduleInTicks(10, () => {
            let boss = event.level.getEntities().filter(e => e.tags.contains('ritual_boss') && e.isAlive()).findFirst().orElse(null);
            let minions = event.level.getEntities().filter(e => e.tags.contains('ritual_minion') && e.isAlive());
            if (boss && minions.length == 0) boss.removeTag('phase_shielded');
        });
    }
});
EntityEvents.death(event => {
    let entity = event.entity;
    if (entity.type === 'minecraft:giant' && entity.hasTag('ritual_boss')) {
        let server = event.server;
        server.tell("§4§lThe Zombie Overlord has been defeated! Treasures await the victors!");

        // Custom drops
        // 1. ebonlord_ingot: always 1, then +1 @60%, +1 @20%, +1 @10%
        let ingotCount = 1;
        if (Math.random() < 0.6) ingotCount++;
        if (Math.random() < 0.2) ingotCount++;
        if (Math.random() < 0.1) ingotCount++;
        entity.spawnAtLocation(Item.of('threateningly_mobs:ebonlord_ingot', ingotCount));

        // 2. heart_crystal: 40%
        if (Math.random() < 0.4) {
            entity.spawnAtLocation('heart_crystals:heart_crystal');
        }

        // 3. bettle_great_sword: 20%
        if (Math.random() < 0.2) {
            entity.spawnAtLocation('threateningly_mobs:bettle_great_sword');
        }

        // 4. firebird_spawn_egg: 50%
        if (Math.random() < 0.5) {
            entity.spawnAtLocation('Mythicmounts:firebird_spawn_egg');
        }

        // Visual flair on death
        event.level.spawnParticles('minecraft:explosion', true, entity.x, entity.y + 5, entity.z, 5, 5, 5, 20, 0.2);
    }
});