import { world, system } from "@minecraft/server";
import { handleScoutScope } from "./trinketEvents.js";

const witherLootData = new Map();

function getAllWithers() {
  let withers = world
    .getDimension("overworld")
    .getEntities({ type: "minecraft:wither" });

  withers = withers.concat(
    world.getDimension("nether").getEntities({ type: "minecraft:wither" })
  );

  withers = withers.concat(
    world.getDimension("the_end").getEntities({ type: "minecraft:wither" })
  );

  return withers;
}

// Track hurt Withers with scope-equipped attackers
world.afterEvents.entityHurt.subscribe((data) => {
  const victim = data.hurtEntity;
  if (!victim || victim.typeId !== "minecraft:wither") return;

  const player = data.damageSource?.damagingEntity;
  if (!player || player.typeId !== "minecraft:player") return;

  const tags = player.getTags();

  let tier = null;
  let prophecy = false;
  let hasRelevantTag = false;

  for (const tag of tags) {
    if (tag.startsWith("pb_gat_trinket_scout_")) {
      tier = parseInt(tag.split("_").pop());
      hasRelevantTag = true;
    }
    if (tag.startsWith("pb_gat_trinket_prophecy_scope_")) {
      tier = parseInt(tag.split("_").pop());
      prophecy = true;
      hasRelevantTag = true;
    }
    if (tag.startsWith("pb_gat_trinket_lucky_scope_")) {
      tier = parseInt(tag.split("_").pop()) * 2;
      hasRelevantTag = true;
    }
  }

  if (!hasRelevantTag || !tier) return;

  // Store snapshot location every time they are hit
  witherLootData.set(victim.id, {
    victim,
    player,
    tier,
    prophecy,
    location: { ...victim.location }, // snapshot
  });
});

// Check every few ticks for Withers that no longer exist
system.runInterval(() => {
  const aliveWithers = getAllWithers();

  for (const [entityId, data] of witherLootData.entries()) {
    const stillAlive = aliveWithers.some((w) => w.id === entityId);

    if (!stillAlive) {
      system.runTimeout(() => {
        try {
          handleScoutScope(
            data.victim,
            data.player,
            data.tier,
            data.prophecy,
            data.location // pass the saved snapshot
          );
        } catch (err) {}
      }, 200);

      witherLootData.delete(entityId);
    }
  }
}, 5);
