// scripts/armors/titanium_effects.js
import { E, ARMOR_SETS, hasSet, safeAddEffect } from "./armors_index.js";
import { EntityDamageCause } from "@minecraft/server";

const ITEM_RADIUS = 8;
const XP_RADIUS = 6;
const DMG_RADIUS = 1.5;
const DMG_AMOUNT = 6;

function dist2(a, b) {
  const dx = a.x - b.x;
  const dy = a.y - b.y;
  const dz = a.z - b.z;
  return dx * dx + dy * dy + dz * dz;
}

function pullNearest(dim, loc, maxDistance, typeId, toLoc) {
  const ents = dim.getEntities({ location: loc, maxDistance, type: typeId });
  if (ents.length === 0) return;

  let best = ents[0];
  let bestD = dist2(best.location, loc);

  for (let i = 1; i < ents.length; i++) {
    const d = dist2(ents[i].location, loc);
    if (d < bestD) {
      bestD = d;
      best = ents[i];
    }
  }

  // Teleporta el más cercano (equivalente a c=1)
  best.teleport(toLoc, { dimension: dim });
}

export function titaniumEffects(player, eqIds) {
  if (!E) return;
  if (!hasSet(eqIds, ARMOR_SETS.titanium)) return;

  const dim = player.dimension;
  const loc = player.location;

  pullNearest(dim, loc, ITEM_RADIUS, "minecraft:item", loc);

  safeAddEffect(player, E.regeneration, 0);

  pullNearest(dim, loc, XP_RADIUS, "minecraft:xp_orb", loc);

  const monsters = dim.getEntities({
    location: loc,
    maxDistance: DMG_RADIUS,
    families: ["monster"],
  });

  for (const m of monsters) {
    m.applyDamage(DMG_AMOUNT, { cause: EntityDamageCause.thorns, damagingEntity: player });
  }
}
