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



export function initVoidShiaSurprise() { 

    
    const
        markObjective = world.scoreboard.getObjective("Random"),
        altarCoords = { x: 400501.5, y: 4, z: 400484.5 },
        theEnd = fo.theEnd;

    const WORLD_GEN_PROGRESS_PROPERTY = "worldGenProgress";

    let
        teleportFlag = false,
        timer = 0,
        interactionSubscription = null;

    
    function getWorldGenProgress() {
        const worldGenProgressData = world.getDynamicProperty(WORLD_GEN_PROGRESS_PROPERTY);
        return worldGenProgressData ? JSON.parse(worldGenProgressData) : false;
    }

    
    function monitorSleepState(player) {
        const maxWaitTicks = 400; 
        let ticksWaited = 0;

        const checkInterval = system.runInterval(() => {
            if (!player.isSleeping) {
                system.run(() => {
                    
                    
                    
                    player.setDynamicProperty("dimension", player.dimension.id);
                    player.setDynamicProperty("saved_position", {
                        x: player.location.x,
                        y: player.location.y,
                        z: player.location.z
                    });
                    
                    player.setDynamicProperty("hasBeenTeleported", true);

                    
                    player.runCommand(`execute in the_end run tp @s ${altarCoords.x} ${altarCoords.y} ${altarCoords.z} facing ${altarCoords.x} ${altarCoords.y + 10} ${altarCoords.z}`)
                    

                    system.runTimeout(() => { 

                        if (world.gameRules.showCoordinates) { 
                            world.gameRules.showCoordinates = false;
                        }
                        if (world.gameRules.respawnBlocksExplode) { 
                            world.gameRules.respawnBlocksExplode = false;
                        }

                        player.runCommand(`fog @s push foreboding:fog08ub Fog`);
                    }, 6)

                });

                
                system.clearRun(checkInterval);
            } else if (ticksWaited >= maxWaitTicks) {
                
                system.clearRun(checkInterval);
                

                
                teleportFlag = true;
                subscribeToBedInteraction();
            }
            ticksWaited++;
        }, 1); 
    }

    
    function subscribeToBedInteraction() {
        if (!interactionSubscription) {
            interactionSubscription = world.afterEvents.playerInteractWithBlock.subscribe((event) => {
                const markedScore = markObjective.getScore(event.player)

                if (event.block?.typeId === "minecraft:bed" && markedScore >= 1) {
                    

                    system.runTimeout(() => {
                        if (event.player.isSleeping) {
                            

                            
                            
                            monitorSleepState(event.player);

                            
                            teleportFlag = false;
                            unsubscribeFromBedInteraction();
                        }
                    }, 90);
                }
            });

        }
    }

    
    function unsubscribeFromBedInteraction() {
        if (interactionSubscription) {
            world.afterEvents.playerInteractWithBlock.unsubscribe(interactionSubscription);
            interactionSubscription = null;
        }
    }

    
    
    system.runInterval(() => {
        if (fo.forebodingScore !== -1 || timer >= 45) return; 

        timer = timer + 1 

        if (timer >= 45) {
            const worldGenProgress = getWorldGenProgress();
            const allMirrorProcessed = worldGenProgress?.mirror;
            if (!allMirrorProcessed) return;

            teleportFlag = true;
            subscribeToBedInteraction();
            
        }

    }, 1197)

}