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

export function initJukeboxHaunted() {

    
    const JUKEBOX_LIST_PROPERTY = "jukebox_locations"; 
    const SOUND_NAME = "excuse"; 
    const PLAYER_RADIUS = 64; 
    const CHECK_INTERVAL = 2400; 

    const chance = 1 / 60; 
    const forebodingCheck = fo.scoreChapter3; 
    const interval = 4800; 

    let eventflag = false; 

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

    
    function getDistance(pos1, pos2) {
        if (!pos1 || !pos2) {
            return Infinity; 
        }
        return Math.sqrt(
            Math.pow(pos1.x - pos2.x, 2) +
            Math.pow(pos1.y - pos2.y, 2) +
            Math.pow(pos1.z - pos2.z, 2)
        );
    }

    
    let activeJukebox = null;

    
    world.afterEvents.playerPlaceBlock.subscribe((event) => {
        const block = event.block;

        if (block.typeId === "minecraft:jukebox") {
            const jukeboxLocations = JSON.parse(world.getDynamicProperty(JUKEBOX_LIST_PROPERTY) || "[]");
            const jukeboxPos = roundCoordinates(block.location);

            
            if (!jukeboxLocations.some(loc => loc.x === jukeboxPos.x && loc.y === jukeboxPos.y && loc.z === jukeboxPos.z)) {
                jukeboxLocations.push(jukeboxPos);
                world.setDynamicProperty(JUKEBOX_LIST_PROPERTY, JSON.stringify(jukeboxLocations));
                
            } else {
                
            }
        }
    });

    
    world.afterEvents.playerInteractWithBlock.subscribe((event) => {
        const block = event.block;

        if (block.typeId === "minecraft:jukebox") {
            const jukeboxPos = roundCoordinates(block.location);

            
            if (activeJukebox && jukeboxPos.x === activeJukebox.x && jukeboxPos.y === activeJukebox.y && jukeboxPos.z === activeJukebox.z) {
                stopSound(jukeboxPos);
            }
        }
    });

    
    world.beforeEvents.playerBreakBlock.subscribe((event) => {
        const block = event.block;

        if (block.typeId === "minecraft:jukebox") {
            const jukeboxLocations = JSON.parse(world.getDynamicProperty(JUKEBOX_LIST_PROPERTY) || "[]");
            const jukeboxPos = roundCoordinates(block.location);

            
            const updatedLocations = jukeboxLocations.filter(loc => !(loc.x === jukeboxPos.x && loc.y === jukeboxPos.y && loc.z === jukeboxPos.z));
            world.setDynamicProperty(JUKEBOX_LIST_PROPERTY, JSON.stringify(updatedLocations));
            

            
            if (activeJukebox && jukeboxPos.x === activeJukebox.x && jukeboxPos.y === activeJukebox.y && jukeboxPos.z === activeJukebox.z) {
                stopSound(jukeboxPos);
            }
        }
    });

    
    function playSoundAtJukebox(jukeboxPos) {
        const overworld = fo.overworld;
        const block = overworld.getBlock(jukeboxPos);

        if (!block || block.typeId !== "minecraft:jukebox") {
            
            const jukeboxLocations = JSON.parse(world.getDynamicProperty(JUKEBOX_LIST_PROPERTY) || "[]");
            const updatedLocations = jukeboxLocations.filter(loc => !(loc.x === jukeboxPos.x && loc.y === jukeboxPos.y && loc.z === jukeboxPos.z));
            world.setDynamicProperty(JUKEBOX_LIST_PROPERTY, JSON.stringify(updatedLocations));
            
            return;
        }

        
        const recordPlayer = block.getComponent("minecraft:record_player");
        if (recordPlayer && recordPlayer.isPlaying()) {
            recordPlayer.ejectRecord();
            
        }

        
        overworld.playSound(SOUND_NAME, jukeboxPos, { volume: 6 });
        

        
        activeJukebox = jukeboxPos;

    }

    
    function stopSound(jukeboxPos) {
        fo.overworld.runCommand(`execute positioned ${jukeboxPos.x} ${jukeboxPos.y} ${jukeboxPos.z} run stopsound @a ${SOUND_NAME}`);
        

        
        activeJukebox = null;

    }

    
    function checkForNearbyJukeboxes() {
        const jukeboxLocations = JSON.parse(world.getDynamicProperty(JUKEBOX_LIST_PROPERTY) || "[]");

        if (!Array.isArray(jukeboxLocations) || jukeboxLocations.length === 0) {
            return; 
        }

        const players = world.getPlayers();

        if (!Array.isArray(players)) {
            return; 
        }

        
        const validJukeboxes = jukeboxLocations.filter(jukeboxPos => {
            return players.some(player => {
                const distance = getDistance(player.location, jukeboxPos);
                return distance <= PLAYER_RADIUS;
            });
        });

        if (validJukeboxes.length === 0) {
            return; 
        }

        
        const randomJukebox = validJukeboxes[Math.floor(Math.random() * validJukeboxes.length)];

        
        playSoundAtJukebox(randomJukebox);
        eventflag = false
    };

    
    system.runInterval(() => {
        if (!eventflag && fo.forebodingScore >= forebodingCheck && Math.random() <= (chance * fo.netProbabilityModifier)) {
            eventflag = true
            
        } 

    }, interval);


    
    system.runInterval(() => {

        if (eventflag) {
            checkForNearbyJukeboxes();
        }

    }, CHECK_INTERVAL);

}