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


export function initPhantomFriend() {

    
    const MIN_PLAYERS_FOR_EVENT = 2; 
    const MIN_PLAYTIME_TICKS = 576000; 
    const WAIT_TIME_TICKS = 6000; 
    const MESSAGE_DELAY_TICKS = 400; 

    const forebodingCheck = 1; 
    const forebodingCheck2 = fo.scoreChapter4; 

    
    const PLAYER_NAMES_PROPERTY = "player_names"; 
    const PLAYTIME_PROPERTY = "playtime"; 
    const EVENT_RAN_PROPERTY = "event_ran"; 

    
    const MESSAGE_KEYS = [
        "Fo.PhantomPlayer01",
        "Fo.PhantomPlayer02",
        "Fo.PhantomPlayer03"
    ];

    
    function debugLog(message) {
        world.sendMessage(`[Debug] ${message}`);
    }

    
    function initializeProperties() {
        if (!world.getDynamicProperty(PLAYER_NAMES_PROPERTY)) {
            world.setDynamicProperty(PLAYER_NAMES_PROPERTY, JSON.stringify([])); 
        }
        if (!world.getDynamicProperty(PLAYTIME_PROPERTY)) {
            world.setDynamicProperty(PLAYTIME_PROPERTY, 0); 
        }
        if (!world.getDynamicProperty(EVENT_RAN_PROPERTY)) {
            world.setDynamicProperty(EVENT_RAN_PROPERTY, false); 
        }
    }

    
    function trackPlayersAndPlaytime() {
        const players = world.getPlayers();
        const playerNames = players.map(player => player.name);

        
        world.setDynamicProperty(PLAYER_NAMES_PROPERTY, JSON.stringify(playerNames));

        
        if (players.length >= MIN_PLAYERS_FOR_EVENT && fo.forebodingScore >= forebodingCheck) {
            let playtime = world.getDynamicProperty(PLAYTIME_PROPERTY) || 0;
            playtime += 20; 
            world.setDynamicProperty(PLAYTIME_PROPERTY, playtime);
            
        }

        
    }

    
    world.beforeEvents.playerLeave.subscribe((event) => {
        const playerName = event.playerName;
        const playersOnline = world.getPlayers().length;
        const playtime = world.getDynamicProperty(PLAYTIME_PROPERTY) || 0;

        

        
        if (playtime >= MIN_PLAYTIME_TICKS && playersOnline === 2 && fo.forebodingScore >= forebodingCheck2) {
            
            if (world.getDynamicProperty(EVENT_RAN_PROPERTY)) {
                
                return;
            }

            const playerNames = JSON.parse(world.getDynamicProperty(PLAYER_NAMES_PROPERTY)) || [];

            system.runTimeout(() => {
                const onlinePlayer = world.getPlayers()[0].name;

                
                const offlinePlayers = playerNames.filter(name => name !== onlinePlayer);

                if (offlinePlayers.length > 0) {
                    
                    const selectedPlayer = offlinePlayers[Math.floor(Math.random() * offlinePlayers.length)];
                    

                    
                    system.runTimeout(() => sendMessages(selectedPlayer), WAIT_TIME_TICKS);
                } else {
                    
                }
            }, 20);
        }
    });

    
    world.afterEvents.playerJoin.subscribe((event) => {
        const playerName = event.playerName;
        

        
        if (trackedPlayer && trackedPlayer === playerName) {
            
            
            world.sendMessage({
                translate: MESSAGE_KEYS[2],
                with: [playerName] 
            });
            
            trackedPlayer = null;
        }

    });

    
    let trackedPlayer = null;

    
    async function sendMessages(playerName) {
        trackedPlayer = playerName; 
        

        
        world.setDynamicProperty(EVENT_RAN_PROPERTY, true);
        

        for (let i = 0; i < 3; i++) {
            if (!trackedPlayer) {
                
                break; 
            }
            
            world.sendMessage({
                translate: MESSAGE_KEYS[i],
                with: [playerName] 
            });
            
            await new Promise(resolve => system.runTimeout(resolve, MESSAGE_DELAY_TICKS));
        }

        
        trackedPlayer = null;
        

    }

    
    initializeProperties();

    
    system.runInterval(trackPlayersAndPlaytime, 20);

};