import { uiManager, ActionFormData } from "@minecraft/server-ui";
import { dailyMenu } from "./starterMenu.js";

/**
 * Opens the Team selection menu (styled by RP server_form.json via title = "Teams").
 * Adds one of these tags to the player: valor | mystic | instinct
 * Ensures only ONE team tag is present.
 */
export function teamMenu(player) {
  const form = new ActionFormData();
  const actions = [];

  form.title("Teams");
  form.body("000000000000");

  form.button("JOIN TEAM VALOR");
  actions.push(() => setTeam(player, "valor"));

  form.button("JOIN TEAM MYSTIC");
  actions.push(() => setTeam(player, "mystic"));

  form.button("JOIN TEAM INSTINCT");
  actions.push(() => setTeam(player, "instinct"));

  form.show(player).then((response) => {
    if (response.canceled || response.cancelationReason) return;
    const fn = actions[response.selection];
    if (fn) fn();
  });
}

function setTeam(player, team) {
  // enforce only 1 team tag
  player.removeTag("valor");
  player.removeTag("mystic");
  player.removeTag("instinct");

  player.addTag(team);
  try { player.addTag("pr:team_selected"); } catch (e) {}
  try { player.addTag("pr:started"); } catch (e) {}

  if (!player.hasTag("pr:first_village_quest_done")) {
    try { player.addTag("pr:first_village_quest"); } catch (e) {}
  }

  player.sendMessage(`§7Team set to §l§a${team.toUpperCase()}§r§7!`);
  if (!player.hasTag("pr:first_village_quest_done")) {
    player.sendMessage("§6Quest Added: §eFind a village and speak to a quest NPC.");
  }
  try { player.playSound("random.orb"); } catch (e) {}
  uiManager.closeAllForms(player);

  // continue to the daily rewards flow (keeps your current starter flow intact)
  try {
    dailyMenu(player);
  } catch (e) {
    // ignore if dailyMenu isn't available for some reason
  }
}
