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

world.afterEvents.playerInteractWithEntity.subscribe(function (event) {
    if (event.target.typeId == "yokai:tower_wizard") {
      event.target.runCommand(`execute as @s at @s positioned ^ ^1 ^2 run camera "${event.player.name}" set minecraft:free ease 0.3 linear pos ~ ~ ~ facing @s`)
      if (event.player.hasTag("customF") && !event.player.hasTag("gri_yes") && !event.player.hasTag("finalExam")) {
        grimorioMenu(event.player, event.target)
      } else if (event.player.hasTag("gri_yes") && !event.player.hasTag("finalExam")) {
        exam(event.player)
      } else if (event.player.hasTag("finalExam")) {
        finalExam(event.player)
      } else {
        noCustom(event.player)
      }
    } else if ((event.target.typeId == "yokai:broom_e" || event.target.typeId == "yokai:broom_c" || event.target.typeId == "yokai:broom_b") && event.player.hasTag("sneak")) {
      event.player.runCommand(`give @s ${event.target.typeId}_item`)
      event.target.remove()
    } else if (event.target.typeId == "yokai:chest_sus") {
      const chestDaily = event.player.getDynamicProperty("chestDaily") ?? 0
      event.target.playAnimation("animation.chest_take")
      system.runTimeout(() => {
        event.target.triggerEvent("sumir")
        event.player.setDynamicProperty("chestDaily", chestDaily + 1)
      }, 12)
    } else if (event.target.typeId == "yokai:tailor") {
      tailorAba(event.player)
    } else if (event.target.typeId == "yokai:artisan") {
      artisanAba(event.player)
    }
})
//probabilidades
const gri_chance = [
  {
    nome: "magna", range: [0, 35], rangeBlessed: [0, 30], duration: 70
  },
  {
    nome: "noelle", range: [36, 61], rangeBlessed: [31, 52], duration: 70
  },
  {
    nome: "luck", range: [62, 84], rangeBlessed: [53, 74], duration: 70
  },
  {
    nome: "yuno", range: [85, 93], rangeBlessed: [75, 88], duration: 80
  },
  {
    nome: "licht", range: [94, 100], rangeBlessed: [89, 100], duration: 80
  }
]

const griAnti = [
  {
    nome: "asta", range: [0, 100], duration: 150
  }
  ]


//Tower wizard 
function grimorioMenu(player, mob) {
  const menu = new ActionFormData()
    .title({translate:"npc.title.1"})
    .button({translate:"npc.button.3"})
    .button({translate:"npc.button.2"})
    .body({translate:"npc.text.2"})
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.runCommand("camera @s clear")
    if (escolha.selection == 0) {
      mob.runCommand(`tp "${player.name}" ^^-3^15 360 0`)
      player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ^4^3^-2 facing @s")
      player.addTag("ui")
      player.addTag("gri_yes")
      const random = Math.floor(Math.random() * 100) + 1;
      let escolhido;
      if (player.hasTag("blessed")) {
        escolhido = gri_chance.find(g => 
          random >= g.rangeBlessed[0] && random <= g.rangeBlessed[1]
        );
      } else if (!player.hasTag("anti")) {
        escolhido = gri_chance.find(g => 
          random >= g.range[0] && random <= g.range[1]
        );
      } else {
        escolhido = griAnti.find(g => 
          random >= g.range[0] && random <= g.range[1]
        )
      }
      player.triggerEvent(`gri_torre_${escolhido.nome}`)
      system.runTimeout(() => {
        player.triggerEvent("gri_torre_none")
        player.sendMessage({translate:"message.exam0"})
        player.runCommand("camera @s clear")
        const item = new ItemStack(`yokai:gri_${escolhido.nome}`, 1);
        item.keepOnDeath = true;
        item.lockMode = "slot";
        const inventory = player.getComponent("inventory").container;
        inventory.setItem(0, item);
        player.triggerEvent(`gri_${escolhido.nome}_close`)
        player.removeTag("ui")
      }, escolhido.duration)
    }
    if (escolha.selection == 1) player.runCommand("camera @s clear")
  })
}


