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

export function initJukeboxCave() {

    
    const CHECK_INTERVAL = 8407; 
    const EVENT_CHANCE = 1 / 34; 
    const PLACEMENT_RADIUS = 96; 
    const MIN_PLAYER_DISTANCE = 64; 
    const LOCATION_CHECKS = 40; 
    const ForebodingScore = fo.scoreChapter4; 

    let activeJukebox = null; 

    
    function roundCoordinates(location) {
        return {
            x: Math.floor(location.x),
            y: Math.floor(location.y),
            z: Math.floor(location.z)
        };
    }

    
    function tryTriggerEvent() {
        
        if (fo.forebodingScore > ForebodingScore && Math.random() < (EVENT_CHANCE * fo.netProbabilityModifier)) {
            
            placeJukeboxNearRandomPlayer();
        } else {
            
        }
    }

    
    function placeJukeboxNearRandomPlayer() {
        let players = [...world.getPlayers()];
        if (players.length === 0) {
            
            return; 
        }

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

        let locationsChecked = 0;

        while (locationsChecked < LOCATION_CHECKS) {
            
            let jukeboxPos = {
                x: playerPos.x + Math.floor(Math.random() * PLACEMENT_RADIUS * 2) - PLACEMENT_RADIUS,
                z: playerPos.z + Math.floor(Math.random() * PLACEMENT_RADIUS * 2) - PLACEMENT_RADIUS
            };
            

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

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

            if (!isValidPosition) {
                
                continue; 
            }

            
            locationsChecked++;
            

            
            let dimension = fo.overworld;
            let foundValidSpot = false;

            for (let y = 10; y >= -50; y--) {
                let block = dimension.getBlock({ x: jukeboxPos.x, y: y, z: jukeboxPos.z });
                let blockAbove = dimension.getBlock({ x: jukeboxPos.x, y: y + 1, z: jukeboxPos.z });

                if (block && blockAbove) {
                    
                    if (!block.isAir && !block.isLiquid && blockAbove.isAir) {
                        jukeboxPos.y = y + 1; 
                        foundValidSpot = true;
                        
                        break;
                    }
                }
            }

            if (foundValidSpot) {
                
                let block = dimension.getBlock(jukeboxPos);
                if (block && block.isAir) {
                    block.setPermutation(BlockPermutation.resolve("minecraft:jukebox"));
                    
                    playSoundAtJukebox(jukeboxPos); 
                    return; 
                } else {
                    
                }
            } else {
                
            }
        }

        
    }

    
    function playSoundAtJukebox(location) {
        
        fo.overworld.playSound("excuse", location, { volume: 8 });
        activeJukebox = roundCoordinates(location); 
    }

    
    function stopSound(location) {
        const roundedLocation = roundCoordinates(location); 
        if (
            activeJukebox &&
            roundedLocation.x === activeJukebox.x &&
            roundedLocation.y === activeJukebox.y &&
            roundedLocation.z === activeJukebox.z
        ) {
            
            fo.overworld.runCommand(`execute positioned ${activeJukebox.x} ${activeJukebox.y} ${activeJukebox.z} run stopsound @a excuse`);
            activeJukebox = null;
        } else {
            
        }
    }

    
    world.afterEvents.playerInteractWithBlock.subscribe((event) => {
        if (event.block.typeId === "minecraft:jukebox") {
            
            stopSound(event.block.location); 
        }
    });

    
    world.beforeEvents.playerBreakBlock.subscribe((event) => {
        if (event.block.typeId === "minecraft:jukebox") {
            
            stopSound(event.block.location); 
        }
    });

    
    system.runInterval(tryTriggerEvent, CHECK_INTERVAL);

}