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

world.afterEvents.playerDimensionChange.subscribe((event) => {
  const exam = event.player.getDynamicProperty("exam") ?? 0
  if (event.player.hasTag("estrutura_end") && exam == 0) {
    event.player.runCommand("tp @s ~~~ -90 0")
    event.player.setDynamicProperty("examLoc", event.player.location)
    const item = new ItemStack("yokai:ready", 1);
    item.keepOnDeath = true;
    item.lockMode = "slot";
    const inventory = event.player.getComponent("inventory").container;
    inventory.addItem(item);
    event.player.sendMessage({translate:"message.exam"})
    system.runTimeout(() => {
      event.player.runCommand(`tickingarea remove coliseu${event.player.id}`)
    }, 500)
  } else if (event.player.hasTag("combat") && event.toDimension.id == "minecraft:the_end") {
    event.player.sendMessage({translate:"message.exam2"})
    const item = new ItemStack("yokai:ready", 1);
    item.keepOnDeath = true;
    item.lockMode = "slot";
    const inventory = event.player.getComponent("inventory").container;
    inventory.addItem(item);
    event.player.setDynamicProperty("exam", 3)
    event.player.runCommand("event entity @e[r=50,type=yokai:sekke] sumir")
    event.player.runCommand("event entity @e[r=50,type=yokai:sekke_magnum] sumir")
    event.player.sendMessage({translate:"message.exam12"})
  } else if (exam == 3 && event.toDimension.id == "minecraft:overworld") {
      event.player.sendMessage({translate:"message.exam13"})
      event.player.setDynamicProperty("exam", 4)
  }
})

