import { world } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { pokemonUtils } from "./utils/pokemonUtils.js";

const PC_ENTITY_ID = "pr:storage_pc";

function isPC(entity) {
  return entity?.typeId === PC_ENTITY_ID;
}

/**
 * SAFE multi-box selector that does NOT depend on server_form.json.
 * - Clicking the PC entity opens a ModalForm (box + slot).
 * - Then it sets pr:pc_page and pr:selectedSlot so your existing withdraw/deposit logic can work.
 * - Finally it opens your original PC UI (pokemonUtils.openPC).
 * If anything goes wrong, it falls back to pokemonUtils.openPC directly.
 */
world.afterEvents.playerInteractWithEntity.subscribe((ev) => {
  const player = ev.player;
  const target = ev.target;

  if (!isPC(target)) return;

  try {
    openModalPC(player);
  } catch (e) {
    // Fallback: open the original PC
    try { pokemonUtils.openPC(player); } catch {}
  }
});

function openModalPC(player) {
  const allPC = pokemonUtils.getPCPokemons(player) ?? [];
  const pageSize = 30;
  const maxBoxes = 60;

  let page = player.getDynamicProperty("pr:pc_page");
  if (typeof page !== "number" || page < 0) page = 0;

  const maxPage = allPC.length === 0 ? 0 : Math.floor((allPC.length - 1) / pageSize);
  if (page > maxPage) page = maxPage;

  const start = page * pageSize;
  const slice = allPC.slice(start, start + pageSize);

  const form = new ModalFormData();
  form.title(`Pokémon Storage PC — Box ${page + 1}/${maxPage + 1}`);

  form.dropdown(
    "Select Box",
    Array.from({ length: maxBoxes }, (_, i) => `Box ${i + 1}`),
    page
  );

  const slotLabels = slice.map((p) => (p ? `${p.name} (Lvl ${p.level})` : "Empty Slot"));
  while (slotLabels.length < pageSize) slotLabels.push("Empty Slot");

  form.dropdown("Select Slot", slotLabels, 0);

  form.show(player).then((res) => {
    if (res.canceled) return;

    const selectedBox = res.formValues[0];
    const selectedSlot = res.formValues[1];

    // Store current box + selected slot in the same semantics your existing utils expect:
    // - pr:selectedSlot = 10 + absolutePcIndex
    player.setDynamicProperty("pr:pc_page", selectedBox);
    player.setDynamicProperty("pr:selectedSlot", 10 + (selectedBox * pageSize) + selectedSlot);

    // Open the original PC so Withdraw/Deposit buttons still work with your existing code.
    pokemonUtils.openPC(player);
  });
}
