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

/**
 * Trainer Challenge UI
 * Entity side triggers: scriptevent pr:trainer_menu <trainerId>|<type>
 * This script shows a menu and, on "Challenge", triggers:
 *   scriptevent pr:trainer_challenge <trainerId>|<type>
 */
const MENU_EVENT = "pr:trainer_menu";
const CHALLENGE_EVENT = "pr:trainer_challenge";

// UI icon texture paths (no file extension)
const ICON_CHALLENGE = "textures/ui/button_default";
const ICON_CANCEL = "textures/ui/button_hover";

function parsePayload(message) {
  // Expected: "<trainerId>|<type>"
  const parts = (message ?? "").split("|");
  return {
    trainerId: (parts[0] ?? "").trim(),
    type: (parts[1] ?? "").trim(),
  };
}

world.afterEvents.scriptEventReceive.subscribe(async (ev) => {
  if (ev.id !== MENU_EVENT) return;
  const player = ev.sourceEntity;
  if (!player || player.typeId !== "minecraft:player") return;

  const { trainerId, type } = parsePayload(ev.message);
  const title = "Trainer Battle";
  const body = `Trainer: ${trainerId || "unknown"}\nType: ${type || "unknown"}`;

  const form = new ActionFormData()
    .title(title)
    .body(body)
    .button("Challenge", ICON_CHALLENGE)
    .button("Cancel", ICON_CANCEL);

  try {
    const res = await form.show(player);
    if (res.canceled) return;
    if (res.selection === 0) {
      const payload = `${trainerId}|${type}`;
      // Fire the battle start hook. Your battle system should listen for this.
      await player.runCommand(`scriptevent ${CHALLENGE_EVENT} ${payload}`);
    }
  } catch (e) {
    // ignore UI errors (e.g. player left)
  }
});
