// Import necessary modules from Minecraft server API
import { world, system, EntityComponentTypes } from "@minecraft/server";

export function scaredMobs() {
  world.afterEvents.projectileHitBlock.subscribe((event) => {
    const projectile = event.projectile;
    const block = event.getBlockHit().block;
    if (projectile.typeId == "hb_hr:scared_pig_projectile" && block) {
      const loc = { x: block.location.x, y: block.location.y + 0.05, z: block.location.z };
      block.dimension.spawnEntity("hb_hr:scared_pig_acid", loc);
    }
  });

  system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.sourceEntity?.typeId === "hb_hr:scared_chicken" || event.sourceEntity?.typeId === "hb_hr:scared_sheep" || event.sourceEntity?.typeId === "hb_hr:scared_cow" || event.sourceEntity?.typeId === "hb_hr:scared_pig" || event.sourceEntity?.typeId === "hb_hr:scared_pig_acid") {
      let target = event.sourceEntity;

      switch (event.id) {
        case "hb_hr:transform_full_health":
          const healthComponent = target.getComponent(EntityComponentTypes.Health);
          if (healthComponent !== undefined) {
            healthComponent.setCurrentValue(healthComponent.effectiveMax);
          }
          break;
        case "hb_hr:scared_sheep_scream":
          let nearbyEntitiesScream = target.dimension.getEntities({
            location: target.location,
            maxDistance: 1.5,
          });

          if (nearbyEntitiesScream.length === 0) return;
          else {
            nearbyEntitiesScream.forEach((entity) => {
              if (entity.typeId == target.typeId || entity.typeId == "minecraft:item" || entity.typeId == "minecraft:item" || entity.typeId == "minecraft:falling_block" || entity.typeId == "minecraft:xp_orb" || entity.typeId == "minecraft:arrow") return;
              entity.applyDamage(2, { cause: "entityAttack", damagingEntity: target });
            });
          }
          break;
        case "hb_hr:scared_pig_acid":
          let nearbyEntitiesAcid = target.dimension.getEntities({
            location: target.location,
            maxDistance: 3,
          });

          if (nearbyEntitiesAcid.length === 0) return;
          else {
            nearbyEntitiesAcid.forEach((entity) => {
              if (entity.typeId == target.typeId) return;
              entity.addEffect("poison", 60, { amplifier: 0 });
            });
          }
          break;

        default:
          break;
      }
    }
  });
  world.afterEvents.playerInteractWithEntity.subscribe((event) => {
    const { player, target, beforeItemStack, itemStack } = event;
    if (target) {
      switch (target.typeId) {
        case "hb_hr:scared_chicken":
          break;

        default:
          break;
      }
    }
  });
  world.afterEvents.entityHitEntity.subscribe((event) => {
    const damager = event.damagingEntity;
    const hit_entity = event.hitEntity;

    const healthComponentCheck = hit_entity.getComponent(EntityComponentTypes.Health);
    // if (healthComponentCheck !== undefined) {
    //   world.sendMessage("currentValue: " + healthComponentCheck.currentValue);
    //   world.sendMessage("effectiveMax: " + healthComponentCheck.effectiveMax);
    // }

    if (hit_entity.typeId !== "hb_hr:scared_sheep") return;
    if (damager.typeId !== "minecraft:player") return;
    const markVariant = hit_entity.getComponent("minecraft:mark_variant").value;
    // only teleport if scared sheep is hostile aka mark_variant == 2
    if (markVariant != 2) return;
    // only continue with 80% chance:
    const chance = 0.8;
    if (Math.random() >= chance) return; // Math.random() ∈ [0,1); ≥0.8 is 20% → return early

    const healthComponent = hit_entity.getComponent(EntityComponentTypes.Health);
    if (healthComponent !== undefined) {
      if (healthComponent.currentValue == 0) return;
      // add 3 health aka 10%, currently 30 health max
      healthComponent.setCurrentValue(healthComponent.currentValue + 3);
    }
    // how many blocks behind the player to teleport the sheep
    const blocksBehind = -0.5; // ← change this to whatever distance you want

    // get player position & facing
    const pos = damager.location;
    const yawDeg = damager.getRotation().y;
    const yawRad = yawDeg * (Math.PI / 180);

    // compute N blocks behind:
    const offsetX = Math.sin(yawRad) * blocksBehind;
    const offsetZ = Math.cos(yawRad) * blocksBehind;
    const behindX = pos.x - offsetX;
    const behindZ = pos.z + offsetZ;

    const target = {
      x: behindX,
      y: pos.y,
      z: behindZ,
    };
    hit_entity.playAnimation("animation.hb_hr.scared_sheep.teleport");
    hit_entity.teleport(target, damager.dimension);
  });
}