world.afterEvents.itemUse.subscribe((use) => {
  if (use.itemStack.typeId == "yokai:ready") {
    const exam = use.source.getDynamicProperty("exam") ?? 0
    const inventory = use.source.getComponent("inventory").container
    inventory.setItem(use.source.selectedSlotIndex, undefined)
    const loc = use.source.getDynamicProperty("examLoc")
      use.source.runCommand(`execute in the_end run tp @s ${loc.x} ${loc.y} ${loc.z} -90 0`)
      use.source.runCommand("tp @s ~~~ -90 20")
    if (exam == 0) {
      if (use.source.hasTag("anti")) {
        use.source.runCommand("camera @s set minecraft:free ease 0.3 linear pos ^1^2.3^2.5 facing @s")
        use.source.triggerEvent("broom_exam_asta")
        use.source.addTag("ui")
        system.runTimeout(() => {
          use.source.sendMessage({translate:"message.exam2"})
          use.source.sendMessage({translate:"message.exam7"})
          const item = new ItemStack("yokai:ready", 1);
          item.keepOnDeath = true;
          item.lockMode = "slot";
          const inventory = use.source.getComponent("inventory").container;
          inventory.addItem(item);
          use.source.setDynamicProperty("exam", 1)
        }, 40)
        system.runTimeout(() => {
          use.source.removeTag("ui")
          use.source.runCommand("camera @s clear")
          use.source.triggerEvent("atk_none")
        }, 50)
      } else {
        use.source.runCommand("camera @s set minecraft:free ease 0.3 linear pos ^0^5^2 rot ~ 90")
        use.source.triggerEvent("broom_exam")
        use.source.setDynamicProperty("vassoura", 1)
        use.source.addTag("camera")
      }
    } else if (exam == 1) {
      use.source.addTag("movement")
      use.source.addTag("camera")
      use.source.sendMessage({translate:"message.exam8"})
      system.runTimeout(() => {
        use.source.sendMessage("§a3")
      }, 80)
      system.runTimeout(() => {
        use.source.sendMessage("§22")
      }, 100)
      system.runTimeout(() => {
        use.source.sendMessage("§c1")
      }, 120)
      system.runTimeout(() => {
        use.source.runCommand("summon yokai:alvo ~10~1~ facing @s")
        use.source.runCommand("summon yokai:alvo ~10~1~6 facing @s")
        use.source.runCommand("summon yokai:alvo ~10~1~-6 facing @s")
        use.source.runCommand("summon yokai:alvo ~12~4~3 facing @s")
        use.source.runCommand("summon yokai:alvo ~12~4~-3 facing @s")
        use.source.runCommand("summon yokai:alvo ~12~4~9 facing @s")
        use.source.runCommand("summon yokai:alvo ~12~4~-9 facing @s")
        use.source.runCommand("summon yokai:alvo ~15~6~6 facing @s")
        use.source.runCommand("summon yokai:alvo ~15~6~-6 facing @s")
        use.source.runCommand("summon yokai:alvo ~19~10~ facing @s")
        use.source.removeTag("camera")
      }, 140)
      system.runTimeout(() => {
        use.source.sendMessage({translate:"message.exam9"})
      }, 340)
      system.runTimeout(() => {
        use.source.sendMessage({translate:"message.exam10"})
      }, 440)
      system.runTimeout(() => {
        use.source.sendMessage("§a4")
      }, 460)
      system.runTimeout(() => {
        use.source.sendMessage("§23")
      }, 480)
      system.runTimeout(() => {
        use.source.sendMessage("§c2")
      }, 500)
      system.runTimeout(() => {
        use.source.sendMessage("§41")
        use.source.runCommand("event entity @e[type=yokai:alvo,r=100] kill")
        use.source.removeTag("movement")
        use.source.setDynamicProperty("exam", 2)
        use.source.sendMessage({translate:"message.exam11"})
        const itemR = new ItemStack("yokai:ready", 1);
        itemR.keepOnDeath = true;
        itemR.lockMode = "slot";
        const inv = use.source.getComponent("inventory").container;
        inv.addItem(itemR);
      }, 520)
    } else if (exam == 2) {
      use.source.runCommand("summon yokai:sekke ~8~~ facing @s")
      use.source.addTag("combat")
    } else if (exam == 3) {
      const examPontos = use.source.getDynamicProperty("examPontos") ?? 0
      use.source.runCommand("camera @s fade time 0.2 0.3 0.2")
      use.source.addTag("ui")
      use.source.removeTag("combat")
      use.source.triggerEvent("look_up")
      use.source.runCommand("event entity @e[r=50,type=yokai:yami] hand")
      if (examPontos >= 60) {
      use.source.runCommand("event entity @e[r=50,type=yokai:jack] hand")
      }
      if (examPontos >= 80) {
      use.source.runCommand("event entity @e[r=50,type=yokai:gueldre] hand")
      }
      if (examPontos >= 140) {
      use.source.runCommand("event entity @e[r=50,type=yokai:rill] hand")
      }
      if (examPontos >= 160) {
      use.source.runCommand("event entity @e[r=50,type=yokai:dorothy] hand")
      }
      if (examPontos >= 180) {
      use.source.runCommand("event entity @e[r=50,type=yokai:charlotte] hand")
      }
      if (examPontos >= 240) {
      use.source.runCommand("event entity @e[r=50,type=yokai:fuego] hand")
      }
      if (examPontos >= 250) {
      use.source.runCommand("event entity @e[r=50,type=yokai:nozel] hand")
      }
      if (examPontos >= 270) {
      use.source.runCommand("event entity @e[r=50,type=yokai:vangeace] hand")
      }
      system.runTimeout(() => {
        use.source.runCommand("camera @s set minecraft:free pos  ~0.4~1.4~-1.2 rot -5 5")
      }, 6)
      system.runTimeout(() => {
        use.source.runCommand("camera @s fade time 0.2 0.3 0.2")
      }, 46)
      system.runTimeout(() => {
        use.source.runCommand("camera @s set minecraft:free pos ~18~11.4~-13 rot ~~")
      }, 52)
      system.runTimeout(() => {
        use.source.runCommand("camera @s set minecraft:free ease 7 linear pos ~18~11.4~13 Rot ~~")
      }, 56)
      system.runTimeout(() => {
        use.source.addTag("finalExam")
        menuExam(use.source, examPontos, -1, "somar")
      }, 186)
    }
  }
})


//alvo
world.afterEvents.entityHurt.subscribe((event) => {
  if (event.hurtEntity.typeId == "yokai:alvo" && !event.hurtEntity.hasTag("morreu")) {
    event.hurtEntity.addTag("morreu")
    event.hurtEntity.playAnimation("animation.alvo")
    const pontos = event.damageSource.damagingEntity.getDynamicProperty("examPontos") ?? 0
    event.damageSource.damagingEntity.setDynamicProperty("examPontos", pontos+10)
    
    system.runTimeout(() => {
      event.hurtEntity.triggerEvent("kill")
    }, 10)
  }
})

