import { world, system, ItemStack } from "@minecraft/server";
import { handleScoutScope } from "./trinketEvents.js"; // Import the function to handle scope drops

function locString(loc) {
  return `x:${loc.x.toFixed(1)}, y:${loc.y.toFixed(1)}, z:${loc.z.toFixed(1)}`;
}

const recentlyBrokenHearts = new Map(); // heart location string -> player id
const twitchingCreakings = new Map(); // creaking entity id -> player id

/// Track heart breaks
world.beforeEvents.playerBreakBlock.subscribe((event) => {
  if (event.block.typeId !== "minecraft:creaking_heart") return;

  const locStr = event.block.location.toString();
  recentlyBrokenHearts.set(locStr, { playerId: event.player.id, location: event.block.location });

  system.runTimeout(() => recentlyBrokenHearts.delete(locStr), 3000);
});

/// Track creaking states
world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
  const entity = event.entity;
  if (entity.typeId !== "minecraft:creaking") return;

  // 1️⃣ Track twitching start to mark player
  if (event.eventId === "minecraft:start_twitching") {
    const brokenHeart = Array.from(recentlyBrokenHearts.values()).find(h =>
      Math.hypot(
        h.location.x - entity.location.x,
        h.location.y - entity.location.y,
        h.location.z - entity.location.z
      ) <= 15
    );

    if (brokenHeart) {
      twitchingCreakings.set(entity.id, brokenHeart.playerId);
    }
  }

  // 2️⃣ When it crumbles, roll loot
  if (event.eventId === "minecraft:crumble") {
    const playerId = twitchingCreakings.get(entity.id);
    if (!playerId) return;

    const player = world.getPlayers().find(p => p.id === playerId);
    if (!player) return;


    // === Loot check ===
    const tags = player.getTags();
    for (const tag of tags) {
      if (tag.startsWith("pb_gat_trinket_scout_")) {
        const tier = parseInt(tag.split("_").pop());
        handleScoutScope(entity, player, tier, false);
      }
      if (tag.startsWith("pb_gat_trinket_prophecy_scope_")) {
        const tier = parseInt(tag.split("_").pop());
        handleScoutScope(entity, player, tier, true);
      }
      if (tag.startsWith("pb_gat_trinket_lucky_scope_")) {
        const tier = parseInt(tag.split("_").pop());
        handleScoutScope(entity, player, tier * 2, false);
      }
      // Add other scope checks if needed
    }

    // Clean up
    twitchingCreakings.delete(entity.id);
  }
});
