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



export function initSaddledHorse() {

    
    const chance = 1 / 300; 
    const forebodingCheck = fo.scoreChapter3; 

    
    let eventComplete = false; 

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

    
    function isHorseFarFromAllPlayers(horse) {
        const players = world.getPlayers({ dimension: horse.dimension });

        
        return players.every(player => getDistance(player.location, horse.location) >= 32);
    }

    
    function saddleHorse(entity) {
        const steed = entity;

        
        steed.triggerEvent("minecraft:horse_saddled");
        steed.triggerEvent("minecraft:on_tame");

        
        const movementComponent = steed.getComponent("minecraft:movement");
        if (movementComponent) {
            
            movementComponent.setCurrentValue(0.4); 
        }

        

    }

    
    world.afterEvents.entitySpawn.subscribe((event) => {
        const entity = event.entity;

        system.runTimeout(() => {

            if (!eventComplete && entity.typeId === "minecraft:horse") {

                const probabilityModifier = Math.min(fo.netProbabilityModifier, 1.5);

                if (fo.forebodingScore > forebodingCheck && Math.random() < (chance * probabilityModifier) && isHorseFarFromAllPlayers(entity)) {

                    saddleHorse(entity);

                    
                    eventComplete = true; 

                }

            }
        }, 1) 
    });

}