export function getRelative(entity, { x, y, z }, [distance, high, horizontal], targetY) {
    const newPosition = {
      x: entity.location.x + x * distance,
      y: entity.location.y + y * distance,
      z: entity.location.z + z * distance
    };
    const dirección = {
        x: -z,
        y: 0,
        z: x
    };
    newPosition.x += dirección.x * horizontal;
    newPosition.y += high;
    newPosition.z += dirección.z * horizontal;
    if (targetY) newPosition.y = targetY;
    return newPosition;
}
export function getRelative2(entity, direction, distance) {
  return {
    x: entity.location.x + direction.x * distance,
    y: entity.location.y + direction.y * distance,
    z: entity.location.z + direction.z * distance
  };
}

export const available_items = new Set([
    "dive_hw:hacker_sword",
    "dive_hw:hacker_chopper",
    "dive_hw:hacker_blade",
    "dive_hw:hacker_hammer",
    "dive_hw:hacker_bow",
    "dive_hw:hacker_axe",
    "dive_hw:hacker_crossbow",
    "dive_hw:hacker_laser",
    "dive_hw:hacker_wand",
    "dive_hw:hacker_pickaxe",
    "dive_hw:hacker_shield",
    "dive_hw:hacker_drill",
    "dive_hw:hacker_blaster",
    "dive_hw:hacker_hoe"
]);
export const itemsHandEffect = new Map();
import { system } from "@minecraft/server";
import { VECTOR } from "./mathUtils";

/**
 * Dispara múltiples proyectiles al mismo tiempo en un patrón de abanico.
 * @param {Player} player - Jugador que dispara.
 * @param {string} bulletID - ID de la entidad proyectil (ej. "minecraft:arrow").
 * @param {number} bulletCount - Número de proyectiles a disparar.
 * @param {number} spreadAngle - Ángulo de dispersión entre proyectiles.
 */
export function shootCommon(player, bulletID, bulletCount = 1, spreadAngle = 5) {
    let bulletId = bulletID;
    let velocity = player.getVelocity();
    let bulletLocation = player.getHeadLocation();
    bulletLocation = VECTOR.addWithVector(bulletLocation, velocity);

    let baseDirection = player.getViewDirection();

    for (let i = 0; i < bulletCount; i++) {
        let angleOffset = (i - (bulletCount - 1) / 2) * spreadAngle;
        let rotatedDirection = VECTOR.rotateXZ(baseDirection, angleOffset);

        let bullet = player.dimension.spawnEntity(bulletId, bulletLocation);
        setUpShoot(bullet, player, rotatedDirection);
    }
}

/**
 * Dispara proyectiles en secuencia con un intervalo de tiempo entre cada uno.
 * @param {Player} player - Jugador que dispara.
 * @param {string} bulletID - ID de la entidad proyectil (ej. "minecraft:arrow").
 * @param {number} bulletCount - Número de proyectiles a disparar.
 * @param {number} delayBetweenShots - Tiempo en ticks entre disparos (1 tick = 50ms).
 */
export function shootRepeat(player, bulletID, bulletCount = 1, delayBetweenShots = 20) {
    let bulletId = bulletID;
    let velocity = player.getVelocity();
    let bulletLocation = player.getHeadLocation();
    bulletLocation = VECTOR.addWithVector(bulletLocation, velocity);

    let baseDirection = player.getViewDirection();

    function shootArrow(index) {
        if (index >= bulletCount) return;

        let bullet = player.dimension.spawnEntity(bulletId, bulletLocation);
        setUpShoot(bullet, player, baseDirection);

        system.runTimeout(() => shootArrow(index + 1), delayBetweenShots);
    }

    shootArrow(0);
}

/**
 * Configura el proyectil con dirección y dueño.
 * @param {Entity} bullet - La entidad proyectil.
 * @param {Player} player - Jugador que dispara.
 * @param {Vector} direction - Dirección en la que se dispara el proyectil.
 */
