import { world, system } from "@minecraft/server";
let jumpMap = new Map();
let breakMap = new Map();

world.afterEvents.playerInteractWithBlock.subscribe((event) => {
    if (event.block.typeId.includes("msft:station_")) {
        event.player.playSound("msft:ambient_god_crafting:ta-da");
    }
})

system.runInterval(() => {

    for (const player of world.getAllPlayers()) {
        if (!jumpMap.get(player.id)) {
            if (player.isJumping && !player.hasTag("useSkill")) {
                player.playAnimation("animation.jump_1");
                jumpMap.set(player.id, true);

                system.runTimeout(() => {
                    jumpMap.delete(player.id);
                }, 20);
            }
        }
    }
}, 1);

world.afterEvents.entitySpawn.subscribe(async (event) => {
    const entity = event.entity;
    if (entity.typeId.includes("boomerang") || entity.typeId.includes("sai") || entity.typeId.includes("shuriken")) return;
    if(entity.typeId.includes("msft:")) {
        const rotation = entity.getRotation();
        const cardinalRotation = rotationToCardinalRotation(rotation);
        const location = entity.location;

        if (!entity.isValid) return;

        await system.waitTicks(20);
        entity.teleport(
            { x: Math.floor(location.x) + 0.5, y: Math.floor(location.y), z: Math.floor(location.z) + 0.5 },
            { rotation: cardinalRotation }
        );

        if (!entity.isValid) return;

        await system.waitTicks(20);
        entity.teleport(
            { x: Math.floor(location.x) + 0.5, y: Math.floor(location.y), z: Math.floor(location.z) + 0.5 },
            { rotation: cardinalRotation }
        );
        

    }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
    event.player.playAnimation("animation.block_place");
});

function rotationToCardinalRotation(rotation) {
    let yaw = rotation.y % 360;
    if (yaw > 180) yaw -= 360;
    else if (yaw < -180) yaw += 360;
    // Cardinal directions in Minecraft (-180 to 180):
    // 0 = South, 90 = West, 180 = North, -90 = East, -180 = North
    const cardinalDirections = [0, 90, 180, -90, -180];
    // Trova la direzione cardinale più vicina
    return {
        x: rotation.x,
        y: cardinalDirections.reduce((prev, curr) =>
            Math.abs(curr - yaw) < Math.abs(prev - yaw) ? curr : prev
        )
    };
}