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

import "./custom.js"
import "./mobs.js"
import "./npc.js"
import "./menu.js"
import "./exam.js"
import "./grimorios/grimorios.js"

import daily from "./menu.js"

// Gamerules
system.runInterval(() => {
  world.getPlayers().forEach(cmc => {
    const tower = world.getDynamicProperty("tower") ?? false
    if (!tower) {
      world.scoreboard.addObjective("moedas")
      cmc.runCommand("tickingarea add circle ~~~ 4 torre")
      cmc.runCommand("execute as @s[tag=!torre] run structure load mystructure:tower2 ^-30^^-3 180_degrees")
      cmc.runCommand("execute as @s[tag=!torre] run structure load mystructure:tower ^-1^^-3 180_degrees")
      cmc.runCommand("execute as @s[tag=!torre] run setworldspawn ~~~")
      world.setDynamicProperty("tower", true)
      system.runTimeout(() => {
        cmc.runCommand("tickingarea remove torre")
      }, 40)
    }
    cmc.addTag("torre")
    if (!cmc.hasTag("start")) {
      const moedas = world.scoreboard.getObjective("moedas")
      moedas.setScore(cmc, 0)
      cmc.setDynamicProperty("rank", "e");
      cmc.setDynamicProperty("xp", 0);
      cmc.setDynamicProperty("xpMax", 100);
      cmc.setDynamicProperty("mana", 10);
      const item = new ItemStack("yokai:menu_c", 1);
      item.keepOnDeath = true;
      item.lockMode = "slot";
      const inventory = cmc.getComponent("inventory").container;
      inventory.setItem(0, item);
      cmc.runCommand("tp @s ~~2~")
      

      

      // Elemento
      const sorteio = Math.round(Math.random() * 99) + 1;
      if (sorteio <= 94) {
        cmc.sendMessage({translate:"message.magia"});
        cmc.triggerEvent("magia")
      } else if (sorteio <= 97) {
        cmc.sendMessage({translate:"message.blessed"});
        cmc.triggerEvent("magia")
        cmc.addTag("blessed")
      } else if (sorteio <= 100) {
        cmc.sendMessage({translate:"message.anti"});
        cmc.addTag("anti")
      }
      cmc.addTag("start");
    }
    //moedas
    const moedasScore = world.scoreboard.getObjective("moedas")
    if (moedasScore.getScore(cmc) > 999999) {
      moedasScore.setScore(cmc, 999999)
    }
    
    //Dragon nest
    const nest = cmc.dimension.getEntities({
      type: "yokai:dragon_nest",
      location: cmc.location,
      maxDistance: 2.5,
    })
    if (nest.length > 0) {
      cmc.triggerEvent("no_damage")
      cmc.addTag("no_damage")
    } else if (!cmc.hasTag("jump_air")) {
      cmc.triggerEvent("damage")
      cmc.removeTag("no_damage")
    }
    // Passiva Yuno Jump
    if (cmc.hasTag("jump_air")) {
      cmc.applyKnockback({ 
        x: 0,
        z: 0
      }, 0.9);
      cmc.removeTag("jump_air")
    }
    //Combate Exame
    if (cmc.hasTag("combat")) {
      const timerCombat = cmc.getDynamicProperty("timerCombat") ?? 0
      cmc.setDynamicProperty("timerCombat", timerCombat+1)
    }
//Boots
    if (cmc.hasTag("boots")) {
      cmc.triggerEvent("boots")
    } else {
      cmc.triggerEvent("no_boots")
    }
    // Title
    const hp = cmc.getComponent("health");
    const life = Math.round((hp.currentValue / hp.effectiveMax) * 100);

    const xpValue = cmc.getDynamicProperty("xp");
    const xpMax = cmc.getDynamicProperty("xpMax");
    const xp = Math.round((xpValue / xpMax) * 100);

    const rank = cmc.getDynamicProperty("rank");
    const timer = cmc.getDynamicProperty("timer");
    const mana = cmc.getDynamicProperty("mana");

    if (mana < 0) {
      cmc.setDynamicProperty("mana", 0);
    }

    if (!cmc.hasTag("ui") && !cmc.hasTag("camera")) {
      let squad = "null";
      const squads = ["tn", "ap", "ra", "ad", "op", "ld", "rl", "cc", "pc"];
      squads.forEach(tag => {
        if (cmc.hasTag(tag)) squad = tag;
      });

      let manaT = cmc.hasTag("anti") ? "anti_mana" : "mana";

      cmc.onScreenDisplay.setTitle({
        rawtext: [
          { text: "back" },
          { text: `${squad}${timer}` },
          { text: `${manaT}${mana}` },
          { text: `Life${life}` },
          { text: `rank_${rank}` },
          { text: `xp${xp}` }
        ]
      });
    } else {
      const vassoura = cmc.getDynamicProperty("vassoura") ?? 0
      let timeBar = cmc.getDynamicProperty("timeBar") ?? 1
      const pontos = cmc.getDynamicProperty("examPontos") ?? 0
      if (timeBar == 38) cmc.setDynamicProperty("timeMaxBar", true) 
      if (timeBar == 1) cmc.setDynamicProperty("timeMaxBar", false) 
      if (timeBar >= 1 && timeBar <= 9) timeBar = "0" + timeBar
      if (vassoura >= 1) {
        cmc.runCommand("tp @s ~~~ ~~")
        cmc.onScreenDisplay.setTitle({
          rawtext: [
            { text: `timebar${vassoura}` },
            { text: `cb${timeBar}` }
          ]
        });
        cmc.onScreenDisplay.setActionBar({translate:"message.exam3"})
        if (cmc.hasTag("jump")) {
          cmc.removeTag("jump")
          if (vassoura == 1) {

            if ((Number(timeBar) >= 1 && Number(timeBar) <= 11) || (Number(timeBar) >= 28 && Number(timeBar) <= 38)) {
              cmc.sendMessage({translate:"message.exam4"})
              cmc.playAnimation("animation.broom_bad")
              cmc.setDynamicProperty("timeBar", 1)
            }
            if ((Number(timeBar) >= 12 && Number(timeBar) <= 16) || (Number(timeBar) >= 24 && Number(timeBar) <= 27)) {
              cmc.sendMessage({translate:"message.exam5"})
              cmc.setDynamicProperty("examPontos", pontos+10)
              cmc.setDynamicProperty("timeBar", 1)
              
            }
            if ((Number(timeBar) >= 17 && Number(timeBar) <= 23)) {
              cmc.sendMessage({translate:"message.exam6"})
              cmc.setDynamicProperty("examPontos", pontos+20)
              cmc.setDynamicProperty("timeBar", 1)
              
            }
            cmc.setDynamicProperty("vassoura", 2)
            
            } else if (vassoura == 2) {
            if ((Number(timeBar) >= 1 && Number(timeBar) <= 13) || (Number(timeBar) >= 26 && Number(timeBar) <= 38)) {
              cmc.sendMessage({translate:"message.exam4"})
              cmc.playAnimation("animation.broom_bad")
              cmc.setDynamicProperty("timeBar", 1)
            }
            if ((Number(timeBar) >= 14 && Number(timeBar) <= 17) || (Number(timeBar) >= 22 && Number(timeBar) <= 25)) {
              cmc.sendMessage({translate:"message.exam5"})
              cmc.setDynamicProperty("examPontos", pontos+18)
              cmc.setDynamicProperty("timeBar", 1)
              
            }
            if ((Number(timeBar) >= 18 && Number(timeBar) <= 21)) {
              cmc.sendMessage({translate:"message.exam6"})
              cmc.setDynamicProperty("examPontos", pontos+30)
              cmc.setDynamicProperty("timeBar", 1)
              
            }
            cmc.setDynamicProperty("vassoura", 3)
              
            } else if (vassoura == 3) {
            if ((Number(timeBar) >= 1 && Number(timeBar) <= 3) || (Number(timeBar) >= 6 && Number(timeBar) <= 19) || (Number(timeBar) >= 21 && Number(timeBar) <= 33) || (Number(timeBar) >= 36 && Number(timeBar) <= 38)) {
              cmc.sendMessage({translate:"message.exam4"})
              cmc.playAnimation("animation.broom_bad")
              cmc.setDynamicProperty("timeBar", 1)
            }
            if ((Number(timeBar) >= 4 && Number(timeBar) <= 5) || (Number(timeBar) >= 34 && Number(timeBar) <= 35)) {
              cmc.sendMessage({translate:"message.exam5"})
              cmc.setDynamicProperty("examPontos", pontos+30)
              cmc.setDynamicProperty("timeBar", 1)
              
            }
            if (Number(timeBar) == 20) {
              cmc.sendMessage({translate:"message.exam6"})
              cmc.setDynamicProperty("examPontos", pontos+50)
              cmc.setDynamicProperty("timeBar", 1)
              
            }
            cmc.setDynamicProperty("vassoura", 0)
            cmc.setDynamicProperty("exam", 1)
            cmc.removeTag("camera")
            cmc.runCommand("camera @s clear")
            cmc.sendMessage({translate:"message.exam7"})
            cmc.triggerEvent("atk_none")
            const itemReady = new ItemStack("yokai:ready", 1);
            itemReady.keepOnDeath = true;
            itemReady.lockMode = "slot";
            const inventory = cmc.getComponent("inventory").container;
            inventory.addItem(itemReady);
            }
        } else {
          const timeMaxBar = cmc.getDynamicProperty("timeMaxBar")
          if (timeMaxBar) {
            cmc.setDynamicProperty("timeBar", Number(timeBar) - 1)
          } else {
            cmc.setDynamicProperty("timeBar", Number(timeBar) + 1)
          }
        }
        
      } else {
        cmc.onScreenDisplay.setTitle("nada");
      }
    }
    
    // Carregar mana e upar rank
    const ranks = [
      { rank: "e", mana: 140 },
      { rank: "d", mana: 120, xp: 200, color: "§e" },
      { rank: "c", mana: 100, xp: 300, color: "§6" },
      { rank: "b", mana: 80, xp: 500, color: "§2" },
      { rank: "a", mana: 60, xp: 700, color: "§9" },
      { rank: "s", mana: 40, xp: 1000, color: "§4" },
      { rank: "rei", mana: 40, xp: 9999, color: "§5" }
    ];

    const currentRank = cmc.getDynamicProperty("rank");
    cmc.triggerEvent(`rank_${currentRank}`)
    
    const indexRank = ranks.findIndex(r => r.rank === currentRank);
    const rankData = ranks[indexRank]
    if (!rankData) return;
    
    if (xpValue >= xpMax) {
      if (indexRank != 6) {
        cmc.runCommand("playsound random.levelup @s")
        cmc.sendMessage(`%message.rank ${ranks[indexRank+1].color}${ranks[indexRank+1].rank}`)
        cmc.setDynamicProperty("rank", ranks[indexRank+1].rank)
        cmc.setDynamicProperty("xpMax", ranks[indexRank+1].xp)
        cmc.setDynamicProperty("xp", 0)
      } else {
        cmc.setDynamicProperty("xp", 9999)
      }
    }
    
    let manaTick = cmc.getDynamicProperty("manaTick") ?? 0;
    if (mana < 10) {
      manaTick += 1;
      cmc.setDynamicProperty("manaTick", manaTick);
    }

    if (mana < 10 && manaTick >= rankData.mana) {
      cmc.setDynamicProperty("mana", mana + 1);
      cmc.setDynamicProperty("manaTick", 0);
    }

    // Pants
    if (!cmc.hasTag("ui")) {
      
      const property = cmc.getProperty("yokai:pants")
      const itemP = cmc.getComponent("equippable").getEquipment("Legs");
      if (!itemP) {
        if (property != 0) {
          cmc.triggerEvent("no_pants");
        }
      } else {
        const pants = ["nada", "yokai:yami_pants", "yokai:asta_pants", "yokai:yuno_pants", "yokai:luck_pants", "yokai:magna_pants"];
        let foiP = false;
        pants.forEach((data, index)=> {
          if (itemP.typeId === data) {
            foiP = true;
            if (property != index) {
              cmc.triggerEvent(data);
            }
          }
        });
        if (!foiP && property != 0) cmc.triggerEvent("no_pants");
      }
    }

    // Shirt
    if (!cmc.hasTag("ui")) {
      const propertyS = cmc.getProperty("yokai:shirt")
      const itemS = cmc.getComponent("equippable").getEquipment("Chest");
      if (!itemS) {
        if (propertyS != 0) {
          cmc.triggerEvent("no_shirt");
        }
      } else {
        const shirts = ["nada", "yokai:yami_shirt", "yokai:magna_shirt", "yokai:asta_shirt", "yokai:yuno_shirt", "yokai:luck_shirt"];
        let foiS = false;
        shirts.forEach((data, index)=> {
          if (itemS.typeId === data) {
            foiS = true;
            if (propertyS != index) {
              cmc.triggerEvent(data);
            }
          }
        });
        if (!foiS && propertyS != 0) cmc.triggerEvent("no_shirt");
      }
    }
    
    
    // Cloaks
    const propertyC = cmc.getProperty("yokai:cloaks")
    const itemC = cmc.getComponent("equippable").getEquipment("Feet");
    if (!itemC) {
      if (propertyC != 0) {
        cmc.triggerEvent("no_cloak");
      }
    } else {
      const cloaks = ["nada", "yokai:cloak_pc", "yokai:cloak_ld", "yokai:cloak_ra", "yokai:cloak_ap", "yokai:cloak_ad", "yokai:cloak_rl", "yokai:cloak_tn", "yokai:cloak_cc", "yokai:cloak_op"];
      let foiC = false;
      cloaks.forEach((data, index)=> {
        if (itemC.typeId === data) {
          foiC = true;
          if (propertyC != index) {
            cmc.triggerEvent(data);
          }
        }
      });
      if (!foiC && propertyC != 0) cmc.triggerEvent("no_cloak");
    }
    
    
    
    //missoes diarias
    const dia = cmc.getDynamicProperty("dia") ?? -1
    const diaAtual = world.getDay()
    if (diaAtual != dia) {
      const ranks = ["e", "d", "c", "b", "a", "s", "rei"];
      const current = ranks.indexOf(cmc.getDynamicProperty("rank"));
      
      const dailyValidos = daily.filter(obj => ranks.indexOf(obj.rank) <= current)
      
      let tamanho = dailyValidos.length - 1
      let randomD = Math.round(Math.random() * tamanho)
      cmc.setDynamicProperty("daily1", dailyValidos[randomD].indice)
      dailyValidos.splice(randomD, 1)
      
      tamanho = dailyValidos.length - 1
      randomD = Math.round(Math.random() * tamanho)
      cmc.setDynamicProperty("daily2", dailyValidos[randomD].indice)
      dailyValidos.splice(randomD, 1)
      
      
      
      tamanho = dailyValidos.length - 1
      randomD = Math.round(Math.random() * tamanho)
      cmc.setDynamicProperty("daily3", dailyValidos[randomD].indice)
      dailyValidos.splice(randomD, 1)
      
      cmc.setDynamicProperty("dia", diaAtual)
      
      if (dia != -1) {
        cmc.sendMessage({translate:"message.daily"})
        cmc.setDynamicProperty("chestDaily", 0)
        cmc.setDynamicProperty("banditDaily", 0)
        cmc.setDynamicProperty("mobDaily", 0)
        cmc.setDynamicProperty("boarDaily", 0)
        cmc.setDynamicProperty("npcBuy", 0)
      }
    }
    
    
  });
}, 1);

