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

const TARGET_ID = "pc:inj_huggywuggy";
const ANIM_FALL = "animation.inj_huggywuggy.fall";
const AIR_DELAY = 15;
const fallTracker = new Map();

system.runInterval(() => {
    const dimensions = ["overworld", "nether", "the_end"];

    for (const dimName of dimensions) {
        const dimension = world.getDimension(dimName);
        const entities = dimension.getEntities({ type: TARGET_ID });

        for (const entity of entities) {
            if (!entity.isValid) continue;

            const velocity = entity.getVelocity();
            const isFalling = !entity.isOnGround && velocity.y < -0.5;

            let airTime = fallTracker.get(entity.id) || 0;

            if (isFalling) {
                airTime++;
                if (airTime === AIR_DELAY + 1) {
                    entity.playAnimation(ANIM_FALL, {
                        blendOutTime: 0.2,
                        stopExpression: "query.is_on_ground"
                    });
                }
            } else {
                airTime = 0;
            }
            fallTracker.set(entity.id, airTime);
        }
    }
}, 1);