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

const VENDOR_ID = "pr:pokemon_plushie_vendor";
const COIN_ID = "pr:poke_coin";
const COST = 5;

// Weighted random plushie items (equal weights here)
const plushies = [

  "pr:balbasaur_plushie_entity_spawn_egg",
  "pr:charmander_plushie_entity_spawn_egg",
  "pr:squirtle_plushie_entity_spawn_egg",
  "pr:mew_plushie_entity_spawn_egg",
];

function randomPlushie() {
  return plushies[Math.floor(Math.random() * plushies.length)];
}

async function countItem(player, itemId) {
  const inv = player.getComponent("minecraft:inventory")?.container;
  if (!inv) return 0;
  let total = 0;
  for (let i = 0; i < inv.size; i++) {
    const it = inv.getItem(i);
    if (it && it.typeId === itemId) total += it.amount;
  }
  return total;
}

async function removeItems(player, itemId, amount) {
  const inv = player.getComponent("minecraft:inventory")?.container;
  if (!inv) return false;
  let left = amount;
  for (let i = 0; i < inv.size && left > 0; i++) {
    const it = inv.getItem(i);
    if (!it || it.typeId !== itemId) continue;
    const take = Math.min(it.amount, left);
    it.amount -= take;
    left -= take;
    if (it.amount <= 0) inv.setItem(i, undefined);
    else inv.setItem(i, it);
  }
  return left === 0;
}

function giveItem(player, itemId) {
  const inv = player.getComponent("minecraft:inventory")?.container;
  if (!inv) return false;
  try {
    const leftover = inv.addItem(new ItemStack(itemId, 1));
    return leftover === undefined;
  } catch {
    return false;
  }
}


world.beforeEvents.playerInteractWithEntity.subscribe(async (ev) => {
  try {
    const player = ev.player;
    const target = ev.target;
    if (!player || !target) return;
    if (target.typeId !== VENDOR_ID) return;

    // Always show cost feedback on interaction
    // (This runs even if the vanilla interact_text isn't showing)
    const coins = await countItem(player, COIN_ID);
    if (coins < COST) {
      try { player.onScreenDisplay.setActionBar(`§cNeed §65 §cPoke Coins!`); } catch {}
      return;
    }

    const ok = await removeItems(player, COIN_ID, COST);
    if (!ok) {
      try { player.onScreenDisplay.setActionBar(`§cNeed §65 §cPoke Coins!`); } catch {}
      return;
    }

    const prize = randomPlushie();
    const gave = giveItem(player, prize);

    if (gave) {
      try { player.onScreenDisplay.setActionBar(`§aYou got a plushie!`); } catch {}
    } else {
      // refund if give failed
      try { const inv = player.getComponent("minecraft:inventory")?.container; if (inv) inv.addItem(new ItemStack(COIN_ID, COST)); } catch {}
      try { player.onScreenDisplay.setActionBar(`§cVendor error — refunded.`); } catch {}
    }
  } catch {
    // swallow
  }
});