// Timer
system.runInterval(() => {
  world.getPlayers().forEach(cmc => {
    let timer = (cmc.getDynamicProperty("timer") ?? 0) + 1;
    if (timer > 4) {
      timer = 1;
    }
    cmc.setDynamicProperty("timer", timer);
  });
}, 4);

// Punch
world.afterEvents.entityHitEntity.subscribe((event) => {
//Pasiva Luck Teaser
  if (event.hitEntity.typeId == "minecraft:player") {
    if (event.hitEntity.getProperty("yokai:grimorios") == 6) {
      if (Math.round(Math.random()) == 1) {
        event.damagingEntity.applyDamage(1, {
          cause: "entityAttack",
          damagingEntity: event.hitEntity
        })
      }
    }
  }
  if (event.damagingEntity.typeId == "minecraft:player") {
    event.damagingEntity.playSound("punch");
    const item = event.damagingEntity.getComponent("inventory").container.getItem(event.damagingEntity.selectedSlotIndex);
    if (!item) return;
    if (item.typeId === "yokai:grand_slam") {
      let location = event.hitEntity.location
      location.y += 1.2
      event.damagingEntity.spawnParticle("yokai:fire_impact", location);
      event.hitEntity.setOnFire(5);
    } else if ((item.typeId === "yokai:slayer_asta" || item.typeId === "yokai:dweller_asta" || item.typeId === "yokai:destroyer_asta") && event.hitEntity.typeId == "minecraft:player") {
      const chance = Math.round(Math.random() * 100)
      if (chance >= 75) {
        const mana = event.hitEntity.getDynamicProperty("mana")
        if (mana > 0) {
          event.hitEntity.setDynamicProperty("mana", mana - 1)
        }
      }
    }
  }
});

world.afterEvents.entitySpawn.subscribe((event) => {
  if (event.entity.typeId == "minecraft:enderman" && event.entity.isValid) {
    
    const players = event.entity.dimension.getPlayers({
      location: event.entity.location,
      maxDistance: 100,
    })
   players.forEach(player => {
     if (player.hasTag("estrutura_end")) {
       event.entity.remove()
     }
   })
  }
})