export function setUpShoot(bullet, player, direction) {
    let power = 3;
    let projectileCompt = bullet.getComponent("projectile");
    projectileCompt.owner = player;
    direction = VECTOR.multiplyByNum(direction, power);
    projectileCompt.shoot(direction);
}
/**
 * Configura el proyectil con dirección y dueño.
 * @param {Entity} entity - Dueño.
 * @param {targetLocation} targetLocation - Target Location.
 * @param {Strenght} strength - Dirección en la que se dispara el proyectil.
 * @param {forceY} forceY -Fuerza en Y
 */
export function applyImpulseTowardsLocation(entity, targetLocation, strength = 1, forceY = 0.1) {
    try {
        const entityLocation = entity.location;
        const directionToTarget = {
            x: targetLocation.x - entityLocation.x,
            y: targetLocation.y - entityLocation.y,
            z: targetLocation.z - entityLocation.z
        };
        const normalize = (vector) => {
            const length = Math.sqrt(vector.x ** 2 + vector.y ** 2 + vector.z ** 2);
            return {
                x: vector.x / length,
                y: vector.y / length,
                z: vector.z / length
            };
        };
        const normalized = normalize(directionToTarget);
        const impulse = {
            x: normalized.x * strength,
            y: normalized.y * strength,
            z: normalized.z * strength
        };
        if (entity.typeId === "minecraft:player") {
            entity.applyKnockback(normalized.x, normalized.z, strength, forceY || 0.5);
        } else {
            entity.clearVelocity();
            entity.applyImpulse(impulse);
        }
    } catch (e) {}
}
export function applyCircleImpulse(entity, player_location) {
  let dx = entity.location.x - player_location.x;
  let dy = entity.location.y - player_location.y;
  let dz = entity.location.z - player_location.z;
  let distance = Math.sqrt(dx * dx + dy * dy + dz * dz);

  if (distance == 0) return;

  let nx = dx / distance;
  let nz = dz / distance;

  if (entity instanceof Player) {
    entity.applyKnockback(nx, nz, 1.5, .5);
    return;
  }

  entity.applyImpulse({
    x: nx * .7,
    y: .3,
    z: nz * .7
  });
  return;
}
export function getCircleBorder(center, radius) {
  const { x, y, z } = center;
  const points = [];
  const step = Math.PI / (radius * 2);

  for (let angle = 0; angle < 2 * Math.PI; angle += step) {
    const dx = Math.cos(angle) * radius;
    const dz = Math.sin(angle) * radius;
    points.push({ x: Math.round(x + dx), y, z: Math.round(z + dz) });
  }

  return points;
}
export function sphereCoordinates(center, radius) {
  const coordinates = [];

  for (let x = -radius; x <= radius; x++) {
    for (let y = -radius; y <= radius; y++) {
      for (let z = -radius; z <= radius; z++) {
        if (x * x + y * y + z * z <= radius * radius) {
          coordinates.push({ x: center.x + x, y: center.y + y, z: center.z + z });
        }
      }
    }
  }

  return coordinates;
}


export function getRandomXYZ(origin, radius, dimension) {
  for (let i = 0; i < 100; i++) {
    const angle = Math.random() * Math.PI * 2;
    const dist = Math.random() * radius;
    const x = Math.floor(origin.x + Math.cos(angle) * dist);
    const z = Math.floor(origin.z + Math.sin(angle) * dist);
    const y = Math.floor(origin.y + (Math.random() * 8 - 4)); // ±4 bloques

    const pos = { x, y, z };
    const air = dimension.getBlock(pos);
    const ground = dimension.getBlock({ x, y: y - 1, z });

    if (air?.typeId === "minecraft:air" && ground?.typeId !== "minecraft:air") {
      return { x: x + 0.5, y, z: z + 0.5 };
    }
  }
  return null;
}


