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

/**
 * Trigger del radio
 */
world.afterEvents.itemUse.subscribe((event) => {
  const player = event.source;
  const item = event.itemStack;

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

  openMainMenu(player);
});

/**
 * Menú principal
 */
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) return;

    switch (res.selection) {
      case 0:
        openLanguageMenu(player);
        break;
    }
  });
}

/**
 * Menú de idioma
 */
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);
    } else if (res.selection === 1) {
      showDialogueSpanish(player);
    }
  });
}

/**
 * Diálogo en inglés (placeholder)
 */
function showDialogueEnglish(player) {
  const form = new MessageFormData()
    .title("Commander Miranda Keyes")
    .body(
      "We've intercepted Forerunner data pointing to a structure known as the Library.\n\n" +
      "Whatever is inside that place is critical. You need to get there first."
    )
    .button1("Locate the Library")
    .button2("Cancel");

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

    locateLibrary(player, "en");
  });
}

/**
 * Diálogo en español (placeholder)
 */
function showDialogueSpanish(player) {
  const form = new MessageFormData()
    .title("Comandante Miranda Keyes")
    .body(
      "Hemos interceptado datos Forerunner que apuntan a una estructura conocida como la Biblioteca.\n\n" +
      "Lo que sea que esté ahí es crítico. Debes llegar antes que cualquier otra fuerza."
    )
    .button1("Localizar la Biblioteca")
    .button2("Cancelar");

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

    locateLibrary(player, "es");
  });
}

/**
 * Ejecuta el locate
 */
function locateLibrary(player, lang) {
  system.run(() => {
    player.runCommandAsync("locate structure halo:library");

    if (lang === "en") {
      player.sendMessage("§aCoordinates to the Library have been uploaded to your HUD.");
    } else {
      player.sendMessage("§aLas coordenadas de la Biblioteca han sido cargadas en tu HUD.");
    }
  });
}
