import { world, system } from "@minecraft/server";
import { fo } from './utilities/fo_constants.js';


export function initVoidEncounter() {
    
    const
        foreboding = fo.forebodingObjective,
        villageCenter = { x: 400512, y: 2, z: 400528 }, 
        BORDER_RADIUS = 520,
        CHEST_POSITION = { x: 400512, y: 7, z: 400561 },
        LADDER_POSITION = { x: 400513, y: 5, z: 400563 },
        DOOR_POSITION = { x: 400514, y: 2, z: 400558 },
        SPAWN_POSITION = { x: 400514.5, y: 2, z: 400559.5 },
        theEnd = fo.theEnd,
        overworld = fo.overworld,
        BOOK_ID = "minecraft:written_book",
        PUMPKIN_HELMET = "carved_pumpkin";

    let eventPhase = 0;

    
    function chestHasBook(chest) {
        const container = chest.getComponent("inventory").container;
        for (let i = 0; i < container.size; i++) {
            const item = container.getItem(i);
            if (item?.typeId === BOOK_ID) {
                
                return true;

            }
        }
        return false;
    }

    
    function playerHasBook(player) {
        const inventory = player.getComponent("inventory").container;
        for (let i = 0; i < inventory.size; i++) {
            const item = inventory.getItem(i);
            if (item?.typeId === BOOK_ID) {
                
                return true;

            }
        }
        return false;
    }

    
    function populateChest(chest) {
        const container = chest.getComponent("inventory").container;
        const lootTable = "foForgiveme";

        
        for (let slot = 0; slot < container.size; slot++) {
            const item = container.getItem(slot);
            if (!item) {
                
                theEnd.runCommand(`loot replace block ${CHEST_POSITION.x} ${CHEST_POSITION.y} ${CHEST_POSITION.z} slot.container ${slot} loot ${lootTable}`)
                
                return;
            }
        }
    }

    
    world.afterEvents.playerInteractWithBlock.subscribe((event) => {
        const { block, player } = event;

        
        if (block.location.x === CHEST_POSITION.x &&
            block.location.y === CHEST_POSITION.y &&
            block.location.z === CHEST_POSITION.z &&
            block.dimension.id === "minecraft:the_end") {

            

            if (eventPhase === 0) { eventPhase++ }

            
            if (!chestHasBook(block) && !playerHasBook(player)) {
                
                system.runTimeout(() => {
                    populateChest(block);

                    player.playMusic("phurpa", {
                        fade: 10,
                        loop: true,
                        volume: 0.01,
                    }); 
                    
                }, 1); 
            }
        }
    });

    

    
    function teleportPlayerBack(player) {
        let originalD = player.getDynamicProperty("dimension");
        let dimensionId = world.getDimension(originalD);
        let originalPos = player.getDynamicProperty("saved_position");
        system.runTimeout(() => {

            if (originalPos !== undefined || originalD !== undefined) {
                player.teleport(originalPos, { dimension: dimensionId });
                player.setDynamicProperty("hasBeenTeleported", false);
            } else { 
                
                player.teleport({ x: 0, y: 280, z: 0 }, { dimension: overworld });
                
                system.runTimeout(() => {
                    const playerLocation = player.location;
                    const dimension = player.dimension;

                    
                    let targetY = playerLocation.y - 1;

                    
                    while (targetY >= -64) { 
                        const blockBelow = dimension.getBlock({
                            x: playerLocation.x,
                            y: targetY,
                            z: playerLocation.z
                        });

                        
                        if (!blockBelow?.isAir) {
                            
                            player.teleport({ x: playerLocation.x, y: targetY + 1, z: playerLocation.z });
                            break; 
                        }

                        
                        targetY -= 1;
                    }
                }, 10);


            }
        }, 1)
    }

    
    function spawnScaryArmorStand() {
        try {
            const IT = theEnd.spawnEntity("minecraft:armor_stand", SPAWN_POSITION);
            IT.addEffect("invisibility", 99999);
            IT.nameTag = "Foredoom";

            const tpInterval = system.runInterval(() => {
                theEnd.runCommand(`tp @e[type=armor_stand,name=Foredoom] ${SPAWN_POSITION.x} ${SPAWN_POSITION.y} ${SPAWN_POSITION.z} facing @p`);
            }, 1)

            
            system.runTimeout(() => { theEnd.playSound("ambient.cave", SPAWN_POSITION) }, 15)

            theEnd.runCommand(`replaceitem entity @e[type=armor_stand,name=Foredoom] slot.armor.head 0 ${PUMPKIN_HELMET}`);

            

            system.runTimeout(() => {
                
                system.clearRun(tpInterval);
                IT.remove();

                
                theEnd.runCommand(`deop @a`) 

                system.runTimeout(() => {
                    const visitors = theEnd.getPlayers({
                        location: villageCenter,
                        maxDistance: BORDER_RADIUS
                    });

                    const targetVisitor = visitors[0]; 

                    for (let visitor of visitors) {

                        teleportPlayerBack(visitor)
                    }

                    
                    foreboding.setScore("Counter ", -72000); 


                    system.runTimeout(() => {

                        
                        const viewDirection = targetVisitor.getViewDirection();

                        
                        const distance = 6 + Math.random() * 12; 
                        const thunderPos = {
                            x: targetVisitor.location.x + viewDirection.x * distance,
                            y: targetVisitor.location.y + viewDirection.y * distance,
                            z: targetVisitor.location.z + viewDirection.z * distance,
                        };
                        const thunderblock = overworld.getTopmostBlock(thunderPos, 40)
                        const thunderblockAbove = {
                            x: thunderblock.x,
                            y: thunderblock.y + 1,
                            z: thunderblock.z,
                        };

                        overworld.spawnEntity("minecraft:lightning_bolt", thunderblockAbove);
                        overworld.runCommand(`kick @a [scores={Random=..1}] ᛃᚨᛉ`)
                        world.playMusic("phurpa", { fade: 10, loop: true, volume: 0.01, });

                    }, 95)

                }, 1)

            }, 100)

        } catch (error) {
            console.error("Error spawning armor stand:", error);
        }
    }

    function openDoor() {

        
        const block = theEnd.getBlock(DOOR_POSITION);
        if (block.typeId !== "minecraft:spruce_door") return;

        const isClosed = !block.permutation.getState("open_bit"); 

        if (isClosed) {
            
            const doorPermutation = block.permutation.withState("open_bit", true);
            block.setPermutation(doorPermutation);
            theEnd.playSound("random.door_open", block.location, { volume: 2 });
        } else {
            
            const doorPermutation = block.permutation.withState("open_bit", false);
            block.setPermutation(doorPermutation);
            theEnd.playSound("random.door_close", block.location, { volume: 2 });
        }

    }

    
    system.runInterval(() => {
        if (eventPhase !== 1) return; 

        const playersNearLadder = theEnd.getPlayers({
            location: LADDER_POSITION,
            maxDistance: 2,
            minDistance: 0
        });

        if (playersNearLadder.length > 0) {
            
            openDoor();
            spawnScaryArmorStand();
            eventPhase++; 
        }
    }, 6); 

}