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

const ENTITY_IDENTIFIERS = [
    "mebesm:huggy_wuggy",
    "mebesm:kissy_missy",
    "mebesm:kissy_missy_wounded",
    "mebesm:huggy_wuggy_wounded"
];

const FALLING_ANIMATION = "animation.huggy_wuggy.falling_loop";
const IDLE_ANIMATION = "animation.huggy_wuggy.idle";

const FALL_DELAY_TICKS = 15;

const fallingTracker = new Map();

function manageFallingAnimation(entity) {
    const tracker = fallingTracker.get(entity.id) || { startTime: 0, isPlaying: false };

    const velocity = entity.getVelocity();
    const onGround = entity.isOnGround;

    const isFallingConditionMet = velocity.y < -0.05 && !onGround;

    if (isFallingConditionMet) {
        if (tracker.startTime === 0) {
            tracker.startTime = system.currentTick;
        }

        const elapsedTicks = system.currentTick - tracker.startTime;

        if (elapsedTicks >= FALL_DELAY_TICKS && !tracker.isPlaying) {
            entity.playAnimation(FALLING_ANIMATION, {
                blendOutTime: 0.1,
                loop: true,
            });
            tracker.isPlaying = true;
        }
    } else {
        tracker.startTime = 0;

        if (tracker.isPlaying) {
            entity.playAnimation(IDLE_ANIMATION, {
                blendOutTime: 10,
                loop: true
            });

            tracker.isPlaying = false;
        }
    }

    fallingTracker.set(entity.id, tracker);
}

system.runInterval(() => {
    try {
        const dimension = world.getDimension("overworld");

        for (const entityType of ENTITY_IDENTIFIERS) {
            for (const entity of dimension.getEntities({ type: entityType })) {
                manageFallingAnimation(entity);
            }
        }

        for (const [id] of fallingTracker.entries()) {
            if (!world.getEntity(id)) {
                fallingTracker.delete(id);
            }
        }
    } catch (e) {
        console.error(`[FALLING] ${e}`);
    }
}, 2);