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

//ender pet passive: it has a 50% chance to teleport 2 blocks to the side when hit
system.afterEvents.scriptEventReceive.subscribe(e => {
    if (e.id != "oct_eg:ender_pet") return;
    if (e.message == "teleport") {
        const pet = e.sourceEntity;

        //50% chance to teleport to the right
        if (Math.random() >= 0.5) {
            try {
                const viewDir = pet.getViewDirection();

                const rightVector = {
                    x: -viewDir.z,
                    y: 0,
                    z: viewDir.x
                };

                const length = Math.sqrt(rightVector.x ** 2 + rightVector.z ** 2);
                rightVector.x /= length;
                rightVector.z /= length;

            
                const location = pet.location;
                const targetPos = {
                    x: location.x + rightVector.x*3,
                    y: location.y,
                    z: location.z + rightVector.z*3
                };
                pet.dimension.spawnParticle("oct_eg:void_step.sparks_in",pet.location);

                pet.tryTeleport(targetPos);

            } catch (error) {
                //console.warn("pet could not be teleported!");
            }

        } else { //50% chance to teleport to the left
            try {
              
                const viewDir = pet.getViewDirection(); 

                
                const rightVector = {
                    x: viewDir.z,
                    y: 0,
                    z: -viewDir.x
                };

                
                const length = Math.sqrt(rightVector.x ** 2 + rightVector.z ** 2);
                rightVector.x /= length;
                rightVector.z /= length;

             
                const location = pet.location;
                const targetPos = {
                    x: location.x + rightVector.x*3,
                    y: location.y,
                    z: location.z + rightVector.z*3
                };
                pet.dimension.spawnParticle("oct_eg:void_step.sparks_in",pet.location);
               
                pet.tryTeleport(targetPos);
            } catch (error) {
                //console.warn("pet could not be teleported!");
            }
        }

    }
})