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

world.afterEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const item = event.itemStack;

  if (!player || player.typeId !== "minecraft:player") return;
  if (!item || item.typeId !== "halo:radio") return;

  openMainMenu(player);
});

function openMainMenu(player) {
  const form = new ActionFormData()
    .title("Forerunner Data Interface")
    .body("Select an available operation.")
    .button("The Library – Locate")
    .button("Exit");

  form.show(player).then((res) => {
    if (res.canceled || res.selection === 1) return;
    if (res.selection === 0) openLanguageMenu(player);
  });
}

function openLanguageMenu(player) {
  const form = new ActionFormData()
    .title("Select Language")
    .body("Choose your preferred language.")
    .button("English")
    .button("Español");

  form.show(player).then((res) => {
    if (res.canceled) return;
    if (res.selection === 0) showDialogueEnglish(player);
    if (res.selection === 1) showDialogueSpanish(player);
  });
}

function showDialogueEnglish(player) {
  const form = new MessageFormData()
    .title("Commander Miranda Keyes")
    .body("Intercepting data... Tracking the Library now.")
    .button1("Locate")
    .button2("Cancel");

  form.show(player).then((res) => {
    if (res.canceled || res.selection === 1) return;
    spawnLocateEntity(player, "en");
  });
}

function showDialogueSpanish(player) {
  const form = new MessageFormData()
    .title("Comandante Miranda Keyes")
    .body("Interceptando datos... Localizando la Biblioteca.")
    .button1("Localizar")
    .button2("Cancelar");

  form.show(player).then((res) => {
    if (res.canceled || res.selection === 1) return;
    spawnLocateEntity(player, "es");
  });
}

function spawnLocateEntity(player, lang) {
  const msg = lang === "es" ? "§a[Miranda Keyes]: §fSeñal enviada. Esperando coordenadas..." : "§a[Miranda Keyes]: §fSignal sent. Awaiting coordinates...";
  player.sendMessage(msg);

  try {
    // USAMOS EL MÉTODO NATIVO: spawnea la entidad directamente en la posición del jugador
    player.dimension.spawnEntity("halo:library_locate", player.location);
    
    player.onScreenDisplay.setActionBar(lang === "es" ? "§bSincronizando..." : "§bSyncing...");
    player.runCommandAsync(`playsound note.pling @s ~ ~ ~ 1 1.5`);
  } catch (e) {
    player.sendMessage("§c[Error]: No se pudo invocar el rastreador. Verifica el identificador de la entidad.");
    console.warn("Fallo al spawnear: " + e);
  }
}