import { world } from "@minecraft/server";

// List of all entities that should be tamed on spawn
const tameableEntities = new Set([
    "enchanted_paperpets:arcos",
    "enchanted_paperpets:auralis",
    "enchanted_paperpets:blimp",
    "enchanted_paperpets:cloudy",
    "enchanted_paperpets:dinaris",
    "enchanted_paperpets:dunes",
    "enchanted_paperpets:fruit_spirit",
    "enchanted_paperpets:jeppo",
    "enchanted_paperpets:kino",
    "enchanted_paperpets:lapis",
    "enchanted_paperpets:lompy",
    "enchanted_paperpets:mira",
    "enchanted_paperpets:nova",
    "enchanted_paperpets:otto",
    "enchanted_paperpets:shade",
    "enchanted_paperpets:solara",
    "enchanted_paperpets:wando",
    "enchanted_paperpets:zara",
    "enchanted_paperpets:story_book_1",
    "enchanted_paperpets:story_book_2",
    "enchanted_paperpets:story_book_3",
    "enchanted_paperpets:story_book_4",
    "enchanted_paperpets:story_book_5",
    "enchanted_paperpets:story_book_6"
]);

world.afterEvents.entitySpawn.subscribe(({ entity }) => {
    if (tameableEntities.has(entity.typeId)) {
        const tameable = entity.getComponent("minecraft:tameable");
        if (tameable) {
            let closestPlayer = null;
            let minDistance = Infinity;

            for (const player of world.getPlayers()) {
                const dx = player.location.x - entity.location.x;
                const dy = player.location.y - entity.location.y;
                const dz = player.location.z - entity.location.z;
                const distance = dx * dx + dy * dy + dz * dz; // Squared distance for efficiency

                if (distance < minDistance) {
                    minDistance = distance;
                    closestPlayer = player;
                }
            }

            if (closestPlayer) {
                tameable.tame(closestPlayer);
                entity.triggerEvent("enchanted_paperpets:paper_tame");
            }
        }
    }
});
