import * as ModalForm from '@minecraft/server-ui';
import { system, world } from '@minecraft/server';

let playerLore = {};
let loreTimeouts = {};
let permanentLore = {};
let playerEmotions = {};
let playerLoreColors = {};

const colorMap = [
  "§´§0", // 0 - Preto
  "§´§c", // 1 - Vermelho
  "§´§6", // 2 - Laranja
  "§´§e", // 3 - Amarelo
  "§´§a", // 4 - Verde
  "§´§9", // 5 - Azul
  "§´§d", // 6 - Roxo
  "§´§f"  // 7 - Branco
];

world.afterEvents.itemUse.subscribe(event => {
  if (event.itemStack.typeId === "well:chatbubbles") {
    let player = event.source;
    const allPlayers = [...world.getPlayers()];
    const otherPlayers = allPlayers.filter(p => p.name !== player.name);
    if (otherPlayers.length === 0) {
      player.sendMessage({
        'rawtext': [{
          'translate': 'msg.players.not.online'
        }]
      });
      return;
    }
    openLoreCommand(player);
  }
});

function setPlayerLore(player, loreText) {
  const words = loreText.split(" ");
  let line = '';
  const lines = [];
  for (const word of words) {
    if ((line + word).length <= 20) {
      line += (line.length > 0 ? " " : '') + word;
    } else {
      lines.push(line);
      line = word;
    }
  }
  if (line.length > 0) {
    lines.push(line);
  }

  const color = playerLoreColors[player.name] || "§´§b"; // cor padrão se nenhuma for definida
  const formattedLore = lines.map(l => color + l).join("§´\n");

  playerLore[player.name] = formattedLore;
  updatePlayerNameTag(player);

  if (loreTimeouts[player.name]) {
    system.clearRun(loreTimeouts[player.name]);
    delete loreTimeouts[player.name];
  }

  if (!permanentLore[player.name]) {
    loreTimeouts[player.name] = system.runTimeout(() => {
      delete playerLore[player.name];
      player.nameTag = player.name;
      delete loreTimeouts[player.name];
    }, 300);
  }
}

function updatePlayerNameTag(player) {
  const lore = playerLore[player.name];
  const emotion = playerEmotions[player.name];
  const emotionTag = emotion ? ` ${emotion}` : '';
  const originalName = player.name;
  player.nameTag = originalName + emotionTag + (lore ? "\n§´§b" + lore : '');
}

function initLoreOnJoin() {
  world.afterEvents.playerJoin.subscribe(event => {
    const player = event.player;
    system.runTimeout(() => {
      updatePlayerNameTag(player);
    }, 10);
  });
}

function openLoreCommand(player) {
  const form = new ModalForm.ModalFormData();

  form.textField("ChatBubbles", {
    'rawtext': [{ 'translate': "form.chatbubbles.ui" }]
  });

  form.dropdown("Escolha uma emoção", [
    "Nenhuma",
    "Feliz",
    "Triste",
    "Zangado",
    "Surpreso",
    "Apaixonado",
	"Decepcionado",
	
	"gargalhando",
	"Malicioso",
	"Brincando",
	"Impaciente",
	"Ambicioso",
	"Estiloso",
	
	"Indiferente",
	"Tímido",
	"Envergonhado",
    "Pensativo"
  ], 0);

  form.slider("Cor da mensagem", 0, 7, 1, 3); // valor padrão 3 = Amarelo

  form.toggle({
    'rawtext': [{ 'translate': "form.chatbubbles.chat.permanente" }]
  }, !!permanentLore[player.name]);

  form.show(player).then(async result => {
    if (!result.canceled) {
      const loreText = result.formValues[0];
      const emotionIndex = result.formValues[1];
      const colorIndex = result.formValues[2];
      const isPermanent = result.formValues[3];

      const emotions = [
        "",
        "",
        "",
        "",
        "",
        "",
        "",
		
		"",
        "",
        "",
        "",
        "",
        "",
		
		"",
        "",
        "",
        ""
		
      ];

      playerEmotions[player.name] = emotions[emotionIndex];
      playerLoreColors[player.name] = colorMap[colorIndex];
      permanentLore[player.name] = isPermanent;

      setPlayerLore(player, loreText);

      // Executa comandos conforme a emoção
      switch (emotionIndex) {
        case 1: // Feliz
          await player.runCommand(`particle heart ~ ~2 ~`);
		  await player.runCommand(`playanimation @s animation.chatbubbles.feliz`);
          break;
        case 2: // Triste
          await player.runCommand(`particle splash ~ ~2 ~`);
		  await player.runCommand(`playanimation @s animation.chatbubbles.triste`);
          break;
        case 3: // Zangado
          await player.runCommand(`particle angry_villager ~ ~2 ~`);
          break;
        case 4: // Surpreso
          await player.runCommand(`particle explosion_emitter ~ ~2 ~`);
		  await player.runCommand(`playanimation @s animation.chatbubbles.surpreso`);
          break;
        case 5: // Apaixonado
          await player.runCommand(`particle minecraft:heart_particle ^ ^2 ^`);
		  await player.runCommand(`particle minecraft:heart_particle ^1 ^2 ^`);
		  await player.runCommand(`particle minecraft:heart_particle ^ ^2 ^1`);
		  await player.runCommand(`playanimation @s animation.chatbubbles.apaixonado`);
          break;
        case 6: // Assustado
          await player.runCommand(`particle smoke ~ ~2 ~`);
          break;
      }
    }
  });
}

world.beforeEvents.chatSend.subscribe((event, {
  message,
  sender
}) => {
  if (message === "!lore permanente") {
    event.cancel = true;
    const isPermanent = permanentLore[sender.name];
    permanentLore[sender.name] = !isPermanent;
    return;
  }
  if (message.startsWith('*')) {
    event.cancel = true;
    const loreText = message.slice(1).trim();
    if (loreText.length === 0) {
      sender.sendMessage("§cVocê precisa digitar uma lore após o '*'.");
    } else {
      setPlayerLore(sender, loreText);
      sender.sendMessage("§aLore definida como: §7" + loreText);
    }
    return;
  }
});

export { setPlayerLore, updatePlayerNameTag, openLoreCommand, initLoreOnJoin };