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:rag_bag",
        disableTag: "is_screaming_rag_bag",
        animations: ["amb1", "amb2", "amb3", "amb4", "amb5"],
        intervalRange: { min: 100, max: 450 },
    },
    {
        entityType: "mebesm:gutter_plush",
        disableTag: "is_screaming_gutter_plush",
        animations: ["amb1", "amb2", "amb3", "amb4", "amb5"],
        intervalRange: { min: 100, max: 450 },
    },
    {
        entityType: "mebesm:giblet",
        disableTag: "is_screaming_giblet",
        animations: ["amb1", "amb2", "amb3", "amb4", "amb5"],
        intervalRange: { min: 200, max: 450 },
    },
    {
        entityType: "mebesm:lily_lovebraids",
        disableTag: "is_screaming_lily_lovebraids",
        animations: ["amb1", "amb2", "amb3", "amb4", "amb6", "amb7"],
        intervalRange: { min: 200, max: 450 },
    },
    {
        entityType: "mebesm:chum_chomlkins",
        disableTag: "is_screaming_chum_chomlkins",
        animations: ["amb1", "amb2", "amb3", "amb4"],
        intervalRange: { min: 100, max: 450 },
    },
];

const SPAWN_IMMUNITY_TICKS = 200;

const entityTimers = new Map();
const entitySpawnTick = new Map();

let currentTick = 0;

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(() => {
    currentTick++;

    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 (!entitySpawnTick.has(id)) {
                entitySpawnTick.set(id, currentTick);
            }

            if (currentTick - entitySpawnTick.get(id) < SPAWN_IMMUNITY_TICKS) continue;

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