import { system } from "@minecraft/server";

system.afterEvents.scriptEventReceive.subscribe((data) => {
  const { id, sourceEntity } = data;
  if (id == "pb_gat:broken_grapple") {
    const leashable = sourceEntity.getComponent("leashable");
    if (leashable) leashable.unleash();
    const items = sourceEntity.dimension.getEntities({
      type: "minecraft:item",
    });
    let closestLead = null;
    let closestDist = Infinity;

    for (const item of items) {
      const stack = item.getComponent("item")?.itemStack;
      if (!stack || stack.typeId !== "minecraft:lead") continue;

      const dx = item.location.x - sourceEntity.location.x;
      const dy = item.location.y - sourceEntity.location.y;
      const dz = item.location.z - sourceEntity.location.z;
      const dist = dx * dx + dy * dy + dz * dz;

      if (dist < 100 && dist < closestDist) {
        closestLead = item;
        closestDist = dist;
      }
    }

    if (closestLead?.isValid()) closestLead.remove();
    sourceEntity.remove();
  }
  if (id == "pb_gat:mb_gam_drop_item") {
    mbEntityDropItem(sourceEntity);
  }
});

function mbEntityDropItem(sourceEntity) {
  const entityInv = sourceEntity?.getComponent("minecraft:inventory")?.container;
  const dropItem = entityInv?.getItem(0);
  if (!dropItem) return;

  const entityPos = sourceEntity.location;

  // Drop the item
  sourceEntity.dimension.spawnItem(dropItem, entityPos);

  sourceEntity.remove();
}