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

const MAP = new Map([
  ["pr:balbasaur_plushie", "pr:balbasaur_plushie_entity"],
  ["pr:charmander_plushie", "pr:charmander_plushie_entity"],
  ["pr:squirtle_plushie", "pr:squirtle_plushie_entity"],
  ["pr:mew_plushie", "pr:mew_plushie_entity"],
]);

world.afterEvents.playerInteractWithBlock.subscribe((ev) => {
  const player = ev.source;
  if (!player) return;

  const item = ev.itemStack;
  if (!item) return;

  const entId = MAP.get(item.typeId);
  if (!entId) return;

  const loc = ev.block.location;
  const spawnLoc = {
    x: loc.x + 0.5,
    y: loc.y + 1,
    z: loc.z + 0.5,
  };

  try {
    player.dimension.spawnEntity(entId, spawnLoc);
  } catch {
    return;
  }

  // consume item
  const inv = player.getComponent("minecraft:inventory")?.container;
  if (!inv) return;

  const slot = player.selectedSlotIndex;
  const current = inv.getItem(slot);
  if (!current || current.typeId !== item.typeId) return;

  if (current.amount <= 1) {
    inv.setItem(slot, undefined);
  } else {
    const newStack = new ItemStack(current.typeId, current.amount - 1);
    newStack.nameTag = current.nameTag;
    inv.setItem(slot, newStack);
  }
});