function exam(player) {
  const menu = new ActionFormData()
    .title({translate:"npc.title.1"})
    .button({translate:"npc.button.4"})
    .button({translate:"npc.button.2"})
    .body({translate:"npc.text.3"})
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.runCommand("camera @s clear")
    if (escolha.selection == 0) {
      let posX = Math.round(Math.random() * 20000)
      let posZ = Math.round(Math.random() * 20000)
      posX = Math.random() < 0.5 ? posX : -posX
      posZ = Math.random() < 0.5 ? posZ : -posZ
      player.runCommand("camera @s clear")
      player.setDynamicProperty("voltar", player.location)
      player.runCommand(`execute in the_end run tickingarea add circle ${posX} 150 ${posZ} 4 coliseu${player.id}`)
      player.runCommand(`execute in the_end run structure load mystructure:coliseu1 ${posX} 150 ${posZ}`)
      player.runCommand(`execute in the_end run structure load mystructure:coliseu2 ${posX + 42} 150 ${posZ}`)
      player.runCommand(`execute in the_end run structure load mystructure:coliseu3 ${posX} 150 ${posZ + 42}`)
      player.runCommand(`execute in the_end run structure load mystructure:coliseu4 ${posX + 42} 150 ${posZ + 42}`)
      player.runCommand(`fog @s push "yokai:coliseu" exam`)
      player.addTag("estrutura_end")
      player.runCommand(`execute in the_end run tp @s ${posX + 41} 152 ${posZ + 41} -90 0`)
      player.runCommand("gamemode a")
    }
    if (escolha.selection == 1) player.runCommand("camera @s clear")
  })
}

function noCustom(player) {
  const menu = new ActionFormData()
    .title({translate:"npc.title.1"})
    .button({translate:"npc.button.1"})
    .button({translate:"npc.button.2"})
    .body({translate:"npc.text.1"})
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.runCommand("camera @s clear")
    if (escolha.selection == 0) player.runCommand("camera @s clear")
    if (escolha.selection == 1) player.runCommand("camera @s clear")
  })
}

function finalExam(player) {
  const menu = new ActionFormData()
    .title({translate:"npc.title.1"})
    .button({translate:"npc.button.6"})
    .button("...")
    .body({translate:"npc.text.4"})
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.runCommand("camera @s clear")
    if (escolha.selection == 0) player.runCommand("camera @s clear")
    if (escolha.selection == 1) player.runCommand("camera @s clear")
  })
}



function tailorAba(player) {
  player.addTag("ui")
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  
  const menu = new ActionFormData()
    .title({translate:"npc.title.11"})
    .button({translate:"yokai:itemGroup.name.shirts"})
    .button({translate:"yokai:itemGroup.name.pants"})
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.removeTag("ui")
    if (escolha.selection == 0) tailorShirts(player)
    if (escolha.selection == 1) tailorPants(player)
  })
}


function tailorShirts(player) {
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  
  const menu = new ActionFormData()
    .title("tailorRoupa")
    .button(` 30`)
    .button(` 30`)
    .button(` 30`)
    .button(` 30`)
    .button(` 30`)
    .button("")
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.removeTag("ui")
    if (escolha.selection == 0) {
      player.triggerEvent("yokai:asta_shirt")
      tailorShirtsBuy(player, 0)
    }
    if (escolha.selection == 1) {
      player.triggerEvent("yokai:magna_shirt")
      tailorShirtsBuy(player, 1)
    }
    if (escolha.selection == 2) {
      player.triggerEvent("yokai:luck_shirt")
      tailorShirtsBuy(player, 2)
    }
    if (escolha.selection == 3) {
      player.triggerEvent("yokai:yami_shirt")
      tailorShirtsBuy(player, 3)
    }
    if (escolha.selection == 4) {
      player.triggerEvent("yokai:yuno_shirt")
      tailorShirtsBuy(player, 4)
    }
    if (escolha.selection == 5) tailorAba(player)
  })
}



