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



export function initDog() {

    
    const chance = 1 / 180; 
    const forebodingCheck = fo.scoreChapter4; 
    const checkInterval = 1200; 

    const DOG_NAMES = ["Eurylochus", "Odysseus", "Bella", "Charlie", "Luna", "Coco", "Rocky", "Chiquis", "Médor", "Fifi", "Rex", "Loulou", "Karabaş", "Zeytin", "Paşa", "Duman", "Шарик", "Барсик", "Лайка", "Рекс", "小白", "旺财", "大黄", "拉奇", "ポチ", "たろう", "さくら", "こたろう", "Мурко", "Пух", "فوفو", "لولو", "سلطان", "كلبى", "Roki", "Sisu", "Taika", "رعد", "فهد", "زيزو"];
    let dogSpawned = false;
    let playerTriggered = false; 
    let eventFlag = false


    
    function attemptSpawnDog() {
        const wolves = fo.overworld.getEntities({ type: "minecraft:wolf" });
        const existingDog = wolves.some(wolf => DOG_NAMES.includes(wolf.nameTag));
        if (dogSpawned || existingDog) return; 

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

        if (eventFlag === true) { 
            const players = fo.overworld.getPlayers();
            if (players.length === 0) return;

            const player = players[Math.floor(Math.random() * players.length)]; 
            const nearbyVillages = fo.overworld.getEntities({
                type: "minecraft:villager",
                location: player.location,
                minDistance: 32,
                maxDistance: 120
            });

            if (nearbyVillages.length > 0) {
                const village = nearbyVillages[Math.floor(Math.random() * nearbyVillages.length)];
                
                const randomName = DOG_NAMES[Math.floor(Math.random() * DOG_NAMES.length)];
                
                fo.overworld.runCommand(`summon wolf ${village.location.x} ${village.location.y} ${village.location.z} ~ ~ minecraft:on_tame ${randomName}`);
                system.runTimeout(() => { fo.overworld.runCommand(`execute as @e [type=wolf, name=${randomName}, c=1] run spreadplayers ~ ~ 1 10 @s ~3`) }, 1)

                dogSpawned = true;
                playerTriggered = false; 
                

            }
        }
    }

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

    
    function trackDogProximity() {
        const wolves = fo.overworld.getEntities({ type: "minecraft:wolf" });
        const namedWolf = wolves.find(wolf => DOG_NAMES.includes(wolf.nameTag));

        if (!namedWolf) return;

        const players = fo.overworld.getPlayers({
            location: namedWolf.location,
            maxDistance: 60,
        });
        let anyPlayerNearby = false;

        for (const player of players) {
            const distance = getDistance(player.location, namedWolf.location);

            if (!playerTriggered && distance <= 5) {
                playerTriggered = true; 
                
            }

            if (distance <= 60) {
                anyPlayerNearby = true;
            }

        }

        
        if (playerTriggered && !anyPlayerNearby) {
            namedWolf.remove();
            playerTriggered = false;
            
        }
    }



    
    system.runInterval(attemptSpawnDog, checkInterval);
    
    system.runInterval(trackDogProximity, 20);

}

