import { system } from "@minecraft/server";
import { combinedMobs } from "../variables.js";

export default function goodSpearAbility(player, SpearTier) {
  // Notify the player and set up the delay
  let particleEffect;
  let damageAmount;
  let radius;
  let impulseStrength;

  switch (SpearTier) {
    case 1:
      damageAmount = 10;
      radius = 8;
      impulseStrength = 1.2;
      particleEffect = "float_ad:good_dagger_strike_1";
      break;
    case 2:
      damageAmount = 20;
      radius = 10;
      impulseStrength = 1.5;
      particleEffect = "float_ad:good_dagger_strike_2";
      break;
    case 3:
      damageAmount = 30;
      radius = 12;
      impulseStrength = 2;
      particleEffect = "float_ad:good_dagger_strike_3";
      break;
    default:
      damageAmount = 10;
      radius = 6;
      impulseStrength = 1.2;
      particleEffect = "float_ad:good_dagger_strike_1";
  }

  // Play sound
  player.playSound("float_ad.spear_ability_good");

  system.runTimeout(() => {
    const entities = player.getEntitiesFromViewDirection({
      maxDistance: radius,
      includeLiquidBlocks: true,
      includePassableBlocks: true,
    });

    if (entities.length > 0) {
      for (let result of entities) {
        const { distance, entity } = result; // Unpack the distance and entity
        if (distance <= radius) {
          const entityTypeId = entity?.typeId;

          if (!entityTypeId) continue; // Skip if typeId is undefined

          if (combinedMobs.includes(entity.typeId)) {
            entity.applyDamage(damageAmount, { cause: "starve" });
            entity.runCommandAsync(`particle ${particleEffect} ~ ~ ~`);

            // Calculate the impulse direction away from the player
            const dirX = entity.location.x - player.location.x;
            const dirZ = entity.location.z - player.location.z;
            const magnitude = Math.sqrt(dirX * dirX + dirZ * dirZ);
            const normalizedDirX = dirX / magnitude;
            const normalizedDirZ = dirZ / magnitude;

            entity.applyImpulse({
              x: normalizedDirX * impulseStrength,
              y: 0.1,
              z: normalizedDirZ * impulseStrength,
            });
            entity.runCommandAsync(`particle ${particleEffect} ~ ~ ~`);
          }
        }
      }
    } else {
    }
  }, 9); // 0.5-second delay
}