function tailorShirtsBuy(player, shirt) {
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  let color;
  if (moedas >= 30) {
    color = "§a"
  } else {
    color = "§c"
  }
  const menu = new ActionFormData()
    .title("tailorRoupaBuy")
    .button(` 30`)
    .button(` 30`)
    .button(` 30`)
    .button(` 30`)
    .button(` 30`)
    .button(`${color}%interact.text.buy`)
    .button("")
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.removeTag("ui")
    if (escolha.selection == 0) {
      player.triggerEvent("yokai:asta_shirt")
      tailorShirtsBuy(player, 0)
    }
    if (escolha.selection == 1) {
      player.triggerEvent("yokai:magna_shirt")
      tailorShirtsBuy(player, 1)
    }
    if (escolha.selection == 2) {
      player.triggerEvent("yokai:luck_shirt")
      tailorShirtsBuy(player, 2)
    }
    if (escolha.selection == 3) {
      player.triggerEvent("yokai:yami_shirt")
      tailorShirtsBuy(player, 3)
    }
    if (escolha.selection == 4) {
      player.triggerEvent("yokai:yuno_shirt")
      tailorShirtsBuy(player, 4)
    }
    if (escolha.selection == 5) {
      switch (shirt) {
        case 0:
          if (moedas >= 30) {
            moedasScore.addScore(player, -30)
            player.runCommand("give @s yokai:asta_shirt")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorShirtsBuy(player, shirt)
          }
        break
        case 1:
          if (moedas >= 30) {
            moedasScore.addScore(player, -30)
            player.runCommand("give @s yokai:magna_shirt")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorShirtsBuy(player, shirt)
          }
        break
        case 2:
          if (moedas >= 30) {
            moedasScore.addScore(player, -30)
            player.runCommand("give @s yokai:luck_shirt")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorShirtsBuy(player, shirt)
          }
        break
        case 3:
          if (moedas >= 30) {
            moedasScore.addScore(player, -30)
            player.runCommand("give @s yokai:yami_shirt")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorShirtsBuy(player, shirt)
          }
        break
        case 4:
          if (moedas >= 30) {
            moedasScore.addScore(player, -30)
            player.runCommand("give @s yokai:yuno_shirt")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorShirtsBuy(player, shirt)
          }
        break
      }
    }
    if (escolha.selection == 6) tailorAba(player)
  })
}


function tailorPants(player) {
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  
  const menu = new ActionFormData()
    .title("tailorRoupaP")
    .button(` 20`)
    .button(` 20`)
    .button(` 20`)
    .button(` 20`)
    .button(` 20`)
    .button("")
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.removeTag("ui")
    if (escolha.selection == 0) {
      player.triggerEvent("yokai:asta_pants")
      tailorPantsBuy(player, 0)
    }
    if (escolha.selection == 1) {
      player.triggerEvent("yokai:magna_pants")
      tailorPantsBuy(player, 1)
    }
    if (escolha.selection == 2) {
      player.triggerEvent("yokai:luck_pants")
      tailorPantsBuy(player, 2)
    }
    if (escolha.selection == 3) {
      player.triggerEvent("yokai:yami_pants")
      tailorPantsBuy(player, 3)
    }
    if (escolha.selection == 4) {
      player.triggerEvent("yokai:yuno_pants")
      tailorPantsBuy(player, 4)
    }
    if (escolha.selection == 5) tailorAba(player)
  })
}