// Magnum Sekke
  world.afterEvents.entityHurt.subscribe((event) => {
    if (event.hurtEntity.typeId == "yokai:sekke_magnum") {
      let item = event.damageSource.damagingEntity.getComponent("inventory")
      if (!item) return
        item = item.container.getItem(event.damageSource.damagingEntity.selectedSlotIndex)
      if (item) {
        if (item.typeId == "yokai:slayer_asta") {
          const hit = event.hurtEntity.getDynamicProperty("hit") ?? 0
          event.hurtEntity.setDynamicProperty("hit", hit + 2)
          if (hit + 2 >= 5) {
            event.hurtEntity.triggerEvent("kill")
            event.hurtEntity.runCommand("event entity @e[type=yokai:sekke,r=5] no_magnum")
            system.runTimeout(() => {
              event.hurtEntity.triggerEvent("sumir")
            }, 4)
          }
        } else {
          const hit = event.hurtEntity.getDynamicProperty("hit") ?? 0
          event.hurtEntity.setDynamicProperty("hit", hit + 1)
          if (hit + 1 >= 5) {
            event.hurtEntity.triggerEvent("kill")
            event.hurtEntity.runCommand("event entity @e[type=yokai:sekke,r=5] no_magnum")
            system.runTimeout(() => {
              event.hurtEntity.triggerEvent("sumir")
            }, 4)
          }
        }
      } else {
        const hit = event.hurtEntity.getDynamicProperty("hit") ?? 0
        event.hurtEntity.setDynamicProperty("hit", hit + 1)
        if (hit + 1 >= 5) {
          event.hurtEntity.triggerEvent("kill")
          event.hurtEntity.runCommand("event entity @e[type=yokai:sekke,r=5] no_magnum")
          system.runTimeout(() => {
            event.hurtEntity.triggerEvent("sumir")
          }, 4)
        }
      }
    } else if (event.hurtEntity.typeId == "yokai:sekke") {
      const life = event.hurtEntity.getComponent("health").currentValue
      if (life <= 10 && life > 1 && !event.hurtEntity.hasTag("magnum2")) {
        event.hurtEntity.triggerEvent("magnum")
        event.hurtEntity.addTag("magnum2")
      } else if (life <= 1 && !event.hurtEntity.hasTag("process")) {
        const player = event.hurtEntity.dimension.getPlayers({
          location: event.hurtEntity.location,
          maxDistance: 50,
        })
        const timerCombat = player[0].getDynamicProperty("timerCombat") ?? 0
        const examPontos = player[0].getDynamicProperty("examPontos") ?? 0
        if (timerCombat <= 600) {
          player[0].setDynamicProperty("examPontos", examPontos+100)
        } else if (timerCombat > 600 && timerCombat <= 1200) {
          player[0].setDynamicProperty("examPontos", examPontos+80)
        } else if (timerCombat > 1200 && timerCombat <= 1800) {
          player[0].setDynamicProperty("examPontos", examPontos+60)
        } else if (timerCombat > 1800 && timerCombat <= 2400) {
          player[0].setDynamicProperty("examPontos", examPontos+40)
        } else if (examPontos > 2400) {
          player[0].setDynamicProperty("examPontos", examPontos+20)
        }
        event.hurtEntity.triggerEvent("death")
        event.hurtEntity.addTag("process")
        system.runTimeout(() => {
          if (!event.hurtEntity) return
            const item = new ItemStack("yokai:ready", 1);
            item.keepOnDeath = true;
            item.lockMode = "slot";
            const inventory = player[0].getComponent("inventory").container;
            inventory.addItem(item);
            player[0].setDynamicProperty("exam", 3)
            player[0].removeTag("combat")
            player[0].sendMessage({translate:"message.exam12"})
          event.hurtEntity.triggerEvent("sumir")
        }, 18)
      }
    }
  })
  
  
world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
  if (event.eventId == "no_magnum") {
    const view = event.entity.getViewDirection();
    const len = Math.sqrt(view.x * view.x + view.z * view.z);
    const front = {
      x: view.x / len,
      z: view.z / len
    };
    const player = event.entity.dimension.getPlayers({
      location: event.entity.location,
      maxDistance: 5,
    })
    
    const force = 1.2;
    if (player.length == 0) {
      event.entity.triggerEvent("dash")
      event.entity.applyImpulse({ x: front.x * force, y: 0.22, z: front.z * force });
    } else {
      event.entity.triggerEvent("atk_none")
    }
  }
})

