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

// Function to calculate the angle between two vectors
function calculateAngleBetweenVectors(v1, v2) {
  const dotProduct = v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
  const magnitudeV1 = Math.sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z);
  const magnitudeV2 = Math.sqrt(v2.x * v2.x + v2.y * v2.y + v2.z * v2.z);
  return Math.acos(dotProduct / (magnitudeV1 * magnitudeV2)) * (180 / Math.PI);
}

export default function evilSwordAbility(player, swordTier) {
  // Notify the player and set up the delay

  let damageAmount;
  let particleEffect;

  const viewAngle = 90; // Set the view angle to 75 degrees

  switch (swordTier) {
    case 1:
      damageAmount = 10;
      particleEffect = "float_ad:evil_dagger_strike_1";
      break;
    case 2:
      damageAmount = 20;
      particleEffect = "float_ad:evil_dagger_strike_2";
      break;
    case 3:
      damageAmount = 30;
      particleEffect = "float_ad:evil_dagger_strike_3";
      break;
    default:
      damageAmount = 10;
      particleEffect = "float_ad:evil_dagger_strike_1";
  }

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

  const performAttack = () => {
    // Apply damage to entities within a 5-block radius and 45-degree cone in front of the player
    const entities = player.dimension.getEntities({
      location: player.location,
      maxDistance: 5,
    });

    for (const entity of entities) {
      const direction = player.getViewDirection();
      const toEntity = {
        x: entity.location.x - player.location.x,
        y: entity.location.y - player.location.y,
        z: entity.location.z - player.location.z,
      };

      // Calculate the angle between the player's looking direction and the direction to the entity
      const angle = calculateAngleBetweenVectors(direction, toEntity);

      if (angle <= viewAngle / 2 && combinedMobs.includes(entity.typeId)) {
        entity.applyDamage(damageAmount, { cause: "starve" });
        entity.runCommandAsync(`particle ${particleEffect} ~ ~ ~`);
      }
    }
  };

  system.runTimeout(() => {
    performAttack();
    system.runTimeout(() => {
      performAttack();
    }, 10); // delay for the second attack
  }, 1); // delay for the first attack
}