function tailorPantsBuy(player, pants) {
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  let color;
  if (moedas >= 20) {
    color = "§a"
  } else {
    color = "§c"
  }
  const menu = new ActionFormData()
    .title("tailorRoupaBuyP")
    .button(` 20`)
    .button(` 20`)
    .button(` 20`)
    .button(` 20`)
    .button(` 20`)
    .button(`${color}%interact.text.buy`)
    .button("")
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.canceled) player.removeTag("ui")
    if (escolha.selection == 0) {
      player.triggerEvent("yokai:asta_pants")
      tailorPantsBuy(player, 0)
    }
    if (escolha.selection == 1) {
      player.triggerEvent("yokai:magna_pants")
      tailorPantsBuy(player, 1)
    }
    if (escolha.selection == 2) {
      player.triggerEvent("yokai:luck_pants")
      tailorPantsBuy(player, 2)
    }
    if (escolha.selection == 3) {
      player.triggerEvent("yokai:yami_pants")
      tailorPantsBuy(player, 3)
    }
    if (escolha.selection == 4) {
      player.triggerEvent("yokai:yuno_pants")
      tailorPantsBuy(player, 4)
    }
    if (escolha.selection == 5) {
      switch (pants) {
        case 0:
          if (moedas >= 20) {
            moedasScore.addScore(player, -20)
            player.runCommand("give @s yokai:asta_pants")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorPantsBuy(player, pants)
          }
        break
        case 1:
          if (moedas >= 20) {
            moedasScore.addScore(player, -20)
            player.runCommand("give @s yokai:magna_pants")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorPantsBuy(player, pants)
          }
        break
        case 2:
          if (moedas >= 20) {
            moedasScore.addScore(player, -20)
            player.runCommand("give @s yokai:luck_pants")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorPantsBuy(player, pants)
          }
        break
        case 3:
          if (moedas >= 20) {
            moedasScore.addScore(player, -20)
            player.runCommand("give @s yokai:yami_pants")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorPantsBuy(player, pants)
          }
        break
        case 4:
          if (moedas >= 20) {
            moedasScore.addScore(player, -20)
            player.runCommand("give @s yokai:yuno_pants")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
            player.removeTag("ui")
          } else {
            tailorPantsBuy(player, pants)
          }
        break
      }
    }
    if (escolha.selection == 6) tailorAba(player)
  })
}


function artisanAba(player) {
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  
  const menu = new ActionFormData()
    .title({translate:"npc.title.12"})
    .body(`%npc.text.16`)
    .button({translate:"npc.button.26"})
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.selection == 0) artisanBroom(player)
  })
}



function artisanBroom(player) {
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  
  const menu = new ActionFormData()
    .title({translate:"npc.title.13"})
    .body(`%npc.text.17`)
    .button(` 100`)
    .button(` 300`)
    .button(` 500`)
    .button("")
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.selection >= 0 && escolha.selection <= 2) artisanBroomBuy(player, escolha.selection)
    if (escolha.selection == 3) artisanAba(player)
  })
}




function artisanBroomBuy(player, broom) {
  const moedasScore = world.scoreboard.getObjective("moedas")
  const moedas = moedasScore.getScore(player)
  let color;
  let title;
  let body;
  switch (broom) {
    case 0:
      title = "item.text.broom_e"
      body = "npc.text.18"
      if (moedas >= 100) {
        color = "§a"
      } else {
        color = "§c"
      }
    break
    case 1:
      body = "npc.text.19"
      title = "item.text.broom_c"
      if (moedas >= 300) {
        color = "§a"
      } else {
        color = "§c"
      }
    break
    case 2:
      body = "npc.text.20"
      title = "item.text.broom_b"
      if (moedas >= 500) {
        color = "§a"
      } else {
        color = "§c"
      }
    break
  }
  const menu = new ActionFormData()
    .title({translate:`${title}`})
    .body(`%${body}`)
    .button(` 100`)
    .button(` 300`)
    .button(` 500`)
    .button(`${color}%interact.text.buy`)
    .button("")
    .button(` ${moedas}`)
  menu.show(player).then(escolha => {
    if (escolha.selection >= 0 && escolha.selection <= 2) artisanBroomBuy(player, escolha.selection)
    if (escolha.selection == 3) {
      switch (broom) {
        case 0:
          if (moedas >= 100) {
            moedasScore.addScore(player, -100)
            player.runCommand("give @s yokai:broom_e_item")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
          } else {
            artisanBroomBuy(player, broom)
          }
        break
        case 1:
          if (moedas >= 300) {
            moedasScore.addScore(player, -300)
            player.runCommand("give @s yokai:broom_c_item")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
          } else {
            artisanBroomBuy(player, broom)
          }
        break
        case 2:
          if (moedas >= 500) {
            moedasScore.addScore(player, -500)
            player.runCommand("give @s yokai:broom_b_item")
            const buy = player.getDynamicProperty("npcBuy") ?? 0
            player.setDynamicProperty("npcBuy", buy + 1)
          } else {
            artisanBroomBuy(player, broom)
          }
        break
      }
    }
    if (escolha.selection == 4) artisanAba(player)
  })
}