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

// Custom sounds for menu actions
const menuClickSound = "kaiju.kaiju_controller_menu_click"; // Sound for opening the menu
const resetSound = "kaiju.kaiju_controller_menu_click"; // Sound for the reset button

// List of Kaiju with their display names and corresponding tags
const kaijuList = [
  { name: "§l§eWardenzilla", tag: "wardenzillaplayer" },
  { name: "§l§eGolem Kong", tag: "golem_kong_player" },
  { name: "§l§eRophan", tag: "rophantom_player" },
  { name: "§l§eBeheMoohoglin", tag: "behemoohoglin_player" },
  { name: "§l§eSniffelah", tag: "sniffela_player" },
  { name: "§l§eMothlley", tag: "mothlley_player" },
  { name: "§l§eWither Ghidorah", tag: "wither_ghidorah_player" },
  { name: "§l§eSqucylla", tag: "squcylla_player" },
  { name: "§l§eBlazing Neakri", tag: "blazing_neakri_player" },
  { name: "§l§eEnder Muto", tag: "ender_muto_player" },
  { name: "§l§eRadstonezilla", tag: "mecha_wardenzillaplayer" }
];

// Function to open the main menu
function openMainMenu(player) {
  player.runCommandAsync(`playsound ${menuClickSound} @s`); // Play menu sound

  const form = new ActionFormData()
    .title("ALL KAIJU")
    .body("Select the kaiju:")
    .button("Reset Character");

  // Add buttons for each Kaiju
  kaijuList.forEach(kaiju => {
    form.button(kaiju.name);
  });

  form.show(player).then((response) => {
    if (response.canceled) return;

    if (response.selection === 0) {
      resetTags(player);
    } else {
      const selectedKaiju = kaijuList[response.selection - 1];
      activateEventCommand(player, selectedKaiju.tag);
    }
  });
}

// Function to activate the same event command for all buttons (except reset) and tag the player
function activateEventCommand(player, tag) {
  player.addTag(tag);
  player.runCommandAsync(`playsound ${menuClickSound} @s`);
  player.sendMessage(`You have selected your Kaiju!`);

  // Execute the /kill command (this will kill the player; replace with desired command if needed)
  player.runCommandAsync(`/event entity @e[family=kaiju_minecraft,r=10] minecraft:control`);
}

// Function to reset and remove all tags from the player (no other command is activated here)
function resetTags(player) {
  player.runCommandAsync(`playsound ${resetSound} @s`);

  const tags = player.getTags();
  tags.forEach((tag) => {
    player.removeTag(tag);
  });

  player.sendMessage("Reset Character!");
}

// Event listener when the custom item (or item of choice) is used to open the menu
world.afterEvents.itemUse.subscribe((event) => {
  const { source, itemStack } = event;
  if (itemStack?.typeId === "gojidraw:kaiju_controller") {
    openMainMenu(source);
  }
});