import { world, system, ItemStack, Dimension } from "@minecraft/server";
function Element(projetil) {
  const family = projetil.getComponent("type_family").getTypeFamilies()
  const noFamilies = ["absorb", "anular"]
  const element = family.filter(f => !noFamilies.includes(f))
  return element[0]
}
  
//Dweller Asta
system.beforeEvents.startup.subscribe((event) => {
  event.itemComponentRegistry.registerCustomComponent('yokai:dweller_asta', {
    onUse: use => {
      if (use.source.hasTag("no_skill")) return
        const projetil = use.source.dimension.getEntities({
          location: use.source.location,
          maxDistance: 15,
          families: ["absorb"],
        })[0]
        if (projetil) {
          const mana = use.source.getDynamicProperty("mana")
          if (mana >= 3) {
            use.source.setDynamicProperty("mana", mana - 3)
            const element = Element(projetil)
            const inventory = use.source.getComponent("inventory").container
            const sword = new ItemStack(`yokai:dweller_asta_${element}`, 1)
            sword.keepOnDeath = true
            sword.lockMode = "slot"
            inventory.setItem(7, sword)
            projetil.triggerEvent("kill")
            use.source.playSound("dweller_charge")
          }
        } else {
          const mana = use.source.getDynamicProperty("mana")
          if (mana >= 5) {
            use.source.setDynamicProperty("mana", mana - 5)
            const inventory = use.source.getComponent("inventory").container
            const sword = new ItemStack(`yokai:dweller_asta_anti`, 1)
            sword.keepOnDeath = true
            sword.lockMode = "slot"
            inventory.setItem(7, sword)
            use.source.playSound("dweller_charge")
          }
        }
    }
  })
});
  
    system.beforeEvents.startup.subscribe((event) => {
    event.itemComponentRegistry.registerCustomComponent('yokai:dweller_asta_mana', {
      onUse: use => {
        if (use.source.hasTag("no_skill")) return
        const player = use.source
        const inventory = player.getComponent("inventory").container
        const sword = new ItemStack(`yokai:dweller_asta`, 1)
        sword.keepOnDeath = true
        sword.lockMode = "slot"
        const item = use.itemStack.typeId.split("_")[2]
        player.triggerEvent("dweller_slash")
        player.playSound("shoot_dweller")
        player.triggerEvent(`dweller_${item}`)
        system.runTimeout(() => {
          player.triggerEvent("atk_none")
          inventory.setItem(7, sword)
        }, 10)
      }
    })
  });
  
  
  system.afterEvents.scriptEventReceive.subscribe((data) => {
    const mana = data.sourceEntity.typeId.split("_")
    if (mana[0] == "yokai:dweller" && data.id == "yokai:damage") {
      let timer = data.sourceEntity.getDynamicProperty("timer") ?? 0
      data.sourceEntity.setDynamicProperty("timer", timer + 1)
      timer = data.sourceEntity.getDynamicProperty("timer") ?? 0
      const player = data.sourceEntity.getComponent("minecraft:projectile")
      const mobs = data.sourceEntity.dimension.getEntities({
        location: data.sourceEntity.location,
        maxDistance: 5.5,
        excludeTypes: ["item"],
      })
      let acertou = false
      const maxX = 5.5
      const maxY = 1.5
      if (timer >= 48) {
        data.sourceEntity.triggerEvent("kill")  
      } else {
        
        for (const mob of mobs) {
          if (mob.id != data.sourceEntity.id && mob.id != player.owner.id && mob.typeId != "minecraft:xp_orb") {
            const position = mob.location
            const dx = position.x - data.sourceEntity.location.x;
            const dy = position.y - data.sourceEntity.location.y;
            const dz = position.z - data.sourceEntity.location.z;
          
            const baseX = Math.sqrt(dx * dx + dz * dz);
            const baseY = Math.abs(dy);
            if (baseX <= maxX && baseY <= maxY) {

              
                if (mana[1] == "fire") {
                  mob.setOnFire(4, true)
                } else if (mana[1] == "anti") {
                  if (mob.typeId == "minecraft:player") {
                    const pMana = mob.getDynamicProperty("mana")
                    mob.setDynamicProperty("mana", pMana - 2)
                  } 
                } else if (mana[1] == "wind") {
                  const velocity = data.sourceEntity.getVelocity();
                  const magnitude = Math.sqrt(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z);
                  if (magnitude > 0) {
                    const strength = 3.4;
                    const knockback = {
                      x: (velocity.x / magnitude) * strength,
                      z: (velocity.z / magnitude) * strength,
                    };
                    mob.applyKnockback(knockback, 0.4);
                  }
                }
           
              

              mob.applyDamage(8, {
                damagingEntity: player.owner,
                damagingProjectile: data.sourceEntity,
              })
             

              acertou = true  
              if (mob.typeId == "yokai:dragon_nest") break
            }
          }
        }
        if (acertou) {
          data.sourceEntity.triggerEvent("kill")  
        }
      }
    }
  })

  
  //Destroyer Asta
  system.beforeEvents.startup.subscribe((event) => {
    event.itemComponentRegistry.registerCustomComponent('yokai:destroyer_asta', {
      onUse: use => {
        if (use.source.hasTag("no_skill")) return
          const mana = use.source.getDynamicProperty("mana")
          if (mana >= 9) {
            use.source.triggerEvent("destroyer_zone")
            use.source.playSound("destroyer_zone")
            use.source.setDynamicProperty("mana", mana - 9)
            const mobs = use.source.dimension.getEntities({
              location: use.source.location,
              maxDistance: 15,
              families: ["anular"],
            })
            for (const mob of mobs) {
              if (mob.id != use.source.id) {
                if (mob.typeId == "minecraft:player") {
                  if (mob.hasTag("pele_mana")) {
                    mob.removeEffect("speed")
                    mob.removeEffect("resistance")
                    mob.removeTag("pele_mana")
                    mob.triggerEvent("none_skin")
                  }
                } else if (mob.typeId == "yokai:dragon_nest") {
                  
                  mob.dimension.spawnParticle("yokai:dragon_nest_splash", mob.location)
                  mob.triggerEvent("sumir")
                } else {
                  mob.triggerEvent("kill")
                }
              }
            }
            system.runTimeout(() => {
              use.source.triggerEvent("atk_none")
            }, 10)
          }
      }
    })
  });
  