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

export function initCounter() {

    
    let cachedProperties = {
        totalDuration: 0,
        endlessMode: false,
        maintainChapter: false,
        afkPause: false
    };
    let cachedPlayers = [];
    let lastPlayerUpdate = 0;

    
    function getDistance(pos1, pos2) {
        const dx = pos1.x - pos2.x;
        const dz = pos1.z - pos2.z;
        return Math.sqrt(dx * dx + dz * dz);
    }

    
    function updateCachedPlayers() {
        cachedPlayers = fo.overworld.getPlayers();
        lastPlayerUpdate = system.currentTick;
    }

    
    function updateCachedProperties() {
        cachedProperties.totalDuration = fo.totalDuration;
        cachedProperties.endlessMode = fo.endlessMode;
        cachedProperties.maintainChapter = fo.maintainChapter;
        cachedProperties.afkPause = fo.afkPause;
    }

    
    function incrementScore(amount = 1) {
        const objective = fo.forebodingObjective;
        if (!objective) return;

        const currentScore = objective.getScore("Counter ") || 0;
        objective.setScore("Counter ", currentScore + amount);
    }

    
    function processMarkedPlayers() {
        const forebodingScore = fo.forebodingScore;
        const markScore = world.scoreboard.getObjective("Random");
        if (!markScore) return;

        const TARGET_POS = { x: 25992, z: 25416 };

        
        if (forebodingScore === -1 || forebodingScore === 0) {
            const markedPlayers = world.getPlayers({
                scoreOptions: [{ objective: "Random", minScore: 100 }]
            });

            for (let player of markedPlayers) {
                markScore.setScore(player, 88);
            }
            return;
        }

        
        if (forebodingScore < fo.scoreChapter4) return;

        
        const playersWithScores = [];
        for (let player of cachedPlayers) {
            const score = markScore.getScore(player);
            if (score !== undefined && score >= 1) {
                playersWithScores.push(player);
            }
        }

        if (playersWithScores.length === 0) return;

        
        for (let player of playersWithScores) {
            const playerPos = player.location;
            const calculatedDistance = getDistance(playerPos, TARGET_POS);
            const distance = calculatedDistance < 276 ?
                Math.max(Math.floor(Math.random() * 1000), 99) :
                calculatedDistance;

            markScore.setScore(player, distance);
        }
    }

    
    function processMainTimer() {
        const { totalDuration, maintainChapter, afkPause, endlessMode } = cachedProperties;
        const forebodingScore = fo.forebodingScore;

        if (cachedPlayers.length === 0 || maintainChapter || afkPause) return;

        
        if (totalDuration === 10) {
            if (forebodingScore >= 72000 && forebodingScore < fo.scoreChapter3) {
                fo.forebodingObjective?.setScore("Counter ", fo.scoreChapter3);
            } else if (forebodingScore >= 359999 && forebodingScore < fo.scoreChapter4) {
                fo.forebodingObjective?.setScore("Counter ", fo.scoreChapter4);
            } else if (forebodingScore >= 1007999 && forebodingScore < fo.scoreChapter5) {
                fo.forebodingObjective?.setScore("Counter ", fo.scoreChapter5);
            }
        } else if (totalDuration === 15) {
            if (forebodingScore >= 107999 && forebodingScore < fo.scoreChapter3) {
                fo.forebodingObjective?.setScore("Counter ", fo.scoreChapter3);
            } else if (forebodingScore >= 539999 && forebodingScore < fo.scoreChapter4) {
                fo.forebodingObjective?.setScore("Counter ", fo.scoreChapter4);
            }
        }

        
        if (forebodingScore > 0 && forebodingScore < fo.scoreChapter6) {
            
            let incrementAmount = 20;

            if (totalDuration === 25 && forebodingScore >= 1043999 && forebodingScore < 1224000) {
                incrementAmount -= 10; 
            } else if (totalDuration === 30 && forebodingScore >= 1007999 && forebodingScore < 1247760) {
                incrementAmount -= 14; 
            }

            incrementScore(incrementAmount);
        }

        
        if (forebodingScore < fo.scoreChapter7) {
            let incrementAmount = 20;
            if (forebodingScore + incrementAmount >= fo.scoreChapter7) incrementAmount = Math.abs(forebodingScore) - 2;
            incrementScore(incrementAmount);
        }

        
        if (forebodingScore >= fo.scoreChapter6 && !endlessMode) {
            fo.overworld.runCommand(`function Fo/FoL5`);
        }
    }

    

    
    system.runInterval(() => {
        updateCachedProperties();
        
        if (system.currentTick - lastPlayerUpdate > 100) { 
            updateCachedPlayers();
        }
    }, 604); 

    
    system.runInterval(() => {
        processMarkedPlayers();
    }, 600);

    
    system.runInterval(() => {
        processMainTimer();
    }, 20); 


}