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



export function initRandomTorch() {

    
    const TORCH_LIST_PROPERTY = "torch_locations";
    const INTERVAL_CHECK = 3613; 
    const INTERVAL_RUN = 1800;   
    const FOREBODING_THRESHOLD = fo.scoreChapter3;
    const CHANCE = 1 / 40; 

    let eventFlag = false;

    function getDistance(a, b) {
        return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2);
    }

    
    function destroyRandomTorch() {
        const allTorches = JSON.parse(world.getDynamicProperty(TORCH_LIST_PROPERTY) || "[]");
        if (!Array.isArray(allTorches) || allTorches.length === 0) return;

        const overworld = fo.overworld;
        const allPlayers = overworld.getPlayers();
        const undergroundPlayers = allPlayers.filter(p => p.location.y < 30);
        if (undergroundPlayers.length === 0) return;

        const validTorches = allTorches.filter(torchPos => {
            let nearUnderground = false;
            for (const p of undergroundPlayers) {
                if (getDistance(p.location, torchPos) <= 64) {
                    nearUnderground = true;
                    break;
                }
            }

            if (!nearUnderground) return false;

            for (const p of allPlayers) {
                if (getDistance(p.location, torchPos) < 32) {
                    return false;
                }
            }

            return true;
        });

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

        const selected = validTorches[Math.floor(Math.random() * validTorches.length)];
        const block = overworld.getBlock(selected);

        if (!block || block.typeId !== "minecraft:torch") {
            
            const cleaned = allTorches.filter(p => !(p.x === selected.x && p.y === selected.y && p.z === selected.z));
            world.setDynamicProperty(TORCH_LIST_PROPERTY, JSON.stringify(cleaned));
            return;
        }

        block.setType("minecraft:air");
        overworld.spawnItem(new ItemStack("minecraft:torch", 1), block.location);
        overworld.playSound("dig.wood", block.location, { volume: 2, pitch: Math.random() < 0.5 ? 0.8 : 1 })

        const cleaned = allTorches.filter(p => !(p.x === selected.x && p.y === selected.y && p.z === selected.z));
        world.setDynamicProperty(TORCH_LIST_PROPERTY, JSON.stringify(cleaned));

        eventFlag = false;
    }

    
    system.runInterval(() => {

        if (!eventFlag && fo.forebodingScore >= FOREBODING_THRESHOLD) {
            if (Math.random() < CHANCE * fo.netProbabilityModifier) {
                eventFlag = true;
            }
        }
    }, INTERVAL_CHECK);

    
    system.runInterval(() => {
        if (eventFlag) destroyRandomTorch();
    }, INTERVAL_RUN);

}