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

const soundState = new Map();

const mobConfig = {
    "mebesm:art_the_clown2": {
        sound: "musik.musik1",
        duration: 767
    },
    "mebesm:art_the_clown3": {
        sound: "musik.musik8",
        duration: 200
    },
    "mebesm:art_the_clown4": {
        sound: "musik.musik2",
        duration: 254
    },
    "mebesm:art_the_clown5": {
        sound: "musik.musik2",
        duration: 254
    },
    "mebesm:art_the_clown6": {
        sound: "musik.musik7",
        duration: 254
    },
    "mebesm:santa_art_the_clown": {
        sound: "musik.musik3",
        duration: 610
    },
    "mebesm:new_year_art_the_clown": {
        sound: "musik.musik7",
        duration: 460
    },
    "mebesm:art_the_clown7": {
        sound: "musik.musik5",
        duration: 580
    }
};

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const radius = 20;
        let activeConfig = null;
        let activeMobId = null;

        for (const [id, cfg] of Object.entries(mobConfig)) {
            const entities = player.dimension.getEntities({
                type: id,
                location: player.location,
                maxDistance: radius
            }).filter(e => e.getComponent("minecraft:health")?.currentValue > 0);

            if (entities.length > 0) {
                activeConfig = cfg;
                activeMobId = id;
                break;
            }
        }

        const lastState = soundState.get(player.id) || { activeId: null, timer: 0 };

        if (activeConfig) {
            if (lastState.activeId && lastState.activeId !== activeMobId) {
                player.runCommand(`stopsound @s ${mobConfig[lastState.activeId].sound}`);
                lastState.timer = 0;
            }

            if (lastState.timer <= 0) {
                // Изменено на 0.3 (вместо 1), чтобы звук был тихим
                player.runCommand(`playsound ${activeConfig.sound} @s ~ ~ ~ 0.2 1`);
                lastState.timer = activeConfig.duration;
            } else {
                lastState.timer--;
            }
            soundState.set(player.id, { activeId: activeMobId, timer: lastState.timer });
        } else {
            if (lastState.activeId) {
                player.runCommand(`stopsound @s ${mobConfig[lastState.activeId].sound}`);
                soundState.set(player.id, { activeId: null, timer: 0 });
            }
        }
    }
}, 1);