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

const needlerBullets = {
  "halo:rifle_aguijoneador": true,
  "halo:rifle_aguijoneador1": true,
  "halo:neddler": true,
  "halo:neddler1": true,
  "halo:neddler_dual": true,
  "halo:neddler1_dual": true
};

const needlerHits = new Map();

world.afterEvents.projectileHitEntity.subscribe(ev => {
  const proj = ev.projectile;
  if (!proj) return;

  const entity = ev.getEntityHit()?.entity;
  if (!entity || !entity.isValid()) return;
  if (!needlerBullets[proj.typeId]) return;

  let data = needlerHits.get(entity);
  if (!data) {
    data = { count: 0, timer: 10 };
  }

  data.count++;
  data.timer = 10;
  needlerHits.set(entity, data);

  if (data.count >= 9) {
    entity.dimension.spawnEntity(
      "halo:blamita_explode",
      entity.location
    );
    needlerHits.delete(entity);
  }
});

system.runInterval(() => {
  for (const [entity, data] of needlerHits.entries()) {
    if (!entity.isValid()) {
      needlerHits.delete(entity);
      continue;
    }

    data.timer--;

    if (data.timer <= 0) {
      data.count--;
      data.timer = 10;

      if (data.count <= 0) {
        needlerHits.delete(entity);
      }
    }
  }
}, 2);
