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

const AMBIENT_CONFIG = [
    {
        entityType: "mebesm:prototype",
        disableTag: "is_screaming_prototype",
        animations: ["amb1", "amb2", "amb3", "amb4"],
        intervalRange: { min: 100, max: 450 },
    },
    {
        entityType: "mebesm:chum_chomlkins",
        disableTag: "is_screaming_chum_chomlkins",
        animations: ["amb1", "amb2", "amb3", "amb4"],
        intervalRange: { min: 100, max: 450 },
    },
];

const entityTimers = new Map();

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomElement(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

function scheduleNext(entityId, config) {
    const delay = getRandomInt(config.intervalRange.min, config.intervalRange.max);
    entityTimers.set(entityId, { ticksLeft: delay, config });
}

system.runInterval(() => {
    for (const [entityId, data] of entityTimers.entries()) {
        data.ticksLeft--;
        if (data.ticksLeft <= 0) {
            entityTimers.delete(entityId);
        }
    }

    for (const config of AMBIENT_CONFIG) {
        const entities = world.getDimension("overworld").getEntities({ type: config.entityType });

        for (const entity of entities) {
            const id = entity.id;

            if (entityTimers.has(id)) continue;

            if (entity.hasTag(config.disableTag)) {
                scheduleNext(id, config);
                continue;
            }

            const anim = getRandomElement(config.animations);
            try {
                entity.playAnimation(anim);
            } catch (e) { }

            scheduleNext(id, config);
        }
    }
}, 1);