world.afterEvents.playerSpawn.subscribe((event) => {
  if (event.player.hasTag("combat")) {
    const tp = event.player.getDynamicProperty("examLoc")
    event.player.runCommand(`execute in the_end run tp @s ${tp.x} ${tp.y} ${tp.z} -90 0`)
  }
})


const squads = [
  {
    squad: "pavoes",
    pontos: 160
  },
  {
    squad: "louva",
    pontos: 60
  },
  {
    squad: "rosa",
    pontos: 180
  },
  {
    squad: "aguias",
    pontos: 250
  },
  {
    squad: "alvorecer",
    pontos: 270
  },
  {
    squad: "reis",
    pontos: 240
  }, 
  {
    squad: "touros",
    pontos: 0
  },
  {
    squad: "cervos",
    pontos: 140
  },
  {
    squad: "orcas",
    pontos: 80
  }
  
  ]


function menuExam(player, pontos, array, op) {
  let search = false
  let squad = "none"
  while (!search) {
    if (op == "somar") {
      array++
    } else {
      array--
    }
    if (array < 0) {
      array = 8
    } else if (array > 8) {
      array = 0
    }
    if (pontos >= squads[array].pontos) {
      search = true
      squad = squads[array].squad
    }
    switch (squad) {
      case "pavoes":
        pavoes(player, pontos)
      break
      case "louva":
        louva(player, pontos)
      break
      case "rosa":
        rosa(player, pontos)
      break
      case "aguias":
        aguias(player, pontos)
      break
      case "alvorecer":
        alvorecer(player, pontos)
      break
      case "reis":
        reis(player, pontos)
      break
      case "touros":
        touros(player, pontos)
      break
      case "cervos":
        cervos(player, pontos)
      break
      case "orcas":
        orcas(player, pontos)
      break
    }
  }
}

function pavoes(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~19~11.8~-10 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.2"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) pavoes(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_pc")
      player.addTag("pc")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 0, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 0, "somar")
    }
  })
}

  
function louva(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~19~11.8~-7 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.3"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) louva(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_ld")
      player.addTag("ld")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 1, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 1, "somar")
    }
  })
}


function rosa(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~20~11.8~-5 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.4"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) rosa(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_ra")
      player.addTag("ra")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 2, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 2, "somar")
    }
  })
}


function aguias(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~21~11.8~-3 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.5"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) aguias(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_ap")
      player.addTag("ap")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 3, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 3, "somar")
    }
  })
}


function alvorecer(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~21~11.8~-0 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.6"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) alvorecer(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_ad")
      player.addTag("ad")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 4, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 4, "somar")
    }
  })
}


function reis(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~21~11.8~3 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.7"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) reis(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_rl")
      player.addTag("rl")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 5, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 5, "somar")
    }
  })
}


function touros(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~20~11.8~5 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.8"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) touros(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_tn")
      player.addTag("tn")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 6, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 6, "somar")
    }
  })
}


function cervos(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~19~11.8~7 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.9"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) cervos(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_cc")
      player.addTag("cc")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 7, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 7, "somar")
    }
  })
}


function orcas(player, pontos) {
  player.runCommand("camera @s set minecraft:free ease 0.3 linear pos ~19~11.8~10 rot ~~")
  const menu = new ActionFormData()
    .title({translate:"npc.title.10"})
    .button({translate:"npc.button.5"})
    .button("")
    .button("")
  menu.show(player).then(escolha => {
    if (escolha.canceled) orcas(player)
    if (escolha.selection == 0) {
      player.runCommand("give @s yokai:cloak_op")
      player.addTag("op")
      player.removeTag("ui")
      player.triggerEvent("atk_none")
      const voltar = player.getDynamicProperty("voltar")
      player.removeTag("estrutura_end")
      player.runCommand(`execute in overworld run tp @s ${voltar.x} ${voltar.y} ${voltar.z}`)
      player.runCommand("gamemode 0")
      player.runCommand("camera @s clear")
      player.runCommand("fog @s remove exam")
    }
    if (escolha.selection == 1) {
      menuExam(player, pontos, 8, "subtrair")
    }
    if (escolha.selection == 2) {
      menuExam(player, pontos, 8, "somar")
    }
  })
}