import * as mc from "@minecraft/server";

mc.world.afterEvents.entityHitEntity.subscribe((data) => {

    if (data.damagingEntity.typeId !== "minecraft:player") return;
    if (data.hitEntity.typeId !== "bunny_ce:book") return;
    const player = data.damagingEntity;
    const hitEntity = data.hitEntity;
    const lookDirection = player.getViewDirection();
    let hitEntityLocation = hitEntity.location;

    const deltaX = hitEntityLocation.x - player.location.x;
    const deltaZ = hitEntityLocation.z - player.location.z;
    const angle = Math.atan2(deltaZ, deltaX);

    const playerLookAngle = Math.atan2(lookDirection.z, lookDirection.x);
    const angleDifference = (angle - playerLookAngle + Math.PI * 2) % (Math.PI * 2);


    const centerRange = Math.PI / 32;


    if (angleDifference < centerRange || angleDifference > Math.PI * 2 - centerRange) {

        mc.world.playSound("bunny_ce.book.close", hitEntityLocation);
        hitEntity.triggerEvent("bunny_ce:time_to_despawn");
    } else if (angleDifference > Math.PI) {
        mc.world.playSound("bunny_ce.book.page", hitEntityLocation);
        hitEntity.playAnimation("animation.base_book.left");
        hitEntity.triggerEvent("bunny_ce:next_page");
    } else {
        mc.world.playSound("bunny_ce.book.page", hitEntityLocation);
        hitEntity.playAnimation("animation.base_book.right");
        hitEntity.triggerEvent("bunny_ce:back_page");
    }



})














