import { system, world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

function safeJsonParse(s) {
  try { return JSON.parse(s); }
  catch { return null; }
}

system.afterEvents.scriptEventReceive.subscribe((ev) => {
  if (ev.id !== "rp_pr:trainer_menu") return;

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

  const payload =
    (ev.message && ev.message.trim().length)
      ? (safeJsonParse(ev.message) ?? { trainer: "unknown", type: "unknown" })
      : { trainer: "unknown", type: "unknown" };

  system.runTimeout(() => {
    const form = new ActionFormData()
      .title("Trainer Battle")
      .body(`Trainer: ${payload.trainer}\nType: ${payload.type}`)
      .button("Challenge")
      .button("Cancel");

    form.show(player).then((res) => {
      if (res.canceled) return;
      if (res.selection === 0) {
        player.runCommand(
          `scriptevent rp_pr:trainer_challenge ${JSON.stringify(payload)}`
        );
      }
    }).catch(() => {});
  }, 2);
});
