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

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"
]);

system.runInterval(() => {
    const dimensions = [
        world.getDimension("overworld"),
        world.getDimension("nether"),
        world.getDimension("the_end")
    ];
    
    for (const dimension of dimensions) {
        const entities = dimension.getEntities();
        
        for (const entity of entities) {
            if (!tameableEntities.has(entity.typeId)) continue;

            const { x, y, z } = entity.location;
            let isMusicPlaying = false;

            // Limits to avoid out-of-bounds errors
            const minY = dimension.id === "minecraft:the_end" ? 0 : -64;
            const maxY = 320;

            // Check for jukebox blocks nearby (range of 10 blocks)
            for (let dx = -10; dx <= 10; dx++) {
                for (let dy = -10; dy <= 10; dy++) {
                    for (let dz = -10; dz <= 10; dz++) {
                        const newX = x + dx;
                        const newY = y + dy;
                        const newZ = z + dz;

                        // Avoid accessing out-of-bounds locations
                        if (newY < minY || newY > maxY) continue;

                        const block = dimension.getBlock({ x: newX, y: newY, z: newZ });
                        if (block && block.typeId === "minecraft:jukebox") {
                            // Check if jukebox has an item inside
                            const inventory = block.getComponent("minecraft:inventory");
                            if (inventory && inventory.container.size > 0) {
                                const record = inventory.container.getItem(0);
                                if (record) {
                                    isMusicPlaying = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (isMusicPlaying) {
                entity.dimension.spawnParticle("enchanted_paperpets:music", entity.location);
            }
        }
    }
}, 20); // Runs every second
