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

world.afterEvents.entitySpawn.subscribe((data) => {
  const entity = data.entity;

  if (entity.typeId !== "cyd_dino:spike_trap") return;

  const pos = entity.location;

  const centeredX = Math.floor(pos.x) + 0.5;
  const centeredY = Math.floor(pos.y);
  const centeredZ = Math.floor(pos.z) + 0.5;

  entity.teleport(
    { x: centeredX, y: centeredY, z: centeredZ },
    { rotation: { x: 0, y: 0 } }
  );

  system.runTimeout(() => {
    try { entity.addTag("cyd_dino:okay"); } catch ($) { }
  }, 40);
});

world.afterEvents.dataDrivenEntityTrigger.subscribe((data) => {
  const { entity, eventId } = data;

  try {
    const pos = entity.location;

    if (!entity.hasTag("cyd_dino:okay")) return;

    if (eventId == "cyd_dino:active") {
      if (entity.typeId !== "cyd_dino:spike_trap") return;

      const entities = entity.dimension.getEntities({
        location: pos,
        maxDistance: 2,
        excludeFamilies: ["cyd_dino:spike_trap"],
        families: ["dino"],
      });

      if (entities.length === 0) return;

      entity.setProperty("cyd_dino:animation", true);

      for (const target of entities) {
        target.applyDamage(30);
        target.addEffect("minecraft:slowness", 20 * 5, { amplifier: 1, showParticles: true });
      }

      system.runTimeout(() => {
        entity.remove();
      }, 20);
    }
  } catch (error) { }
});
