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


export function initTorch() {

    const CHECK_INTERVAL = 6000; 
    const EVENT_CHANCE = 1 / 24; 
    const forebodingCheck = fo.scoreChapter4; 
    const TORCH_RADIUS = 52; 
    const MIN_PLAYER_DISTANCE = 40; 
    const DESTROY_RADIUS = 32; 


    
    const TORCH_LOCATIONS_KEY = "torchLocations";

    
    function saveTorchLocations(torchLocations) {
        world.setDynamicProperty(TORCH_LOCATIONS_KEY, JSON.stringify([...torchLocations]));
    }

    
    function loadTorchLocations() {
        let torchData = world.getDynamicProperty(TORCH_LOCATIONS_KEY);
        if (torchData) {
            return new Map(JSON.parse(torchData));
        }
        return new Map();
    }

    
    let activeTorches = loadTorchLocations();

    

    function tryTriggerEvent() {

        if (fo.forebodingScore >= forebodingCheck && Math.random() < (EVENT_CHANCE * fo.netProbabilityModifier)) {
            
            placeTorchNearRandomPlayer();
        } else {
            
        }
    }

    function removeTorches() {
        if (fo.forebodingScore >= 1) {
            checkPlayersNearTorches();
        }
    }

    function placeTorchNearRandomPlayer() {
        const players = fo.overworld.getPlayers();
        if (players.length === 0) system.runTimeout(placeTorchNearRandomPlayer, 1308);

        const player = players[Math.floor(Math.random() * players.length)];
        const playerPos = player.location;

        let attempts = 0;
        const MAX_ATTEMPTS = 15; 

        while (attempts < MAX_ATTEMPTS) {
            
            let torchPos = {
                x: playerPos.x + Math.floor(Math.random() * TORCH_RADIUS * 2) - TORCH_RADIUS,
                z: playerPos.z + Math.floor(Math.random() * TORCH_RADIUS * 2) - TORCH_RADIUS
            };

            

            
            let isValidPosition = true;
            for (let p of players) {
                let dx = p.location.x - torchPos.x;
                let dz = p.location.z - torchPos.z;
                let distance = Math.sqrt(dx * dx + dz * dz);

                if (distance < MIN_PLAYER_DISTANCE) {
                    isValidPosition = false;
                    break;
                }
            }

            if (!isValidPosition) {
                attempts++;
                continue; 
            }

            
            const topmostBlock = fo.overworld.getTopmostBlock({ x: torchPos.x, z: torchPos.z }, 260);

            if (topmostBlock && !topmostBlock.isLiquid) {
                
                torchPos.y = topmostBlock.y + 1;
                const block = fo.overworld.getBlock(torchPos);

                if (block && block.isAir) {
                    block.setType("minecraft:torch");
                    activeTorches.set(`${torchPos.x},${torchPos.y},${torchPos.z}`, torchPos);
                    saveTorchLocations(activeTorches); 
                    
                    return; 
                } else {
                    
                }
            } else {
                
            }

            attempts++;
        }

        system.runTimeout(placeTorchNearRandomPlayer, 1308)
        
    }

    function checkPlayersNearTorches() {
        const players = fo.overworld.getPlayers();

        for (let [key, torchPos] of activeTorches.entries()) {
            for (let player of players) {
                let dx = player.location.x - torchPos.x;
                let dy = player.location.y - torchPos.y;
                let dz = player.location.z - torchPos.z;
                let distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

                if (distance < DESTROY_RADIUS) {
                    let block = fo.overworld.getBlock(torchPos);
                    if (block && block.typeId === "minecraft:torch") {
                        block.setType("minecraft:air");

                        
                        const torchItem = new ItemStack("torch", 1);
                        fo.overworld.spawnItem(torchItem, torchPos);

                        fo.overworld.playSound("dig.wood", torchPos, { volume: 2, pitch: Math.random() < 0.5 ? 0.8 : 1 })

                        
                    }
                    activeTorches.delete(key);
                    saveTorchLocations(activeTorches); 
                    break;
                }
            }
        }
    }

    system.runInterval(tryTriggerEvent, CHECK_INTERVAL);
    system.runInterval(removeTorches, 20);

};