import { system, world } from "@minecraft/server";
import { pokemonUtils } from "./utils/pokemonUtils.js";

/**
 * PC Boxes via NPC Dialogue
 *
 * Flow:
 * 1) Player interacts with the PC entity (pr:storage_pc)
 * 2) Script spawns (or reuses) a hidden vanilla NPC in the player's current chunk (y=-64)
 * 3) Opens dialogue scene "pr:pc_boxes"
 * 4) Dialogue buttons fire /scriptevent pr:pc_select_box <1..10>
 * 5) Script receives the event, sets pr:pc_page, and opens the normal PC UI.
 *
 * This avoids JSON-UI server_form mapping issues entirely.
 */

const PC_ENTITY_ID = "pr:storage_pc";
const DIALOGUE_NPC_TAG = "pr_pc_dialogue";
const DIALOGUE_SCENE = "pr:pc_boxes";
const EVENT_ID = "pr:pc_select_box";
const BOX_COUNT = 10; // Box 1..10

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

function getOrCreateDialogueNpc(dimension, x, z) {
  // Try reuse nearest tagged NPC in this chunk
  const existing = dimension
    .getEntities({ type: "minecraft:npc", tags: [DIALOGUE_NPC_TAG], closest: 1, location: { x, y: -64, z }, maxDistance: 48 })
    .at(0);

  if (existing) return existing;

  const npc = dimension.spawnEntity("minecraft:npc", { x: x + 0.5, y: -64, z: z + 0.5 });
  npc.addTag(DIALOGUE_NPC_TAG);
  // Hide nameplate a bit by clearing name (optional)
  try { npc.nameTag = "§r"; } catch {}
  return npc;
}

world.afterEvents.playerInteractWithEntity.subscribe((ev) => {
  const player = ev.player;
  const target = ev.target;
  if (!isPC(target)) return;

  const dim = player.dimension;
  const { x, z } = player.location;

  try {
    // Ensure we have an NPC in ticking range (same chunk, underground)
    getOrCreateDialogueNpc(dim, Math.floor(x), Math.floor(z));

    // Open dialogue scene for this player.
    // Syntax: /dialogue open <npc: target> <player: target> [sceneName]
    player.runCommand(`dialogue open @e[type=npc,tag=${DIALOGUE_NPC_TAG},c=1] @s ${DIALOGUE_SCENE}`);
  } catch (e) {
    // Fallback: open the normal PC if dialogue fails
    try { pokemonUtils.openPC(player); } catch {}
  }
});

// Receive box selection from dialogue buttons
system.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id !== EVENT_ID) return;

  const player = event.sourceEntity;
  if (!player || player.typeId !== "minecraft:player") return;

  const raw = String(event.message ?? "").trim();
  const chosen = parseInt(raw, 10);
  if (!Number.isFinite(chosen) || chosen < 1 || chosen > BOX_COUNT) return;

  // Store chosen page (0-indexed)
  player.setDynamicProperty("pr:pc_page", chosen - 1);

  // Open your existing PC UI
  try { pokemonUtils.openPC(player); } catch {}
});
