import { ActionFormData } from "@minecraft/server-ui";
import { CLANS } from "../config.js";
import { setScore, setProp, getScore } from "../system.js";
import { openVilaMenu } from "./vila.js"; 

const selectionState = {};
const SYSTEM_TAGS = ["clan_escolhido", "menu_status_entregue", "ItensIniciaisEntregues"];

export function openClanSelection(player) {
    // ✅ Só abre se o jogador ainda não tiver escolhido um clã
    if (player.hasTag("clan_escolhido")) return;

    // Limpa apenas gênero, não remove tags de sistema
    player.removeTag("male");
    player.removeTag("female");

    // Não remover SYSTEM_TAGS aqui, senão o menu abre de novo após respawn
    // SYSTEM_TAGS.forEach(t => player.removeTag(t));

    // Remove tags de clãs anteriores
    Object.keys(CLANS).forEach(c => {
        player.removeTag(c);
        player.removeTag(c.toLowerCase());
    });

    // Remove tags de vilas anteriores
    const vilasTags = ["folha", "areia", "nuvem", "nevoa", "pedra", "bankonoha", "bansuna", "bannuvem", "bannevoa", "banpedra"];
    vilasTags.forEach(t => player.removeTag(t));

    if (!selectionState[player.id]) selectionState[player.id] = 0;
    
    const clanKeys = Object.keys(CLANS);
    const index = selectionState[player.id];
    const currentClan = clanKeys[index];
    
    const clanIcon = `textures/items/pamobile/nz_cla_${currentClan.toLowerCase()}`;

    const form = new ActionFormData()
        .title(":zenkai_clan_selector:§fClan")
        .body(`§f${currentClan}`);

    form.button("§p§r§e§v§i§o§u§s"); // voltar
    form.button("§s§e§l§e§c§t§aSelecionar", clanIcon); // selecionar
    form.button("§n§e§x§t"); // avançar

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

        if (res.selection === 0) { 
            selectionState[player.id] = (index - 1 + clanKeys.length) % clanKeys.length;
            openClanSelection(player);
        }
        else if (res.selection === 2) { 
            selectionState[player.id] = (index + 1) % clanKeys.length;
            openClanSelection(player);
        }
        else if (res.selection === 1) { 
            applyClan(player, currentClan);
        }
    });
}

function applyClan(player, clanName) {
  const tagMinuscula = clanName.toLowerCase();
  const tagMaiuscula = tagMinuscula.charAt(0).toUpperCase() + tagMinuscula.slice(1);

  player.addTag(tagMinuscula);
  player.addTag(tagMaiuscula);
  player.addTag("clan_escolhido");

  let vida = 200, forca = 5, defesa = 10, chakra = 150, stamina = 300;

  switch (tagMinuscula) {
    case "uchiha":
      vida = 300; forca = 20; defesa = 25; chakra = 400; stamina = 300;
      break;
    case "senju":
      vida = 450; forca = 10; defesa = 40; chakra = 200; stamina = 350;
      break;
    case "uzumaki":
      vida = 400; forca = 8; defesa = 30; chakra = 500; stamina = 350;
      break;
    case "hyuga":
      if (Math.random() < 0.5) {
        vida = 250; forca = 12; defesa = 25; chakra = 250; stamina = 300;
        player.addTag("HyugaNormal");
        player.sendMessage("§aHyuga Principal!");
      } else {
        vida = 200; forca = 8; defesa = 20; chakra = 180; stamina = 250;
        player.addTag("HyugaSelado");
        player.sendMessage("§cHyuga Secundária!");
      }
      break;
    case "aburame":
      if (Math.random() < 0.6) {
        vida = 280; forca = 14; defesa = 25; chakra = 250; stamina = 350;
        player.addTag("AburameRaro");
        player.sendMessage("§bSorte! Aburame Raro!");
      } else {
        vida = 220; forca = 10; defesa = 20; chakra = 200; stamina = 300;
        player.addTag("nz:AburameComun");
      }
      break;
    case "akimichi":
      vida = 350; forca = 18; defesa = 20; chakra = 150; stamina = 400;
      break;
    case "chinoike":
      vida = 280; forca = 16; defesa = 20; chakra = 350; stamina = 300;
      break;
    default:
      // outros clãs ficam com o base genérico
      break;
  }

  // aplica no scoreboard e props
  setScore(player, "vida", vida);
  setScore(player, "forca", forca);
  setScore(player, "defesa", defesa);
  setProp(player, "chakraMax", chakra);
  setProp(player, "staminaMax", stamina);
  setScore(player, "Stamina", stamina);

  player.runCommandAsync(`event entity @s health.${vida}`);
  player.runCommandAsync(`event entity @s damage.${forca}`);
  player.runCommandAsync(`event entity @s resistance.${defesa}`);

  player.runCommandAsync(`replaceitem entity @s slot.hotbar 8 nz:menu_custom 1 0 {"minecraft:item_lock":{"mode":"lock_in_slot"}}`);
  player.runCommandAsync(`give @s nz:kunai 1`);
  player.runCommandAsync(`give @s nz:roupa_ninja 1`);

  openVilaMenu(player);
}