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







export function initP82() {

    
    let
        saved = world.getDynamicProperty("P82Data"),
        P82Data = saved ? JSON.parse(saved) : {
            isPresent: Math.random() < (1 / 5) ? true : false,
            intensity: Math.floor(Math.random() * 3) + 1,
            bookCheck: false,
            bookActive: false,
            bookGiven: false,
        };

    

    saveProgress(P82Data)

    if (!P82Data.isPresent) return;
    const
        checkInterval = 2997, 
        isOnline = world.scoreboard.getObjective("Online").hasParticipant("Pilot1782");

    if (isOnline) {
        system.runTimeout(() => { initP82() }, checkInterval)
        return;
    }

    const
        forebodingScoreCheck3 = fo.scoreChapter3,
        forebodingScoreCheck4 = fo.scoreChapter4,
        forebodingScoreCheck5 = fo.scoreChapter5,
        forebodingScore = fo.forebodingScore;

    if (forebodingScore > forebodingScoreCheck5 && !P82Data.bookCheck) giveBook(P82Data, 0.33); 

    if (forebodingScore > forebodingScoreCheck3 && forebodingScore < forebodingScoreCheck5) {
        const P82EventChance = 1 / 192; 

        if (Math.random() > (P82EventChance * P82Data.intensity)) {
            system.runTimeout(() => { initP82(); }, checkInterval)
            return;
        };

        const
            overworld = fo.overworld,
            activeP82Stalkers = overworld.getEntities({
                type: "fo:forebearer",
                name: "Pilot1782"
            });

        if (activeP82Stalkers.length > 0) {
            system.runTimeout(() => { initP82() }, checkInterval)
            return;
        }

        const roll = Math.random() * 100;

        if (roll < 80) {
            logInOut();
        } else if (roll < 95 && forebodingScore > forebodingScoreCheck4) { 
            intenseLogInOut();
        } else { 
            P82Stalking(checkInterval, overworld);

            world.scoreboard.getObjective("Online").addScore("Pilot1782", 0) 

            world.sendMessage({
                translate: "Fo.PhantomPlayer01",
                with: [`Pilot1782`]
            });
        }


    }

    system.runTimeout(() => { initP82() }, checkInterval)
};


function logInOut() {
    world.sendMessage({
        translate: "Fo.PhantomPlayer01",
        with: [`Pilot1782`]
    });

    world.scoreboard.getObjective("Online").addScore("Pilot1782", 0) 

    const randomLogOffDelay = Math.max(Math.floor(Math.random() * 18000), 3002); 

    if (Math.random() < 0.1) { 
        const deathMessageDelay = Math.max(Math.floor(Math.random() * (randomLogOffDelay - 1200)), 123); 

        system.runTimeout(() => {
            const messages = [
                { translate: "Fo.PhantomPlayer04a", with: ["Pilot1782"] },
                { translate: "Fo.PhantomPlayer04b", with: ["Pilot1782"] },
                { translate: "Fo.PhantomPlayer04d", with: ["Pilot1782"] },
                { translate: "Fo.PhantomPlayer04e", with: ["Pilot1782"] }
            ];

            
            const msg = messages[Math.floor(Math.random() * messages.length)];

            world.sendMessage(msg);

        }, deathMessageDelay)
    };

    system.runTimeout(() => {
        world.scoreboard.getObjective("Online").removeParticipant("Pilot1782"); 
        world.sendMessage({
            translate: "Fo.PhantomPlayer03",
            with: [`Pilot1782`]
        });
    }, randomLogOffDelay)

}

function intenseLogInOut() {
    world.sendMessage({
        translate: "Fo.PhantomPlayer01",
        with: [`Pilot1782`]
    });

    world.scoreboard.getObjective("Online").addScore("Pilot1782", 0) 
    const randomLogOffDelay = Math.max(Math.floor(Math.random() * 220), 38); 

    system.runTimeout(() => {
        world.scoreboard.getObjective("Online").removeParticipant("Pilot1782"); 
        world.sendMessage({
            translate: "Fo.PhantomPlayer03",
            with: [`Pilot1782`]
        });

        const randomLogInDelay = Math.max(Math.floor(Math.random() * 220), 38); 

        if (Math.random() <= 0.9) {
            system.runTimeout(() => {
                intenseLogInOut();
            }, randomLogInDelay);
        };

    }, randomLogOffDelay);

}

function P82Stalking(checkInterval, overworld) {
    const overworldPlayers = overworld.getPlayers();

    if (overworldPlayers.length === 0) {
        system.runTimeout(() => {
            P82Stalking(checkInterval, overworld);
        }, checkInterval)
    };

    const surfacePlayers = [...overworldPlayers].filter(player => player.location.y > 60); 
    if (surfacePlayers.length !== 0) {
        P82StalkerSpawn(overworld, surfacePlayers, true);
        return;
    }

    const undergroundPlayers = [...overworldPlayers].filter(player => player.location.y < 35); 
    if (undergroundPlayers.length !== 0) {
        P82StalkerSpawn(overworld, undergroundPlayers, false);
        return;
    }

    system.runTimeout(() => {
        P82Stalking(checkInterval, overworld);
    }, checkInterval)
};

function P82StalkerSpawn(overworld, players, surface) {
    const maxHeight = surface ? 50 : 80;

    const
        player = players[Math.floor(Math.random() * players.length)], 
        playerLoc = player.location

    const spawnLoc = {
        x: playerLoc.x + (Math.random() * 20 - 10),
        y: playerLoc.y,
        z: playerLoc.z + (Math.random() * 20 - 10),
    };

    overworld.runCommand(`summon fo:forebearer Pilot1782 ${spawnLoc.x} ${spawnLoc.y} ${spawnLoc.z}`);

    system.runTimeout(() => {
        const P82Stalker = overworld.getEntities({
            type: "fo:forebearer",
            name: "Pilot1782"
        })[0];

        const randomLogOffDelay = Math.floor(Math.random() * 1200 + 1220); 

        system.runTimeout(() => {

            world.scoreboard.getObjective("Online").removeParticipant("Pilot1782"); 
            world.sendMessage({
                translate: "Fo.PhantomPlayer03",
                with: [`Pilot1782`]
            });

            try {
                P82Stalker.remove();
            } catch { }
        }, randomLogOffDelay);
    }, 1)

}


function giveBook(P82Data, bookChance) {
    if (Math.random() < bookChance) {
        P82Data.bookActive = true;
    }
    P82Data.bookCheck = true;
    saveProgress(P82Data)
}




function saveProgress(P82Data) {
    world.setDynamicProperty("P82Data", JSON.stringify(P82Data));
}

