import { world, system, ItemStack, EquipmentSlot, WorldAfterEvents} from "@minecraft/server";
import abilities from './abilities/import.js';
import skills from './skills/import.js';
import weapons from './weaponTypes/import.js';
import mobs from './mob_attacks/import.js';
import effects from './combatEffects/import.js';
import { ModifiedEntities } from "./configs.js";
import { weaponTypeSplicer, stunLock, calculateDamageTaken, backShotCheck, getGamemode, coordExtractor, levelGetter} from './util/utils.js';
import { DelayedSelector, ability_writing, pellet_container, abilityForm, styleChooser, adminOptions} from './util/forms.js';
import { spawnProjectile } from './util/attackMethods.js';
import { setAmmounthand_blaster } from './weaponTypes/weapons/hand_cannon.js';
import { teleporter } from './util/movements.js';
import { Vector3 } from './util/vector3.js';
import { getKnockMap } from './util/attackMethods.js';
import { MainHandChangeEvent } from './util/MainHandChangeEvent.js';
import {JsonDatabase } from "./util/con-database.js";
let selectedSlot = new JsonDatabase("selectedSlot")

const skills_list = Object.values(skills);

let perf = new JsonDatabase("perf")
let AirCharges = new JsonDatabase("AirCharges")
let abilityStorage = new JsonDatabase("abilitiesStorage")
let comboCounter = new JsonDatabase("comboCounter")
let worldStatus = new JsonDatabase("worldStatus")



let tablesInUse = new Set()
let 武器 = {}
let 専ブラ = weapons
for(let 人生 in 専ブラ) {
    武器[人生] = 専ブラ[人生]
}
//scoreboards
let generalis = world.scoreboard
try {
    generalis.addObjective("stunned")
    generalis.addObjective("stunbreak")
    generalis.addObjective("stunTimer")
    generalis.addObjective("stunCheck")
    generalis.addObjective("posture")
    generalis.addObjective("chargecount")
    generalis.addObjective("pState")
} catch (error) {
    
}

let stunnedScores = generalis.getObjective("stunned")
let stunBreakScores = generalis.getObjective("stunbreak")
let stunTimerScores = generalis.getObjective("stunTimer")
let stunCheckScores = generalis.getObjective("stunCheck")
let postureScore = generalis.getObjective("posture")
let chargeCountScore = generalis.getObjective("chargecount")
let pStateScore = generalis.getObjective("pState")
let Strength = generalis.getObjective("Strength")
let Agility = generalis.getObjective("Agility")
let Dexterity = generalis.getObjective("Dexterity")
let Intelligence = generalis.getObjective("Intelligence")
let Endurance = generalis.getObjective("Endurance")
let PhysicalResistance = generalis.getObjective("PhysicalResistance")
let MagicResistance = generalis.getObjective("MagicResistance")
let Vitality = generalis.getObjective("Vitality")
let Charisma = generalis.getObjective("Charisma")


WorldAfterEvents.prototype.mainHandChangeEvent = new MainHandChangeEvent()
function loreTrigger(player, trigger, item) {
	let attacker = player.getDynamicProperty("attacking")
	if(attacker != 1 && trigger != "ability_scroll"){
	    weapons[trigger].setCore(player, item, abilityStorage) 
	} else if(attacker != 1 && trigger == "ability_scroll"){
	    let level = levelGetter(item.getTags())
	    weapons[trigger].setCore(player, item, level) 
	}
}

function MakeScoreboards(){
    let skillet = Array.from(skills_list)
    for(let i = 0; i < skillet.length; i++) {
        try{
            generalis.addObjective(skillet[i].name)
        } catch(err) {

        }
    }
}

function MakeStatboards(){
    let skillet = ["Strength", "Agility", "Dexterity", "Intelligence", "Endurance", "PhysicalResistance", "MagicResistance", "Vitality", "Charisma", "waterResist", "waterLevel", "waterBoost", "fireResist", "fireLevel", "fireBoost","earthResist","earthLevel","earthBoost","windResist","windLevel","windBoost","darkResist","darkLevel","darkBoost","lightResist","lightLevel","lightBoost","slashResist","slashBoost","bluntResist","bluntBoost","pierceResist","pierceBoost"]
    for(let i = 0; i < skillet.length; i++) {
        try{
            generalis.addObjective(skillet[i])
        } catch(err) {

        }
    }
}

function SetStatboards(entity,multipliers){
    let skillet = ["Strength", "Agility", "Dexterity", "Intelligence", "Endurance", "PhysicalResistance", "MagicResistance", "Vitality", "Charisma", "waterResist", "waterLevel", "waterBoost", "fireResist", "fireLevel", "fireBoost","earthResist","earthLevel","earthBoost","windResist","windLevel","windBoost","darkResist","darkLevel","darkBoost","lightResist","lightLevel","lightBoost","slashResist","slashBoost","bluntResist","bluntBoost","pierceResist","pierceBoost"]
    for(let i = 0; i < skillet.length; i++) {
        try{
            generalis.getObjective(skillet[i]).setScore(entity, Math.floor(Math.random() * multipliers[skillet[i]]))
        } catch(err) {

        }
    }
}

function directionCheck(cali) {
    let velocity = cali.getVelocity();
    let rotation = cali.getRotation();
    let rot_old = Math.floor((Math.atan2(velocity.z, velocity.x) * 180 / Math.PI - 90));
    rot_old < -180 ? rot_old = rot_old + 360 : rot_old
    let dirCheck = Math.abs(rot_old - Math.floor(rotation.y))
    dirCheck = Math.min(dirCheck, (360 - dirCheck))
    return dirCheck
}

function Vector3_cross(v1, v2) {
    return {
      x: v1.y * v2.z - v1.z * v2.y,
      y: v1.z * v2.x - v1.x * v2.z,
      z: v1.x * v2.y - v1.y * v2.x
    }
}
function DEG_TO_RAD(deg) {
    return (deg / 180) * Math.PI;
}
  
function toSphericalFromRotation(dist,rot) {
    const y_rot = -DEG_TO_RAD(rot.y), x_rot = DEG_TO_RAD(90 + rot.x);
    return {
        x: dist * Math.sin(y_rot) * Math.sin(x_rot),
        z: dist * Math.cos(y_rot) * Math.sin(x_rot),
        y: dist * Math.cos(x_rot)
    }
}

function abilityTrigger(player, trigger, weapon, type) {
    let attackCheckers = true
    stunnedScores.getScore(player) != 1 && stunBreakScores.getScore(player) != 1 && player.getDynamicProperty("attacking") != 1 ? attackCheckers = true : attackCheckers = false 
    if(trigger != "O0" && attackCheckers == true && JSON.parse(player.getDynamicProperty("entityStatus")).abilityCd[abilities[trigger].name] == undefined){
        let weaponType = weaponTypeSplicer(weapon)
        player.addTag("attack")
	    abilities[trigger].execute(player, weaponType, type, weapon);
	}
}

function execute_book(player, weaponType, learned, item, level) {
   learned == "Art of Slashing" ? learned = "slashing" : learned == "Cutting Rocks And Minerals" ? learned = "cutting" : learned == "Moving around" ? learned = "movement" : learned = learned
   if (learned == "unspecified"||learned == ""||learned == undefined) {
        weapons[weaponType].book_select(player, item)
   } else {
        switch(weaponType) {
            case "skill_book": {
                if(generalis.getObjective(learned) == undefined) {
                    skills[learned].learn(player);
                    player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, undefined)
                    player.onScreenDisplay.setActionBar(`Learned ${learned}`)
                } else {
                    skills[learned].addLevel(player,level);
                    player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, undefined)
                    player.onScreenDisplay.setActionBar(`Added ${level} level to ${learned}`)
                }
                
            } break;
            case "learning_book": {
                if(generalis.getObjective(learned) == undefined) {
                    skills[learned].learn(player);
                    player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, undefined)
                    player.onScreenDisplay.setActionBar(`Learned ${learned}`)
                } else {
                    skills[learned].addLevel(player,level);
                    player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, undefined)
                    player.onScreenDisplay.setActionBar(`Added ${level} level to ${learned}`)
                }
                
            } break;
        }  
   }
}


function weaponsTrigger(player, trigger, weapon, mode, burn) {
    stunBreakScores.addScore(player,0)
    let key
    let che4ck = stunBreakScores.getScore(player)
	try{
	    let tipped = weapon.getLore()[0]
        tipped != undefined && tipped != '' ? key = `${tipped.split("|")[0]}` : key = ''
	} catch(err) {
	    key = ''
	}

    if(mode == "cancel") return;
	if(trigger != "skill_book" && trigger != "ability_scroll" && trigger != "learning_book" && che4ck != 1 && player.getDynamicProperty("attacking") != 1 ){
	    player.setDynamicProperty("attacking",1)
	    weapons[trigger].execute(player, weapon, key, mode, burn);
	}
}

function skillLearner(player, skill) {
	 skills[skill].learn(player);
}

function mobsTrigger(player, trigger, mode) {
    let key = ""
    if(mode == "cancel") return;
    stunBreakScores.addScore(player,0)
    let che4ck = stunBreakScores.getScore(player)
    let damage
    let stunDamage
    let damageType
	try {
        damage = ModifiedEntities.get(player.typeId).damage ?? 2
        stunDamage = ModifiedEntities.get(player.typeId).stunDamage ?? 3
        damageType = ModifiedEntities.get(player.typeId).damageType ?? "slash"
    } catch (error) {
        damage = 2
        stunDamage = 3
        damageType = "slash"
    }
    if ((player.getDynamicProperty("attacking") != 1 || player.getDynamicProperty("attacking") == undefined) && che4ck != 1) {
        if (player.getDynamicProperty("combo") == undefined) {
            player.setDynamicProperty("combo", 1)
        }
        player.setDynamicProperty("attacking", 1)
        if (trigger == "unidentified") {
            mobs[trigger].execute(player, key, mode, damage, stunDamage, damageType);
            
        } else {
            mobs[trigger].execute(player, key, mode);
        }

    }
}

function AttackChecker(player, burn) {
    let cali = player
    if (cali.getDynamicProperty("attacking") != 1) {
        
        let equipment = cali.getComponent("minecraft:equippable");
        let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
        let offhand = equipment?.getEquipmentSlot(`Offhand`)?.getItem()

        const inv = mainhand
        let attck = cali.getDynamicProperty("attacking")
        if (inv == undefined) return;
        if (attck == 1) {
            return;
        }
        let playerStats = JSON.parse(player.getDynamicProperty("resetingStatus"))
        let sneak = cali.isSneaking
        let sprint = cali.isSprinting
        let check = playerStats.inputs
        
        let jump = cali.isJumping
        let onGround = cali.isOnGround
        let blue = weaponTypeSplicer(inv)
        let red
        let AirTimeSkill = playerStats.AirTime
        let dirCheck = directionCheck(cali)
        try {
            red = weaponTypeSplicer(offhand)
        } 
        catch(err) {
            red = "unarmed"
        }
        if(blue == "skill_book" || blue == "ability_scroll" || blue == "learning_book") return "normal";
        
        let velocity = cali.getVelocity();
        let nemuru = (Math.sqrt(velocity.x ** 2 + velocity.z ** 2) * 20).toFixed(1);
        let AttackChecks = weapons[blue]?.available_moves
        let compos = cali.getDynamicProperty("combo")
        let OnAirge = generalis.getObjective("airTimer").getScore(player)
        //let playerSkills = JSON.parse(player.getDynamicProperty("entitySkills"))
        let Templ = JSON.parse(cali.getDynamicProperty("entityStatus")).dualwieldCheck
        //(blue && red) == "longsword" && !plyerSkills.has("dual_wield_longsword") ? Templ = "normal" : Templ = Templ
        let CheckReturn
        try{
            if (pStateScore == 2) return "flying";
        } catch(err) {}
        if(playerStats.bide >= 30) {
            return "bide";
        }
        if(!onGround) {
            if(AttackChecks.includes(check[0])) {
                CheckReturn = check[0]
            } else if(AirTimeSkill < 10) {
                if(OnAirge < 10){
                    if(red != "unarmed" && red != "shield") {
                        if(red == blue && Templ != "offhand") {
                            CheckReturn = "dual_wield_jump"
                        } else if(weapons[blue].dual_wield.includes(red)) {
                            if(comboCounter.get(cali.id) == 1) {
                                CheckReturn = "onehand_jump"
                            } else {
                                CheckReturn = "offhand_jump"
                            }
                        } else {
                            CheckReturn = "jump"
                        }
                    } else { 
                        CheckReturn = "jump"
                    }
                } else {
                    CheckReturn = "on_air"
                }
                
            } else {
                CheckReturn = "on_air_combo"
            }
        } else {
            if(burn == "") {
                if(!sneak) {
                    if( AttackChecks.includes(check[0])) {
                        CheckReturn = check[0]
                    } else if(red == "shield") {
                        CheckReturn = "offhand_shield"
                    } else if(red != "unarmed" && red != "shield" && !sprint) {
                        if(red == blue && Templ != "offhand") {
                            CheckReturn = "dual_wield"
                        } else if(weapons[blue].dual_wield.includes(red)) {
                            if(comboCounter.get(cali.id) == 1) {
                                CheckReturn = "onehand"
                            } else {
                                CheckReturn = "offhand"
                            }
                        } else {
                            CheckReturn = "normal"
                        }
                    } else {
                        if(sprint == true) {
                            if(red != "unarmed" && red != "shield") {
                                if(red == blue && Templ != "offhand") {
                                    CheckReturn = "dual_wield_sprint"
                                } else if(weapons[blue].dual_wield.includes(red)) {
                                    if(comboCounter.get(cali.id) == 1) {
                                        CheckReturn = "onehand_sprint"
                                    } else {
                                        CheckReturn = "offhand_sprint"
                                    }
                                } else {
                                    CheckReturn = "sprint"
                                }
                            } else { 
                                CheckReturn = "sprint"
                            }
                        } else {
                            if(dirCheck > 120 && AttackChecks.includes("back_attack") && nemuru != 0.0) {
                                CheckReturn = "back_attack"
                            } else {
                                CheckReturn = "normal"
                            }
                        }
                    }
                }
            } else {
                let behind = backShotCheck(cali, burn)
                stunBreakScores.addScore(burn, 0)
                let executeCheck = stunBreakScores.getScore(burn)
                if(behind && sneak && AttackChecks.includes("assasinate")) {
                    CheckReturn = "assasinate"
                } else if(executeCheck == 1) {
                    CheckReturn = "execute"
                } else {
                    if(!sneak) {
                        if(check[0] != undefined && AttackChecks.includes(check[0])) {
                            CheckReturn = check[0]
                        } else if(red == "shield") {
                            CheckReturn = "offhand_shield"
                        } else if(red != "unarmed" && red != "shield" && !sprint) {
                            if(red == blue && Templ != "offhand") {
                                CheckReturn = "dual_wield"
                            } else if(weapons[blue].dual_wield.includes(red)) {
                                if(comboCounter.get(cali.id) == 1) {
                                    CheckReturn = "onehand"
                                } else {
                                    CheckReturn = "offhand"
                                }
                            } else {
                                CheckReturn = "normal"
                            }
                        } else {
                            if(sprint == true) {
                                if(red != "unarmed" && red != "shield") {
                                    if(red == blue && Templ != "offhand") {
                                        CheckReturn = "dual_wield_sprint"
                                    } else if(weapons[blue].dual_wield.includes(red)) {
                                        if(comboCounter.get(cali.id) == 1) {
                                            CheckReturn = "onehand_sprint"
                                        } else {
                                            CheckReturn = "offhand_sprint"
                                        }
                                    } else {
                                        CheckReturn = "sprint"
                                    }
                                } else { 
                                    CheckReturn = "sprint"
                                }
                            } else {
                                if(dirCheck > 120 && AttackChecks.includes("back_attack") && nemuru != 0.0) {
                                    CheckReturn = "back_attack"
                                } else {
                                    CheckReturn = "normal"
                                }
                            }
                        }
                    }
                }
            }
        }
        playerStats["inputs"] = []
        player.setDynamicProperty("resetingStatus", JSON.stringify(playerStats))
        return CheckReturn
    }
}

function InventoryWait(target){
    return new Promise((resolve,reject) => {
        try{
            let espejos = system.runInterval(()=>{
                if(target == undefined) { 
                    reject("no bitches") 
                    system.clearRun(espejos)
                }
                let container
                try{
                    container = target.getComponent("inventory").container
                } catch(err){
                    reject("no bitches") 
                    system.clearRun(espejos)
                }
                let weaponSlot
                try{
                    weaponSlot = container.getItem(0)
                  } catch(error){
                    weaponSlot = "unarmed"
                  }
                let weaponSlotType
                try{
                  weaponSlotType = weaponTypeSplicer(weaponSlot)
                } catch(error){
                  weaponSlotType = "unarmed"
                }
                if(weaponSlotType != "unarmed") {
                  let Storager = JSON.parse(weaponSlot.getDynamicProperty("abilities"))
                  for(let veo = 0;veo < Storager.length;veo++) {
                    if(Storager[veo].Id != "O0") {
                      let Item = new ItemStack(`minced:ability_scroll`,1)
                      Item.setLore([Storager[veo].Id])
                      container.setItem((veo + 1), Item)
                    }
                    if(veo == Storager.length - 1) {
                      resolve("item_placed")
                      system.clearRun(espejos)
                    }
                  }
                }
              },1)
              system.runTimeout(()=>{
                system.clearRun(espejos)
                tablesInUse.delete(target.id)
                reject("Timeout")
              },1000)
        } catch(error) {
            reject(error)
        }
    });
}

async function AfterWaitInventory(target) {
    const checker = await InventoryWait(target)
    if(checker == "no bitches") return;
    if(checker == "item_placed") {
      let espejo = system.runInterval(()=>{
        let container = target.getComponent("inventory").container
        let weapon = container.getItem(0)
        if(weapon == undefined) {
            container.clearAll()
            AfterWaitInventory(target)
            system.clearRun(espejo)
        }
        let weaponType = weaponTypeSplicer(weapon)
        let Storager = JSON.parse(weapon?.getDynamicProperty("abilities"))
        for(let una = 0;una < 5; una++){
          let weaponSlotter = container.getItem(una + 1)
          let abilitySlot
          una < 3 ? abilitySlot = "ability" : una == 3 ? abilitySlot = "charge" : abilitySlot = "ultimate"
          try{
            if(!weaponSlotter.getTags().includes("weaponType:is_ability_scroll")) {
                target.dimension.spawnItem(weaponSlotter, target.location)
                container.setItem(una + 1, undefined)
            }
          } catch(error){
            
          }
          
          try{
            let weaponSlot = weaponSlotter.getLore()[0]
            let Stats = weaponSlot.split("<")
            let ability = abilities[Stats[0]]
            let weaponFilter = ability.filters
            let abilitySlots = ability.slots
            if(Stats[0] != Storager[una].Id && (weaponFilter.includes(weaponType)||weaponFilter.includes("all")) && abilitySlots.includes(abilitySlot)) {
              Storager[una]["Id"] = Stats[0]
            } else if (Stats[0] != Storager[una].Id) {
              Storager[una]["Id"] = "O0"
              target.dimension.spawnItem(weaponSlotter, target.location)
              container.setItem(una + 1, undefined)
            }
          } catch(error){ 
            Storager[una]["Id"] = "O0"
          }
          
        }
        weapon.setDynamicProperty("abilities", JSON.stringify(Storager))
        container.setItem(0,weapon)
      },7)
    }
}

let inControl = new Set()
let canDodge = new Set()
let InADaze = new Set()

world.afterEvents.playerButtonInput.subscribe((eventData) => {
    let p = eventData.player
    let but = eventData.button
    let butState = eventData.newButtonState
    let combater = p.getProperty("mode:combat")
    if(combater == 1) {
        let equipment = p.getComponent("minecraft:equippable");
        let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
        let offhand = equipment?.getEquipmentSlot(`Offhand`)?.getItem()
        let weaponType = weapons[weaponTypeSplicer(mainhand)]
        let offhandType = weaponTypeSplicer(offhand)
        let blockChecker = ""
        offhandType != "unarmed" ? blockChecker = `${offhandType}_` : blockChecker = ""
        let animpref = weaponType?.stylePrefixes[p.getProperty("fighting:style")]
        animpref == undefined || animpref == "" ? animpref = weaponType?.stylePrefixes[0] : animpref = animpref
        if(InADaze.has(p.id)) {
            if(but == "Sneak" ) {
                InADaze.delete(p.id)
                let Statistic = JSON.parse(p.getDynamicProperty("resetingStatus"))
                Statistic["inputs"] = []
                p.playAnimation(`animation.${animpref}.combat_stance_${blockChecker}slide`)
                let iki = 0
                p.applyKnockback(p.getViewDirection().x, p.getViewDirection().z, 0.5, 0)
                let ruuru = system.runInterval(()  => {
                    iki = iki + 1
                    p.applyKnockback(p.getViewDirection().x, p.getViewDirection().z, 2.5, 0)
                    if(iki >= 3){
                        p.setDynamicProperty("resetingStatus", JSON.stringify(Statistic))
                        system.clearRun(ruuru)
                    }
                },3)
            } 
        } else {
            if(but == "Jump" && butState != "Released" ) {
                if(canDodge.has(p.id)) {
                    canDodge.delete(p.id)
                    if(generalis.getObjective("super_jump").getScore(p) >= 1) {
                        let jumpValue = AirCharges.get(p.id)
                        if(jumpValue > 0) {
                            p.applyKnockback(p.getViewDirection().x, p.getViewDirection().z, 0, 1.5)
                            p.addEffect("slow_falling", 5, { amplifier: 3, showParticles: false })
                            AirCharges.set(p.id, jumpValue - 1)
                        }
                    }
                }
            } else if(but == "Sneak" && butState != "Released" ) {
                if(canDodge.has(p.id) == false) {
                    canDodge.add(p.id)
                    system.runTimeout(() => {
                        canDodge.delete(p.id)
                    }, 10)
                }
            } else if(butState == "Released" ) {
                if(canDodge.has(p.id) == true) {
                    let maketak = p.inputInfo.getMovementVector()
                    let stamina =  generalis.getObjective("exhaust").getScore(p)
                    let onGround = p.isOnGround
                    let onSneak = p.isSneaking
                    let sneakCDs = JSON.parse(p.getDynamicProperty("resetingStatus"))
                    if(stamina > 10 && sneakCDs.sneakCD != 1 && onGround && sneakCDs.inputs[sneakCDs.inputs.length - 1] != "S" && !onSneak) {
                        let gm = getGamemode(p);
                        let consumption = 0;
                        gm != "creative" ? consumption = 10 : consumption = 0
                        if(maketak.y < 0){
                            let dodgeValue = weaponType?.back_dodge
                            p.applyKnockback(p.getViewDirection().x, p.getViewDirection().z, dodgeValue[0], dodgeValue[1])
                            system.runTimeout(()=>{
                                p.applyKnockback(p.getViewDirection().x, p.getViewDirection().z, dodgeValue[0], dodgeValue[1])
                            },3)
                            let mover = JSON.parse(p.getDynamicProperty("resetingStatus"))
                            mover.inputs.push("back_dodge")
                            mover["sneakCD"] = 1
                            p.setDynamicProperty("resetingStatus", JSON.stringify(mover))
                            p.triggerEvent("Iframe")
                            p.addTag("Immune")
                            p.playAnimation(`animation.${animpref}.combat_stance_${blockChecker}roll_backward`)     
                        } else if(maketak.y > 0){
                            let dodgeValue = weaponType?.front_dodge
                            p.applyKnockback(p.getViewDirection().x, p.getViewDirection().z, dodgeValue[0], dodgeValue[1])
                            system.runTimeout(()=>{
                                p.applyKnockback(p.getViewDirection().x, p.getViewDirection().z, dodgeValue[0], dodgeValue[1])
                            },3)
                            let mover = JSON.parse(p.getDynamicProperty("resetingStatus"))
                            mover.inputs.push("front_dodge")
                            mover["sneakCD"] = 1
                            p.setDynamicProperty("resetingStatus", JSON.stringify(mover))
                            p.addTag("Immune")
                            p.playAnimation(`animation.${animpref}.combat_stance_${blockChecker}roll_forward`)
                            p.triggerEvent("Iframe")
                            system.runTimeout(()=> {
                                let mover = JSON.parse(p.getDynamicProperty("resetingStatus"))
                                mover["inputs"] = []
                                p.setDynamicProperty("resetingStatus", JSON.stringify(mover))
                                p.removeTag("Immune")
                            },30)
                        } else if(maketak.x > 0){
                            let dodgeValue = weaponType?.left_dodge
                            if(dodgeValue == "none") return;
                            const Forward = toSphericalFromRotation(1, {y: p.getRotation().y, x: 0});
                            const Down = {x: 0, y: -1, z: 0};
                            const Left = Vector3_cross(Forward, Down);
                            p.applyKnockback(Left.x, Left.z, dodgeValue[0], dodgeValue[1])
                            system.runTimeout(()=>{
                                p.applyKnockback(Left.x, Left.z, dodgeValue[0], dodgeValue[1])
                            },3)
                            let mover = JSON.parse(p.getDynamicProperty("resetingStatus"))
                            mover.inputs.push("front_dodge")
                            mover["sneakCD"] = 1
                            p.setDynamicProperty("resetingStatus", JSON.stringify(mover))
                            p.addTag("Immune")
                            p.playAnimation(`animation.${animpref}.combat_stance_${blockChecker}roll_left`)
                            p.triggerEvent("Iframe")
                            system.runTimeout(()=> {
                                let mover = JSON.parse(p.getDynamicProperty("resetingStatus"))
                                mover["inputs"] = []
                                p.setDynamicProperty("resetingStatus", JSON.stringify(mover))
                                p.removeTag("Immune")
                            },30)
                        } else if(maketak.x < 0){
                            let dodgeValue = weaponType?.right_dodge
                            if(dodgeValue == "none") return;
                            const Forward = toSphericalFromRotation(1, {y: p.getRotation().y, x: 0});
                            const Down = {x: 0, y: 1, z: 0};
                            const Left = Vector3_cross(Forward, Down);
                            p.applyKnockback(Left.x, Left.z, dodgeValue[0], dodgeValue[1])
                            system.runTimeout(()=>{
                                p.applyKnockback(Left.x, Left.z, dodgeValue[0], dodgeValue[1])
                            },3)
                            let mover = JSON.parse(p.getDynamicProperty("resetingStatus"))
                            mover.inputs.push("front_dodge")
                            mover["sneakCD"] = 1
                            p.setDynamicProperty("resetingStatus", JSON.stringify(mover))
                            p.addTag("Immune")
                            p.playAnimation(`animation.${animpref}.combat_stance_${blockChecker}roll_right`)
                            p.triggerEvent("Iframe")
                            system.runTimeout(()=> {
                                let mover = JSON.parse(p.getDynamicProperty("resetingStatus"))
                                mover["inputs"] = []
                                p.setDynamicProperty("resetingStatus", JSON.stringify(mover))
                                p.removeTag("Immune")
                            },30)
                        }
                        system.runTimeout(()=> {
                            p.addEffect("slow_falling", 5, { amplifier: 3, showParticles: false })
                            p.triggerEvent("Iframe_remove")
                            p.removeTag("Immune")
                        },5)
                        p.runCommand(`execute as @s run scoreboard players set @s exhregen 200`)
                        p.runCommand(`execute as @s run scoreboard players remove @s exhaust ${consumption}`)
                        system.runTimeout(()=> {
                            let sneakCDss = JSON.parse(p.getDynamicProperty("resetingStatus"))
                            sneakCDss["sneakCD"] = 0
                            p.setDynamicProperty("resetingStatus", JSON.stringify(sneakCDss))
                        },20)
                    }        
                }
            }
        }
    }
})

system.runInterval(()=>{
    for(const player of world.getPlayers()) {
        let combat = generalis.getObjective("combatTimer").getScore(player)
        let combater = player.getProperty("mode:combat")
        let playerControls
        if(combat > 0) {
            generalis.getObjective("combatTimer").addScore(player, -1)
            if(combater == 1 && combat <= 1) {
                generalis.getObjective("combatTimer").addScore(player, -1)
                player.setProperty("mode:combat", 0)
            }
        }
        let chekStm = generalis.getObjective("exhaust").getScore(player)
        postureScore.addScore(player, 0)
        let chekPst = postureScore.getScore(player)
        let playerStat = JSON.parse(player.getDynamicProperty("resetingStatus"))
        if(playerStat.oldposture != chekPst || playerStat.oldstamina != chekStm || playerStat.powerBar != playerStat.oldpowerbar) {
            let stamina = (Math.floor((generalis.getObjective("exhaust").getScore(player) / generalis.getObjective("exhaust_lim").getScore(player)) * 100))
            let posture = (Math.floor((chekPst / 100) * 100))
            let ability = (Math.floor((playerStat.powerBar / 100) * 100))
            posture < 100 && posture >= 10 ? posture = '0' + posture : posture < 10 ? posture = '00' + posture : posture = posture
            stamina < 100 && stamina >= 10 ? stamina = '0' + stamina : stamina < 10 ? stamina = '00' + stamina : stamina = stamina
            ability < 100 && ability >= 10 ? ability = '0' + ability : ability < 10 ? ability = '00' + ability : ability = ability

            let equipment = player.getComponent("minecraft:equippable");
            let mainhand
            let abilies
        
            let abilies0
            let abilies1
            let abilies2
            try {
                mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
                abilies = JSON.parse(mainhand?.getDynamicProperty("abilities"))
            
                let TimerMaps = JSON.parse(player.getDynamicProperty("entityStatus"))
                abilies0 = TimerMaps.abilityCd[abilies[0].Id] 
                abilies1 = TimerMaps.abilityCd[abilies[1].Id]
                abilies2 = TimerMaps.abilityCd[abilies[2].Id]
            } catch(err){
                abilies0 = undefined
                abilies1 = undefined
                abilies2 = undefined
            }

            let chk0
            let chk1 
            let chk2

            abilies0 != undefined ? chk0 = '100' : chk0 = '000'
            abilies1 != undefined ? chk1 = '100' : chk1 = '000'
            abilies2 != undefined ? chk2 = '100' : chk2 = '000'

            abilies0 != undefined ? abilies0 = (Math.floor(((((abilies0/abilities[abilies[0].Id].cooldown) * 100)) - 100) * -1)) : abilies0 = "000"
            abilies1 != undefined ? abilies1 = (Math.floor(((((abilies1/abilities[abilies[1].Id].cooldown) * 100)) - 100) * -1)) : abilies1 = "000"
            abilies2 != undefined ? abilies2 = (Math.floor(((((abilies2/abilities[abilies[2].Id].cooldown) * 100)) - 100) * -1)) : abilies2 = "000"

            abilies0 < 10 && abilies0 != "000" ? abilies0 = "00" + abilies0 : abilies0 > 9 && abilies0 < 100 && abilies0 != "000" ? abilies0 = "0" + abilies0 : abilies0 = abilies0
            abilies1 < 10 && abilies1 != "000" ? abilies1 = "00" + abilies1 : abilies1 > 9 && abilies1 < 100 && abilies1 != "000" ? abilies1 = "0" + abilies1 : abilies1 = abilies1
            abilies2 < 10 && abilies2 != "000" ? abilies2 = "00" + abilies2 : abilies2 > 9 && abilies2 < 100 && abilies2 != "000" ? abilies2 = "0" + abilies2 : abilies2 = abilies2


            player.onScreenDisplay.setTitle(`minced:stm:${stamina}:pst:${posture}:abl:${ability}:ch0:${chk0}:cd0:${(abilies0)}:ch1:${chk1}:cd1:${(abilies1)}:ch2:${chk2}:cd2:${(abilies2)}:`)
            playerStat["oldposture"] = chekPst
            playerStat["oldstamina"] = chekStm
            playerStat["oldpowerbar"] = playerStat.powerBar
            player.setDynamicProperty("oldposture", chekPst)
            player.setDynamicProperty("oldstamina", chekStm)
        }

        
        for(let entity of player.dimension.getEntities()) {
            let eStat
            let lengter
            try {
                eStat = JSON.parse(entity.getDynamicProperty("resetingStatus"))
                lengter = Object.keys(eStat.effects).length != 0
            } catch (error) {
                eStat = {
                    effects: {}
                }
                lengter = 0
            }
            if(lengter > 0) {
                for (var prop in eStat.effects) {
                    eStat.effects[prop]["dur"] = eStat.effects[prop].dur - 1
                    if(eStat.effects[prop].dur == 0) {
                        delete eStat.effects[prop]
                    }
                    entity.setDynamicProperty("resetingStatus", JSON.stringify(eStat))
                }
            }
        }
        
        let block = player.hasTag("blocking")
        let statusses = JSON.parse(player.getDynamicProperty("resetingStatus"))
        let bloch = statusses.blockRecovery
        let nonsta = JSON.parse(player.getDynamicProperty("entityStatus"))
        let aTimes = nonsta.abilityTimes
        let aChecks = nonsta.abilityChecks
        let Abilities = nonsta.abilityCd
        for (var prop in aChecks) {
            aTimes[prop] = aTimes[prop] - 1
            if(aTimes[prop] == 0) {
                delete aTimes[prop]
                aChecks[prop] = 0
                delete aChecks[prop]
                abilities[prop]?.resetStats(player)
            }
            player.setDynamicProperty("entityStatus", JSON.stringify(nonsta))
        }
        for (var props in Abilities) {
            Abilities[props] = Abilities[props] - 1
            if(Abilities[props] == 0) {
                delete Abilities[props]
            }
            player.setDynamicProperty("entityStatus", JSON.stringify(nonsta))
        }

        if(bloch > 0 && !block) {
            statusses["blockRecovery"] = statusses.blockRecovery - 1
        }
        if(!block && bloch == 0) {
            player.runCommand("scoreboard players add @s[scores={posture=!100..110}] posture 5")
            player.runCommand("scoreboard players set @s[scores={posture=101..1100}] posture 100")
        } 
        player.setDynamicProperty("resetingStatus", JSON.stringify(statusses))
    }
},20)

system.runInterval(()=>{
    for(const player of world.getPlayers()) {
        let playerControls = player.inputInfo.getMovementVector()
        if(playerControls.x == 0 && playerControls.y == 0) return;
        let directioneer
        playerControls.x > 0 ? directioneer = "right" : playerControls.x < 0 ? directioneer = "left" : playerControls.y > 0 ? directioneer = "forward" : playerControls.y < 0 ? directioneer = "backward" : directioneer = ""
        if(playerControls.x != 0||playerControls.y != 0) {
            player.setProperty("movement:direction", directioneer)
        }
    }
},5)

function storeItemstoItem(player, entity, item) {
    let container = entity.getComponent('inventory').container
    let ItemsToStore = []
    if (container.emptySlotsCount !== container.size){
        for (let i = 0; i < container.size; i++){
            const item = container.getItem(i);               
            if (item !== undefined) {
                ItemsToStore.push(item)
            }
        }
    }
    entity.triggerEvent("despawn")
    system.runTimeout(()=>{
        let Iteman = new ItemStack(item, 1)
        Iteman.setDynamicProperty("storedItems", JSON.stringify(ItemsToStore))
        player.getComponent("minecraft:equippable").setEquipment('Mainhand', Iteman)
    },3)
    
}

system.run(()=>{
    MakeStatboards()
    for(let reloader of world.getPlayers()) {
        reloader.setProperty("mode:combat", 0)
        reloader.runCommand("execute as @e run scriptevent cmbt:listener remove_attack")
        reloader.runCommandAsync("tag @s remove attack")
        reloader.runCommand("execute as @s run function cdmover");
        stunnedScores.setScore(reloader, 0)
        reloader.setDynamicProperty("attacking", 0)
        reloader.setDynamicProperty("combo", 1)
        comboCounter.set(reloader.id,1)
        let statusDefaults = {
            effects: {},
            Boost: 0,
            slashBoost: 0.0,
            bluntBoost: 0.0,
            pierceBoost: 0.0,
            blockRecovery: 0,
            targetNumMod: 0,
            selectedSlot: "",
            inputs: [],
            sneakTimer: 0,
            sneakCD: 0,
            powerBar: 0,
            powerBarTrigger: 0,
            oldposture: 0,
            oldstamina: 0,
            oldpowerbar: 0,
            magicBar: 0,
            AirTime: 0,
            slash: 0.0,
            blunt: 0.0,
            pierce: 0.0,
            Alldamage: 0.0,
            magicDamage: 0.0,
            bide: 0,
            counter: 0.0,
            aiming: false,
        }
        reloader.setDynamicProperty("resetingStatus", JSON.stringify(statusDefaults))
        DelayedSelector(reloader)
        /*for(const reloaders of reloader.dimension.getEntities()) {
            reloaders.runCommand("execute as @e run scriptevent cmbt:listener remove_attack")
            reloaders.runCommandAsync("tag @s remove attack")
            reloaders.setDynamicProperty("attacking", 0)
            reloaders.setDynamicProperty("combo", 1)
        }*/
    }
})

world.beforeEvents.worldInitialize.subscribe((data) => {
    data.blockComponentRegistry.registerCustomComponent("minced:ability_table", {
        onPlace(e){
            let entity = e.dimension.spawnEntity("minced:ability_table", Vector3.Add(e.block.location, { x: 0.5, y: 0.75, z: 0.5 }));
            entity.nameTag = "entity.minced:ability_table.name";
        },
        onPlayerDestroy(e){
            e.dimension.runCommand("kill @e[type=minced:ability_table,c=1]")
        }
    });
    data.blockComponentRegistry.registerCustomComponent("minced:ability_writing_table", {
        onPlace(e){
            let entity = e.dimension.spawnEntity("minced:ability_writing_table", Vector3.Add(e.block.location, { x: 0.5, y: 0.75, z: 0.5 }));
            entity.nameTag = "entity.minced:ability_table.name";
        },
        onPlayerDestroy(e){
            e.dimension.runCommand("kill @e[type=minced:ability_writing_table,c=1]")
        }
    });
})

world.afterEvents.worldInitialize.subscribe((data) => {
    MakeStatboards()
})


world.afterEvents.playerSpawn.subscribe((data) =>{
    let joiner = data.player
    MakeStatboards()
    if (data.initialSpawn && !joiner.hasTag("joyloy")) {
        if (worldStatus.get("worldData") == undefined) {
            worldStatus.set("worldData", {superJump: true, cameraShake: true, abilitySystem: true})
        }
        joiner.runCommand("execute as @s run function reitire");
        let newPlayer = {
            passives: [],
            attackMoves: [],
            raceType: "human",
            dualwieldCheck: "offhand",
            AirChargeLimit: 3,
            type:"humanoid",
            abilityTimes: {},
            abilityChecks: {},
            abilityCd: {}
        }
        joiner.setDynamicProperty("entityStatusDefault", JSON.stringify(newPlayer))
        joiner.setDynamicProperty("entityStatus", JSON.stringify(newPlayer))
        joiner.setDynamicProperty("entitySkills", JSON.stringify({skillList:{}}))
        AirCharges.set(joiner.id,1)
        setAmmounthand_blaster(joiner)
        joiner.runCommand("execute as @e run scriptevent cmbt:listener remove_attack")
        let playerStats = {
            AirChargeLimit: 3,
            Strength: 2.0,
            Agility: 5.0,
            Dexterity: 1.0,
            Intelligence: 5.0,
            Endurance: 5.0,
            PhysicalResistance: 5.0,
            MagicResistance: 5.0,
            Vitality: 0.0,
            Charisma: 0.0,
            waterResist: 0.0,
            waterLevel: 0.0,
            waterBoost: 0.0,
            fireResist: 0.0,
            fireLevel: 0.0,
            fireBoost: 0.0,
            earthResist: 0.0,
            earthLevel: 0.0,
            earthBoost: 0.0,
            windResist: 0.0,
            windLevel: 0.0,
            windBoost: 0.0,
            darkResist: 0.0,
            darkLevel: 0.0,
            darkBoost: 0.0,
            lightResist: 0.0,
            lightLevel: 0.0,
            lightBoost: 0.0,
            slashResist: 0.0,
            slashBoost: 0.0,
            bluntResist: 0.0,
            bluntBoost: 0.0,
            pierceResist: 0.0,
            pierceBoost: 0.0,
        }
        SetStatboards(joiner, playerStats)
        comboCounter.set(joiner.id,1)
    }
    system.runTimeout(()=>{
      joiner.runCommand(`execute as @s run scriptevent receive:Data ${joiner.getDynamicProperty("entityStatusDefault")}`)
    },5)
    let statusDefaults = {
        effects: {},
        Boost: 0,
        slashBoost: 0.0,
        bluntBoost: 0.0,
        pierceBoost: 0.0,
        blockRecovery: 0,
        targetNumMod: 0,
        selectedSlot: "",
        inputs: [],
        sneakTimer: 0,
        sneakCD: 0,
        powerBar: 0,
        powerBarTrigger: 0,
        oldposture: 0,
        oldstamina: 0,
        oldpowerbar: 0,
        magicBar: 0,
        AirTime: 0,
        slash: 0.0,
        blunt: 0.0,
        pierce: 0.0,
        Alldamage: 0.0,
        magicDamage: 0.0,
        bide: 0,
        counter: 0.0,
        aiming: false,
    }
    joiner.setDynamicProperty("resetingStatus", JSON.stringify(statusDefaults))
    joiner.setProperty("mode:combat", 0)
    stunnedScores.setScore(joiner, 0)
    //blockRecovery.set(joiner.id,0)
    joiner.runCommandAsync("tag @s remove attack")
    joiner.runCommand("execute as @s run function cdmover");
    joiner.setDynamicProperty("attacking", 0)
    joiner.setDynamicProperty("combo", 1)
    DelayedSelector(joiner)
    MakeStatboards()
    MakeScoreboards()
})

world.afterEvents.mainHandChangeEvent.subscribe((event) => {
    const { oldItemStackData, newItemStack, player } = event
    let equipment = player.getComponent("minecraft:equippable");
    let offhand = equipment?.getEquipmentSlot(EquipmentSlot.Offhand)?.getItem()
    let weaponType
    try{
        weaponType = weaponTypeSplicer(newItemStack)
    } catch(err) {
        weaponType = "unarmed"
    }
    weaponType == "skill_book"||weaponType == "ability_scroll"||weaponType == "learning_book" ? weaponType = "unarmed" : weaponType
    if(weaponType != "unarmed" && newItemStack?.getDynamicProperty("fightStyle") == undefined) { 
        loreTrigger(player, weaponType, newItemStack)
    }
    let red
    try {
        red = weaponTypeSplicer(offhand)
    } 
    catch(err) {
        red = "unarmed"
    }
    
    if(weaponType == "unarmed") return
    let usedDevice = player.clientSystemInfo.platformType
    let TextChecker = "pc" 
    switch(usedDevice) {
        case "Desktop": {
            TextChecker = "pc" 
        } break;
        case "Console": {
            TextChecker = "xb" 
        } break;
        case "Mobile": {
            TextChecker = "mb" 
        } break;
    }
    //TextChecker = "xb"
    let OffhandCheck = false
    if(newItemStack.getComponent("minecraft:enchantable")?.hasEnchantment("fire_aspect")) {
        player.setProperty("trail:sword", 1)
    } else {
        player.setProperty("trail:sword", 0)
    }
    red != "unarmed" && weapons[red]?.dual_wield.includes(weaponType) ? OffhandCheck = true : OffhandCheck = false
    OffhandCheck == true ? TextChecker = TextChecker + "_dual_wield" : TextChecker = TextChecker
    if(selectedSlot.get(player.id) == "return") {
        player.selectedSlotIndex = oldItemStackData.SlotIndex
        selectedSlot.set(player.id, "")
    } else if (weaponType != "unarmed" && newItemStack?.getDynamicProperty("abilities") == undefined) {
        loreTrigger(player, weaponType, newItemStack)
    } else if (weaponType != "unarmed" && selectedSlot.get(player.id) != "return" && (red == "unarmed"||OffhandCheck == false)) {
        player?.setProperty("fighting:style", newItemStack?.getDynamicProperty("fightStyle"))
        if(weaponType == "puppet") {
            player.runCommand("execute as @s run scriptevent doll:listener get_doll")
        }
        system.runTimeout(()=>{
            player.runCommand(`event entity @e[tag=${player.name},c=1] despawn`)
        },1) 
        system.runTimeout(()=>{
            let Itemer = player.dimension.spawnEntity("minced:middle_entity", player.location)
            Itemer.addTag(player.name)
            player.getComponent("rideable").addRider(Itemer)
        },3) 
        system.runTimeout(()=>{
            player.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
        },5) 
        if(red != "unarmed") {
          player.runCommand("say offhand unavailable")
        }
        let nonsta = JSON.parse(player.getDynamicProperty("entityStatus"))
        let aTimes = nonsta.abilityTimes
        let aChecks = nonsta.abilityChecks
        for (var prop in aChecks) {
            aTimes[prop] = aTimes[prop] - 1
            if(abilities[prop].canSwitch == false) {
                delete aTimes[prop]
                delete aChecks[prop]
                abilities[prop]?.resetStats(player)
            }
            player.setDynamicProperty("entityStatus", JSON.stringify(nonsta))
        }
    } else if (weaponType != "unarmed" && selectedSlot.get(player.id) != "return" && red != "unarmed" && OffhandCheck == true) {
        player?.setProperty("fighting:style", newItemStack?.getDynamicProperty("fightStyle"))
        system.runTimeout(()=>{
            player.runCommand(`event entity @e[tag=${player.name},c=1] despawn`)
        },1) 
        system.runTimeout(()=>{
            let Itemer = player.dimension.spawnEntity("minced:middle_entity", player.location)
            Itemer.addTag(player.name)
            player.getComponent("rideable").addRider(Itemer)
        },3) 
        system.runTimeout(()=>{
            player.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
        },5)
        let nonsta = JSON.parse(player.getDynamicProperty("entityStatus"))
        let aTimes = nonsta.abilityTimes
        let aChecks = nonsta.abilityChecks
        for (var prop in aChecks) {
            aTimes[prop] = aTimes[prop] - 1
            if(abilities[prop].canSwitch == false) {
                delete aTimes[prop]
                delete aChecks[prop]
                abilities[prop]?.resetStats(player)
            }
            player.setDynamicProperty("entityStatus", JSON.stringify(nonsta))
        }
    } else {
        system.runTimeout(()=>{
            player.runCommand(`event entity @e[tag=${player.name},c=1] despawn`)
        },1)
    }
})

system.afterEvents.scriptEventReceive.subscribe((event) => {
    let id = event.id
    let message = event.message
    let cali = event.sourceEntity
    
    switch(id) {
        case "cmbt:listener": {
            switch(message) {
                case "attack": {
                    if(cali.typeId == "minecraft:player"||cali.typeId == "darkdepths:humanoid") {
                        let inv
                        let offhand
                        switch(cali.typeId) {
                            case "darkdepths:humanoid": {
                                let entityInventory = cali.getComponent("minecraft:inventory").container
                                let mainhand = entityInventory.getItem(0)
                                offhand = entityInventory.getItem(1)
                                inv = mainhand
                            } break;
                            case "minecraft:player": {
                                cali.runCommandAsync("scoreboard players set @s combatTimer 60") 
                                let equipment = cali.getComponent("minecraft:equippable");
                                let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
                                offhand = equipment?.getEquipmentSlot(EquipmentSlot.Offhand)?.getItem()
                                inv = mainhand
                            } break;
                        }
                        if (inv == undefined) return;
                        let blue = weaponTypeSplicer(inv)
                        if(blue == "skill_book" || blue == "ability_scroll" || blue == "learning_book") blue = "unarmed";
                        if (blue == "unarmed") return;
                        let red
                        try {
                            red = weaponTypeSplicer(offhand)
                        } catch (error) {
                            red = "unarmed"
                        }
                        let attck = cali.getDynamicProperty("attacking")
                        if(attck == 1) {
                            return;
                        }
                        let attackType = AttackChecker(cali,"")
                        if(attackType == "offhand") {
                            weaponsTrigger(cali, red, offhand, attackType, "")
                        } else {
                            weaponsTrigger(cali, blue, inv, attackType, "")
                        }
                        
                    } else if(cali.typeId != "minecraft:player") {
                        /*let equipment = cali.getComponent("minecraft:equippable");
                        let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
                        let offhand = equipment?.getEquipmentSlot(EquipmentSlot.Offhand)?.getItem()
                
                        const inv = mainhand
                        let attck = attacking.get(cali.id)
                        if (inv == undefined) return;
                        if(!inv.hasComponent("durability")) {return}
                        let imv = inv.getComponent("durability").damage + 1
                        if (attck == 1) {
                            return;
                        }
                        let sneak = cali.isSneaking
                        let jump = cali.isJumping
                        let onGround = cali.isOnGround
                        let blue = weaponTypeSplicer(inv?.getTags())
                        let red
                        let dualOff
                        let AirTimeSkill = AirTime.get(cali.id) 
                        let velocity = cali.getVelocity();
                        let rotation = cali.getRotation();
                        let rot_old = Math.floor((Math.atan2(velocity.z, velocity.x) * 180 / Math.PI - 90));
                        rot_old < -180 ? rot_old = rot_old + 360 : rot_old
                        let dirCheck = Math.abs(rot_old - Math.floor(rotation.y))
                        dirCheck = Math.min(dirCheck, (360 - dirCheck))
                        try {
                            red = weaponTypeSplicer(offhand.getTags())
                            dualOff = weapons[red]?.dual_wield
                        } 
                        catch(err) {
                            red = "unarmed"
                            dualOff = "unarmed"
                        }*/
                        let TypeZ = cali.getProperty("mob:type")
                        mobsTrigger(cali, TypeZ, "normal")
                    }
                }
                break;
                case "attack_sprint": {
                    if(cali.typeId != "minecraft:player") {
                        if((cali.getDynamicProperty("attacking") != 1||cali.getDynamicProperty("attacking") == undefined) && (cali.typeId == "minecraft:zombie"||cali.typeId == "minecraft:husk")) {
                            mobsTrigger(cali, "zombie", "sprint")
                        } else if(cali.typeId == "minecraft:ravager") {
                            cali.setDynamicProperty("attacking",0)
                            cali.setDynamicProperty("combo",1)
                            cali.removeTag("attack")
                            stunBreakScores.setScore(cali,0)
                            stunnedScores.setScore(cali, 0)
                            generalis.getObjective("clash").setScore(cali, 0)
                            generalis.getObjective("combatCooldown").setScore(cali, 0)
                            cali.triggerEvent("combat:remove_attack")
                            cali.playAnimation(`animation.minced.ravager.stunned`)
                            system.runTimeout(()=>{ mobsTrigger(cali, "ravager", "stunned")},10)
                        }
                    }
                }
                break;
                case "attack_charge": {
                    if(cali.typeId != "minecraft:player") {
                        if((cali.getDynamicProperty("attacking") != 1||cali.getDynamicProperty("attacking") == undefined) && (cali.typeId == "minecraft:zombie"||cali.typeId == "minecraft:husk")) {
                            mobsTrigger(cali, "zombie", "sprint")
                        } else if(cali.typeId == "minecraft:ravager") {
                            cali.setDynamicProperty("attacking",0)
                            cali.setDynamicProperty("combo",1)
                            cali.removeTag("attack")
                            stunBreakScores.setScore(cali,0)
                            stunnedScores.setScore(cali, 0)
                            generalis.getObjective("clash").setScore(cali, 0)
                            generalis.getObjective("combatCooldown").setScore(cali, 0)
                            cali.triggerEvent("combat:remove_attack")
                            cali.playAnimation(`animation.minced.ravager.stunned`)
                            system.runTimeout(()=>{ mobsTrigger(cali, "ravager", "charge")},10)
                        }
                    }
                }
                break;
                case "remove_air": {
                    let AirCheck = JSON.parse(cali.getDynamicProperty("resetingStatus"))
                    AirCheck["AirTime"] = 0
                    cali.setDynamicProperty("resetingStatus", JSON.stringify(AirCheck))
                }
                break;
                case "remove_attack": {
                    stunBreakScores.addScore(cali, 0)
                    try {
                        cali?.triggerEvent(`stun:remove`)
                    } catch (error) {
                        
                    }
                    
                    if(cali.getDynamicProperty("attacking") != 1) {
                        cali.setDynamicProperty("attacking",0)
                        cali.setDynamicProperty("combo",1)
                        let che4ck = stunBreakScores.getScore(cali)
                        if(che4ck != 1) {
                            cali.runCommand("inputpermission set @s movement enabled")
                        }
                        cali.runCommand("inputpermission set @s movement enabled")
                        stunnedScores.setScore(cali, 0)
                        stunBreakScores.setScore(cali, 0)
                    } 
                }
                break;
                case "add_air_charge": {
                    let newValue = AirCharges.get(cali.id) + 1
                    let airLimit = JSON.parse(cali.getDynamicProperty("entityStatus"))
                    if(newValue < airLimit["AirChargeLimit"]) {
                        AirCharges.set(cali.id,newValue)
                    }
                }
                break;
                case "restore_stun_meter": {
                    cali.triggerEvent(`stun:remove`)
                    cali.setDynamicProperty("attacking",0)
                    stunnedScores.setScore(cali, 0)
                    stunBreakScores.setScore(cali, 0)
                }
                break;
                case "restore_stance": {
                    stunnedScores.setScore(cali, 0)
                    stunBreakScores.setScore(cali, 0)
                    cali.triggerEvent(`stun:remove`)
                    cali.setDynamicProperty("attacking",0)
                    if(cali.typeId != "minecraft:player") {
                        cali.playAnimation(`animation.zombie_paced.idle_no_weapon`)
                        cali.triggerEvent(`attack_again`)
                        cali.setDynamicProperty("attacking",0)
                    }
                }
                break;
                default: 
                break;
            }
        }
        break;
        case "update:Data":{
          cali.setDynamicProperty("entityStatusDefault", message)
          cali.runCommand(`execute as @s run scriptevent receive:Data ${message}`)
        } break;
        case "cmbt:doll_send":{
            let equipment = cali.getComponent("minecraft:equippable");
            let ItemtoID = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
            ItemtoID?.setDynamicProperty("doll", message)
            equipment.setEquipment(EquipmentSlot.Mainhand, ItemtoID)
          } break;
        case "status:raceData":{
          let RaceData = JSON.parse(message)
          cali.runCommand(`execute as @s run scriptevent receive:Data ${JSON.stringify(RaceData)}`)
        }
        break;
        case "status:Resistances":{
          let RaceData = JSON.parse(message)
          cali.setDynamicProperty("entityStatusDefault", message)
        }
        break;
        case "status:levelUpdate":{
            cali.setDynamicProperty("entityStatusDefault", message)
        }
        break;
        case "status:MagicUpdate":{
            cali.setDynamicProperty("entityStatusDefault", message)
        }
        break;
        case "status:AccessoryUpdate":{
            cali.setDynamicProperty("entityStatus", message)
        }
        break;
        case "status:lmao":{
            //styleChooser(cali)
        }
        break;
        case "ability:use": {
            let equipment = cali.getComponent("minecraft:equippable");
            let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
            let weaponclass = weaponTypeSplicer(mainhand)
            if(weaponclass == "magazine"||weaponclass == "unarmed"||weaponclass == "skill_book"||weaponclass == "ability_scroll"||weaponclass == "learning_book") return;
            let ability = JSON.parse(mainhand?.getDynamicProperty("abilities"))
            let JumpyJitters =  generalis.getObjective("controls").getScore(cali)
            let offhand = equipment?.getEquipmentSlot(EquipmentSlot.Offhand)?.getItem()
            let red
            try {
                red = weaponTypeSplicer(offhand)
            } 
            catch(err) {
                red = "unarmed"
            }
            let OffhandCheck
            red != "unarmed" && weapons[red]?.dual_wield.includes(weaponclass) ? OffhandCheck = true : OffhandCheck = false
            let storeStatus = JSON.parse(cali.getDynamicProperty("resetingStatus"))
            let TextChecker = "pc"
            OffhandCheck == true && JumpyJitters == 2 ? TextChecker = "pc_dual_wield" : OffhandCheck == true && JumpyJitters == 1 ? TextChecker = "mb_dual_wield" : OffhandCheck != true && JumpyJitters == 1 ? TextChecker = "mb" : TextChecker = "pc"
            let CdMaps = JSON.parse(cali.getDynamicProperty("entityStatus"))
            switch(message) {
                case "one": {
                    if(CdMaps.abilityCd[ability[0].Id] != "O0") {
                        abilityTrigger(cali, ability[0].Id, mainhand, "normal")
                        selectedSlot.set(cali.id,"return")
                    }
                    system.runTimeout(()=>{
                        cali.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
                    },2)
                    
                } break;
                case "two": {
                    if(CdMaps.abilityCd[ability[1].Id] != "O0") {
                        abilityTrigger(cali, ability[1].Id, mainhand, "normal")
                        selectedSlot.set(cali.id,"return")
                    }
                    system.runTimeout(()=>{
                        cali.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
                    },2)
                   
                } break;
                case "three": {
                    if(CdMaps.abilityCd[ability[2].Id] != "O0") {
                        abilityTrigger(cali, ability[2].Id, mainhand, "normal")
                        selectedSlot.set(cali.id,"return")
                    }
                    system.runTimeout(()=>{
                        cali.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
                    },2)
                } break;
                case "switch_right": {
                    abilityForm(cali, mainhand)
                } break;
                case "aim": {
                    if(storeStatus.aiming == false) {
                        storeStatus["aiming"] = true
                        cali.setDynamicProperty("resetingStatus", JSON.stringify(storeStatus))
                        let aimer = system.runInterval(()=>{
                            source.addEffect("slowness", 20, { amplifier: 5, showParticles: false })
                            if (storeStatus.aiming == false){
                                system.clearRun(aimer) 
                            }
                        },5)
                    }
                    if(storeStatus.aiming == true) {
                        storeStatus["aiming"] = false
                        cali.setDynamicProperty("resetingStatus", JSON.stringify(storeStatus))
                    }
                    system.runTimeout(()=>{
                        cali.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
                    },2)
                } break;
                case "dual_wield": {
                    let dualwield = JSON.parse(cali.getDynamicProperty("entityStatus"))
                    if(dualwield["dualwieldCheck"] == "offhand") {
                        dualwield["dualwieldCheck"] = "dual_wield"
                    } else if(dualwield["dualwieldCheck"] == "dual_wield") {
                        dualwield["dualwieldCheck"] = "offhand"
                    }
                    cali.setDynamicProperty("entityStatus",JSON.stringify(dualwield))
                    system.runTimeout(()=>{
                        cali.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
                    },2)
                } break;
                case "attack": {
                    system.runTimeout(()=>{
                        cali.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:${TextChecker}`)
                    },2)
                } break;
            }           
        } break;
        case "ability:Slash": {
            skillLearner(cali, "super_jump")
            //let lmao = JSON.parse(cali.getDynamicProperty("resetingStatus"))
            //lmao["powerBar"] = 100
            //cali.setDynamicProperty("resetingStatus", JSON.stringify(lmao))
        } break;
        case "ability:Slasher": {
            //let lmao = JSON.parse(cali.getDynamicProperty("resetingStatus"))
            //lmao["powerBar"] = 100
            //cali.setDynamicProperty("resetingStatus", JSON.stringify(lmao))
        } break;
        case "ability:hahahahah": {
            let equipment = cali.getComponent("minecraft:equippable");
            let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
            console.warn(JSON.stringify(武器['claws']))
            function getObjectFunctions(obj) {
                return Object.keys(obj).filter(key => typeof obj[key] === "function");
            }
            console.warn(JSON.stringify(getObjectFunctions(武器['claws'])))
            function parseStringifiedFunction(str) {
                const obj = JSON.parse(str); // Parse the JSON string
                if (obj.fu) {
                  // Use `eval` to recreate the function
                  return eval(`(${obj.fu})`);
                }
                throw new Error("No function found in the JSON");
            };
            let attackFuncky = parseStringifiedFunction(武器['claws'].execute);
            attackFuncky(cali, mainhand, 'laceration', 'normal', '')
        } break;
        case "weapon:storeWeapon": {
            const 専ブラ = JSON.parse(message, (key, value) => {
                if (typeof value === "string" && value.startsWith("function")) {
                  return eval(`(${value})`); // Convert the string back into a function
                }
                return value;
            });
            for(let 人生 in 専ブラ) {
                武器[人生] = 専ブラ[人生]
            }
        } break;
        default: {
            if(id.split(":")[1] == 'storeWeapon') {
                let 専ブラ = JSON.parse(message)
                for(let 人生 in 専ブラ) {
                    武器[人生] = 専ブラ[人生]
                }
            } else if(id.split(":")[1] == 'storeAbilities') {
                武器.set(id.split(":")[0], message)
            } else if(id.split(":")[1] == 'storeEffects') {
                武器.set(id.split(":")[0], message)
            } else if(id.split(":")[1] == 'storeEntityTypes') {
                武器.set(id.split(":")[0], message)
            }
        }
    }
});

world.afterEvents.playerInteractWithEntity.subscribe((munēca)=>{
  const {player, target, itemStack} = munēca
  switch(target.typeId) {
    case "minced:ability_table": {
        if(tablesInUse.has(target.id)) return;
        tablesInUse.add(target.id)
        AfterWaitInventory(target)
    } break;
    case "minced:ability_writing_table": {
        ability_writing(player, itemStack)
    } break;
    case "minced:iron_grand_cross_entity": {
        if(player.isSneaking) {
            storeItemstoItem(player, target, "pixel:iron_grand_cross")
            
        }
    } break;
  }
})

world.afterEvents.entityHitBlock.subscribe((data) => {
    let block = data.hitBlock
    let player = data.damagingEntity
    let equipment = player.getComponent("minecraft:equippable");
    let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
    let weaponType
    try {
        weaponType = weaponTypeSplicer(mainhand)
        if (weaponType == "unarmed") {
            if(inv.getTags().includes("minecraft:is_sword")) {
                weaponType = "sword"
            } else {
                return;
            } 
        }
    } 
    catch(err) {
        weaponType = "unarmed"
    }
                           
    
    if(weaponType == "unarmed") return;
    switch(block.typeId) {
        case "minecraft:cobblestone": {
            if((block.typeId == "minecraft:cobblestone" ||block.typeId == "minecraft:stone" ) && weaponType == "war_hammer") {
                let direction = player.getViewDirection()
                let bL = block.location
                player.runCommand(`setblock ${bL.x} ${bL.y} ${bL.z} air destroy`)
                spawnProjectile(player, `3dcombat:block_projectile<${block.typeId}>`, 1, 1, 10, "block", bL)
            }
        } break;
        case "minced:ability_changing_table": {
            if(weaponType == "greatsword") {  
                styleChooser(player)
            }
        } break;
    }
})

world.afterEvents.entityHitEntity.subscribe((entityData) => {
    let cali = entityData.damagingEntity
    let burn = entityData.hitEntity
    if (cali.typeId === "minecraft:player" && cali.getDynamicProperty("attacking") != 1) {
        cali.runCommandAsync("scoreboard players set @s combatTimer 60")
        let equipment = cali.getComponent("minecraft:equippable");
        let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
        let offhand = equipment?.getEquipmentSlot(EquipmentSlot.Offhand)?.getItem()
        const inv = mainhand
        let blue
        try {
            blue = weaponTypeSplicer(inv)
        } catch (error) {
            blue = "unarmed"
        }
        let red
        try {
            red = weaponTypeSplicer(offhand)
        } catch (error) {
            red = "unarmed"
        }
        let AttackType = AttackChecker(cali, burn)
        if(AttackType == "offhand") {
            weaponsTrigger(cali, red, offhand, AttackType, burn)
        } else {
            weaponsTrigger(cali, blue, inv, AttackType, burn)
        }
        let mover = JSON.parse(cali.getDynamicProperty("resetingStatus"))
        mover["inputs"] = []
        cali.setDynamicProperty("resetingStatus",JSON.stringify(mover))
    } else if (cali.typeId != "minecraft:player" && cali.getProperty("mob:type") == undefined) {
        let mobster = "unidentified"
        try {
            mobster = ModifiedEntities.get(cali.typeId).type ?? "unidentified"
        } catch (error) {
            mobster = "unidentified"
        }
        mobsTrigger(cali, mobster, "normal")
    }
});

world.afterEvents.itemStartUse.subscribe((data) => {
    let source = data.source
    let weaponType = weaponTypeSplicer(data.itemStack)
    const cont = source.getComponent("minecraft:inventory").container
    let equipment = source.getComponent("minecraft:equippable");
    if(data.itemStack?.typeId == "minced:combat_config"){ 
        adminOptions(source)
        return;
    } else if(data.itemStack?.typeId == "pixel:pellet_container"){
        pellet_container(source, data.itemStack)
        return;
    } 
    if(weaponType == "unarmed") {return}
    if(weaponType == "skill_book"||weaponType == "ability_scroll"||weaponType == "learning_book") {
        let ItemLore
        try {
            ItemLore = data.itemStack.getLore()[0]
        } catch (error) {
            ItemLore = "unspecified"
        }
        execute_book(source, weaponType, ItemLore, data.itemStack, 1)
        return;
    }
    let offhand
    let typinOff = equipment?.getEquipmentSlot(`Offhand`)?.getItem()
    let animpref
    let weaponTyper = weapons[weaponType]
    try {
        animpref = weaponTyper?.stylePrefixes[source.getProperty("fighting:style")]
        animpref == undefined || animpref == "" ? animpref = weaponTyper?.stylePrefixes[0] : animpref = animpref
    } catch(err) {
        animpref = "minced.halberd"
    }
    try{
        offhand = weaponTypeSplicer(typinOff)
    } catch(err){
        offhand = "unarmed"  
    }
    let stunCheck = stunBreakScores.getScore(source)
    let PowerBar = JSON.parse(source.getDynamicProperty("resetingStatus"))
    let PowerBarCheck = (PowerBar.powerBar >= 100 && PowerBar.powerBarTrigger == 1)
    if(stunCheck != 1 && PowerBarCheck == false) {
        let charged = JSON.parse(data.itemStack.getDynamicProperty("abilities"))[3].Id
        source.runCommandAsync("scoreboard players set @s charger 0")
        let timer = 0
        let charger = system.runInterval(()=>{
                let gauss = JSON.parse(source.getDynamicProperty("resetingStatus"))
                let playerScore = generalis.getObjective("exhaust").getScore(source)
                let lamano = abilities[charged]
                let Cd = JSON.parse(source.getDynamicProperty("entityStatus")).abilityCd[lamano.coodname]
                if (Cd > 1) {
                    system.clearRun(charger)
                    source.runCommand(`title @s actionbar cooldown`)
                }
                if(lamano.charge_type == "continuous") {
                    abilityTrigger(source, charged, data.itemStack, "charge")
                    generalis.getObjective("combatTimer").setScore(source, 60)
                }
                if(lamano.charge_type == "continuous_with_delay") {
                    timer = timer + 1
                    if(timer % abilities[charged].delay == 0) {
                        abilityTrigger(source, charged, data.itemStack, "charge")
                        generalis.getObjective("combatTimer").setScore(source, 60)
                    }
                }
                if(lamano.charge_type == "block") {
                    let blockChecker
                    offhand != "unarmed" && weaponTyper.dual_wield.includes(offhand) ? blockChecker = `${offhand}_block` : blockChecker = "block"
                    try{
                        source.playAnimation(`animation.${animpref}.${blockChecker}`, 
                        {
                            blendOutTime: 0.1,
                            stopExpression: "!query.is_using_item",
                            nextState: `animation.${animpref}.combat_stance`
                        })
                    } catch(err){
                        source.playAnimation(`animation.${animpref}.block`, 
                        {
                            blendOutTime: 0.1,
                            stopExpression: "!query.is_using_item",
                            nextState: `animation.${animpref}.combat_stance`
                        })
                    }
                    
                    abilityTrigger(source, charged, data.itemStack, "charge")
                }
                let chargerTrigger = generalis.getObjective("charger").getScore(source)
                let charge = chargeCountScore.getScore(source)
                if(lamano.charge_type != "block" && lamano.charge_type != "continuous" && lamano.charge_type != "continuous_with_delay") {
                    let yuusha
                    let crumble25 = Math.floor((lamano.charge_interval * lamano.charge_count)* 0.25)
                    let crumble50 = Math.floor((lamano.charge_interval * lamano.charge_count) * 0.5)
                    let crumble75 = Math.floor((lamano.charge_interval * lamano.charge_count) * 0.75)
                    charge >= crumble25 && charge < crumble50 ? yuusha = "▉" : charge >= crumble50 && charge < crumble75 ? yuusha = "▉▉" : charge >= crumble75 && charge < (lamano.charge_interval * lamano.charge_count) ? yuusha = "▉▉▉" :charge >= (lamano.charge_interval * lamano.charge_count) ? yuusha = "▉▉▉▉": yuusha=""
                    source.runCommand(`title @s actionbar Charge:§r${yuusha}`)
                }
                if(charge == 1) {
                    source.playAnimation(`animation.minced.${weaponType}.charge_${lamano.anim_prefix}`, 
                    {
                        stopExpression: "!query.is_using_item",
                    })
                }
                if (chargerTrigger == 1||playerScore < 7||lamano.charge_type != "block" && source.getDynamicProperty("attacking") == 1||lamano.charge_type == "block"||(lamano.charge_interval * lamano.charge_count) == charge && lamano.charge_type != "continuous" && lamano.charge_type != "continuous_with_delay" && lamano.charge_type != "block"){
                    system.clearRun(charger) 
                } else if (JSON.parse(source.getDynamicProperty("entityStatus")).abilityCd[charged] != undefined){
                    system.clearRun(charger)
                    source.onScreenDisplay.setActionBar(`Charge Skill Cooldown: ${JSON.parse(source.getDynamicProperty("entityStatus")).abilityCd[charged]}`)
                } else {
                    chargeCountScore.addScore(source, 1)
                }
                
        },2)
    } else if(stunCheck != 1 && source.getDynamicProperty("attacking") != 1 && PowerBarCheck == true) {
            let ultimater = JSON.parse(data.itemStack.getDynamicProperty("abilities"))[4].Id
            source.runCommandAsync("scoreboard players set @s charger 0")
            chargeCountScore.setScore(source, 0)
            if(ultimater == "O0") {
                PowerBar["powerBarTrigger"] = 0
                source.setDynamicProperty("resetingStatus", JSON.stringify(PowerBar))
                source.removeTag("blocking")
                source.runCommand(`title @s actionbar Ultimate Not Set`)
                return;
            }
            let charger = system.runInterval(()=>{
                let lamano = abilities[ultimater]
                let chargerTrigger = generalis.getObjective("charger").getScore(source)
                let charge = chargeCountScore.getScore(source)
                let yuusha
                let crumble25 = Math.floor((lamano.charge_interval * lamano.charge_count)* 0.25)
                let crumble50 = Math.floor((lamano.charge_interval * lamano.charge_count) * 0.5)
                let crumble75 = Math.floor((lamano.charge_interval * lamano.charge_count) * 0.75)
                charge >= crumble25 && charge < crumble50 ? yuusha = "▉" : charge >= crumble50 && charge < crumble75 ? yuusha = "▉▉" : charge >= crumble75 && charge < (lamano.charge_interval * lamano.charge_count) ? yuusha = "▉▉▉" :charge >= (lamano.charge_interval * lamano.charge_count) ? yuusha = "▉▉▉▉": yuusha=""
                source.runCommand(`title @s actionbar Charge:§r${yuusha}`)
                if (chargerTrigger == 1){
                    system.clearRun(charger) 
                } else if ((lamano.charge_interval * lamano.charge_count) == charge){
                    system.clearRun(charger)
                    abilityTrigger(source, ultimater, data.itemStack, "ultimate")
                    PowerBar["powerBar"] = 0
                    source.setDynamicProperty("resetingStatus", JSON.stringify(PowerBar))
                    source.removeTag("blocking")
                } else {
                    chargeCountScore.addScore(source, 1)
                }
                source.removeTag("blocking")
            },2)
    }
});

world.afterEvents.itemStopUse.subscribe((data) => {
    let source = data.source
    let weaponType = weaponTypeSplicer(data.itemStack)
    if(weaponType == "magazine"||weaponType == "unarmed"||weaponType == "skill_book"||weaponType == "ability_scroll"||weaponType == "learning_book") {return}
    let charged = JSON.parse(data.itemStack?.getDynamicProperty("abilities"))[3]?.Id
    system.runTimeout(()=>{
        source.removeTag("blocking")
        source.removeTag("attack")
        source.runCommand(`reload`)
    },10)
    source.removeTag("blocking")
    let equipment = source.getComponent("minecraft:equippable");
    let offhand
    try{
        offhand = equipment?.getEquipmentSlot(`Offhand`)?.getItem()
    } catch(err){
        offhand = "unidenfitifed"
    }
    let charges = chargeCountScore.getScore(source)
    let PowerBar = JSON.parse(source.getDynamicProperty("resetingStatus"))
    let PowerBarCheck = (PowerBar.powerBar >= 100 && PowerBar.powerBarTrigger == 1)
    if (charged != "B3" && charges > 10 && PowerBarCheck == false) {
        abilityTrigger(source, charged, data.itemStack, "charge")
    } /*else if (charges > 30 && PowerBarCheck == false) {
        abilityTrigger(source, ultimate, weaponType, "ultimate")
    }*/
    system.runTimeout(()=>{
        chargeCountScore.setScore(source, 0)
      },3)
    source.runCommandAsync("scoreboard players set @s charger 1")
});

world.afterEvents.entityHurt.subscribe((entityData) => {
    let damage = entityData.damage
    let cali = entityData.damageSource.damagingEntity
    let burn = entityData.hurtEntity
    if (cali?.typeId == "minecraft:player") {
         let gm = getGamemode(cali);
         let equipment = cali.getComponent("minecraft:equippable");
         let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
         const inv = mainhand
         if (gm != "creative") {
            try {
                var NewItem = inv
                NewItem.getComponent("durability").damage = inv.getComponent("durability").damage + 1;
                NewItem.getComponent("durability").damage <= 0 ? cali.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, undefined) : cali.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, NewItem)
            } catch (error) {
                console.log("no durability")
            }
            
        }
   } else return;
});

world.afterEvents.entityHealthChanged.subscribe((d) =>{
    const { entity, newValue } = d
    let healther
    
    try{
        healther = JSON.parse(entity.getDynamicProperty("resetingStatus")).effects.HR.redux
    } catch(err) {
        healther = 0
    }
    let maxhealth = entity.getComponent("minecraft:health").defaultValue
    if(newValue > (maxhealth - healther)) {
        entity.getComponent("health").setCurrentValue(maxhealth - healther)
    }
})

world.afterEvents.entitySpawn.subscribe((e) => {
    const {entity, cause} = e
    let typeDefaults = new Map([
        ["minecraft:zombie",{
          type:"humanoid",
          Strength: 5,
          Agility: 7,
          Dexterity: 1.0,
          Intelligence: 3,
          Endurance: 10,
          PhysicalResistance: 7,
          MagicResistance: 3,
          Vitality: 0.0,
          Charisma: 0.0,
          StunMeter: 30,
          waterResist: 0.0,
          waterLevel: 0.0,
          waterBoost: 0.0,
          fireResist: 0.0,
          fireLevel: 0.0,
          fireBoost: 0.0,
          earthResist: 0.0,
          earthLevel: 0.0,
          earthBoost: 0.0,
          windResist: 0.0,
          windLevel: 0.0,
          windBoost: 0.0,
          darkResist: 0.0,
          darkLevel: 0.0,
          darkBoost: 0.0,
          lightResist: 0.0,
          lightLevel: 0.0,
          lightBoost: 0.0,
          slashResist: 0.0,
          slashBoost: 0.0,
          bluntResist: 0.0,
          bluntBoost: 0.0,
          pierceResist: 0.0,
          pierceBoost: 0.0,
        }],
        ["minecraft:vindicator",{
            type:"humanoid",
            Strength: 7,
            Agility: 3,
            Dexterity: 5,
            Intelligence: 10,
            Endurance: 15,
            PhysicalResistance: 10,
            MagicResistance: 10,
            Vitality: 0.0,
            Charisma: 0.0,
            StunMeter: 30,
            waterResist: 0.0,
            waterLevel: 0.0,
            waterBoost: 0.0,
            fireResist: 0.0,
            fireLevel: 0.0,
            fireBoost: 0.0,
            earthResist: 0.0,
            earthLevel: 0.0,
            earthBoost: 0.0,
            windResist: 0.0,
            windLevel: 0.0,
            windBoost: 0.0,
            darkResist: 0.0,
            darkLevel: 0.0,
            darkBoost: 0.0,
            lightResist: 0.0,
            lightLevel: 0.0,
            lightBoost: 0.0,
            slashResist: 0.0,
            slashBoost: 0.0,
            bluntResist: 30,
            bluntBoost: 0.0,
            pierceResist: 0.0,
            pierceBoost: 0.0,
          }],
        ["minecraft:husk",{
          type:"humanoid",
          Strength: 7,
          Agility: 3,
          Dexterity: 3,
          Intelligence: 5,
          Endurance: 12,
          PhysicalResistance: 10,
          MagicResistance:7,
          Vitality: 0.0,
          Charisma: 0.0,
          StunMeter: 50,
          waterResist: 0.0,
          waterLevel: 0.0,
          waterBoost: 0.0,
          fireResist: 0.7,
          fireLevel: 0.0,
          fireBoost: 0.0,
          earthResist: 0.0,
          earthLevel: 0.0,
          earthBoost: 0.25,
          windResist: 0.0,
          windLevel: 0.0,
          windBoost: 0.0,
          darkResist: 0.0,
          darkLevel: 0.0,
          darkBoost: 0.0,
          lightResist: 0.0,
          lightLevel: 0.0,
          lightBoost: 0.0,
          slashResist: 0.0,
          slashBoost: 0.0,
          bluntResist: 50,
          bluntBoost: 50,
          pierceResist: 0.0,
          pierceBoost: 0.0,
        }],
        ["minecraft:drowned",{
          type:"humanoid",
          Strength: 7,
          Agility: 3,
          Dexterity: 1.0,
          Intelligence: 5,
          Endurance: 3,
          PhysicalResistance: 0.0,
          MagicResistance: 15,
          Vitality: 0.0,
          Charisma: 0.0,
          StunMeter: 20,
          waterResist: 0.0,
          waterLevel: 5.0,
          waterBoost: 2.0,
          fireResist: 0.7,
          fireLevel: 0.0,
          fireBoost: 0.0,
          earthResist: 0.0,
          earthLevel: 0.0,
          earthBoost: 0.0,
          windResist: 0.0,
          windLevel: 0.0,
          windBoost: 0.0,
          darkResist: 0.0,
          darkLevel: 0.0,
          darkBoost: 0.0,
          lightResist: 0.0,
          lightLevel: 0.0,
          lightBoost: 0.0,
          slashResist: -0.25,
          slashBoost: 0.0,
          bluntResist: -0.25,
          bluntBoost: 0.0,
          pierceResist: -0.5,
          pierceBoost: 0.0,
        }],
        ["minecraft:iron_golem",{
            type:"golem",
            Strength:30,
            Agility: 2,
            Dexterity:5,
            Intelligence: 10,
            Endurance: 50,
            PhysicalResistance: 30,
            MagicResistance: 5,
            Vitality: 0.0,
            Charisma: 0.0,
            waterResist: 0.0,
            waterLevel: 0.0,
            waterBoost: 0.0,
            fireResist: -2.0,
            fireLevel: 0.0,
            fireBoost: 0.0,
            earthResist: 0.0,
            earthLevel: 0.0,
            earthBoost: 0.0,
            windResist: 0.0,
            windLevel: 0.0,
            windBoost: 0.0,
            darkResist: 0.0,
            darkLevel: 0.0,
            darkBoost: 0.0,
            lightResist: 0.0,
            lightLevel: 0.0,
            lightBoost: 0.0,
            slashResist: 90,
            slashBoost: 20,
            bluntResist: 50,
            bluntBoost: 30,
            pierceResist: 50,
            pierceBoost: 0.0,
          }],
        ["minecraft:ravager",{
          type:"quadruped",
          Strength: 35,
          Agility: 10,
          Dexterity: 10,
          Intelligence: 2,
          Endurance: 30,
          PhysicalResistance: 30,
          MagicResistance: 10,
          Vitality: 0.0,
          Charisma: 0.0,
          StunMeter: 100,
          waterResist: 0.0,
          waterLevel: 0.0,
          waterBoost: 0.0,
          fireResist: 0.0,
          fireLevel: 0.0,
          fireBoost: 0.0,
          earthResist: 0.0,
          earthLevel: 0.0,
          earthBoost: 0.0,
          windResist: 0.0,
          windLevel: 0.0,
          windBoost: 0.0,
          darkResist: 0.5,
          darkLevel: 10.0,
          darkBoost: 0.75,
          lightResist: -150,
          lightLevel: 0.0,
          lightBoost: 0.0,
          slashResist: 20,
          slashBoost: 20,
          bluntResist: 50,
          bluntBoost: 30,
          pierceResist: 70,
          pierceBoost: 0.0,
        }],
        ["darkDepths:human",{
          type:"humanoid_custom",
          Strength: 15,
          Agility: 10,
          Dexterity: 10,
          Intelligence: 10,
          Endurance: 10,
          PhysicalResistance: 10,
          MagicResistance: 10,
          Vitality: 10.0,
          Charisma: 10.0,
          StunMeter: 40,
          waterResist: 0.0,
          waterLevel: 0.0,
          waterBoost: 0.0,
          fireResist: 0.0,
          fireLevel: 0.0,
          fireBoost: 0.0,
          earthResist: 0.0,
          earthLevel: 0.0,
          earthBoost: 0.0,
          windResist: 0.0,
          windLevel: 0.0,
          windBoost: 0.0,
          darkResist: 0.0,
          darkLevel: 0.0,
          darkBoost: 0.0,
          lightResist: 0.0,
          lightLevel: 0.0,
          lightBoost: 0.0,
          slashResist: 0.0,
          slashBoost: 0.0,
          bluntResist: 0.0,
          bluntBoost: 0.0,
          pierceResist: 0.0,
          pierceBoost: 0.0,
        }],
        ["minecraft:npc",{
            type:"villager_custom",
            Strength: 2.0,
            Agility: 5.0,
            Dexterity: 1.0,
            Intelligence: 5.0,
            Endurance: 5.0,
            PhysicalResistance: 5.0,
            MagicResistance: 5.0,
            Vitality: 0.0,
            Charisma: 0.0,
            StunMeter: 30,
            waterResist: 0.0,
            waterLevel: 0.0,
            waterBoost: 0.0,
            fireResist: 0.0,
            fireLevel: 0.0,
            fireBoost: 0.0,
            earthResist: 0.0,
            earthLevel: 0.0,
            earthBoost: 0.0,
            windResist: 0.0,
            windLevel: 0.0,
            windBoost: 0.0,
            darkResist: 0.0,
            darkLevel: 0.0,
            darkBoost: 0.0,
            lightResist: 0.0,
            lightLevel: 0.0,
            lightBoost: 0.0,
            slashResist: 0.0,
            slashBoost: 0.0,
            bluntResist: 0.0,
            bluntBoost: 0.0,
            pierceResist: 0.0,
            pierceBoost: 0.0,
          }],
    ])
    
    let EntityChecks = entity?.typeId
    try {
        if(entity.typeId == "minced:middle_entity"||entity.typeId == "minecraft:xp_orb"||entity.typeId == "minecraft:item"||entity.typeId == "minced:ability_table"||entity.typeId == "pixel:hit_box"||entity.getComponent("minecraft:type_family").hasTypeFamily("inanimate")) return;
    } catch (error) {
        return;
    }
    let def = {
        effects: {},
        Boost: 0,
        slashBoost: 0.0,
        bluntBoost: 0.0,
        pierceBoost: 0.0,
        blockRecovery: 0,
        selectedSlot: "",
        inputs: [],
        sneakTimer: 0,
        sneakCD: 0,
        powerBar: 0,
        powerBarTrigger: 0,
        magicBar: 0,
        AirTime: 0,
        slash: 0.0,
        blunt: 0.0,
        pierce: 0.0,
        Alldamage: 0.0,
        magicDamage: 0.0,
        aiming: false,
        counter: 0.0,
    }

    let 月の光 = {
        type:"humanoid_custom",
        Strength: 10.0,
        Agility: 5.0,
        Dexterity: 5.0,
        Intelligence: 5.0,
        Endurance: 5.0,
        PhysicalResistance: 5.0,
        MagicResistance: 5.0,
        Vitality: 10.0,
        Charisma: 10.0,
        StunMeter: 40,
        waterResist: 0.0,
        waterLevel: 0.0,
        waterBoost: 0.0,
        fireResist: 0.0,
        fireLevel: 0.0,
        fireBoost: 0.0,
        earthResist: 0.0,
        earthLevel: 0.0,
        earthBoost: 0.0,
        windResist: 0.0,
        windLevel: 0.0,
        windBoost: 0.0,
        darkResist: 0.0,
        darkLevel: 0.0,
        darkBoost: 0.0,
        lightResist: 0.0,
        lightLevel: 0.0,
        lightBoost: 0.0,
        slashResist: 0.0,
        slashBoost: 0.0,
        bluntResist: 0.0,
        bluntBoost: 0.0,
        pierceResist: 0.0,
        pierceBoost: 0.0,
    }
    
    typeDefaults.get(EntityChecks) != undefined ? 月の光 = typeDefaults.get(EntityChecks) : 月の光 = 月の光
    SetStatboards(entity, 月の光)
    entity?.setDynamicProperty("entityStatus", JSON.stringify(月の光))
    entity?.setDynamicProperty("resetingStatus", JSON.stringify(def))
    entity?.setDynamicProperty("attacking", 0)
    entity?.setDynamicProperty("combo", 1)
    comboCounter.set(entity.id,1)
})

world.afterEvents.projectileHitEntity.subscribe(ev => {
    const hitEntity = ev.getEntityHit().entity;
    if (!hitEntity) return;
    let loc = ev.location
    let projectile = ev.projectile
    let player = ev.source
    let props
    try {
        props = JSON.parse(projectile.getDynamicProperty("properties"))
    } catch(err) {
        props = {
            damage: 10,
            particle: "blunt",
            atkspd: 1,
            effect: [""]
        }
    }
    let knockStrength = new Map([
        ["shortest",1],
        ["short",2],
        ["medium",3],
        ["long",4],
        ["knockdown",7],
        ["on_air",12]
    ])

    let launch_power = props.knockback
    system.runTimeout(() => {
        stunBreakScores.addScore(hitEntity, 0)
        let stun_meter =  hitEntity.getProperty("stat:stun_meter") 
        let blocking = hitEntity.hasTag("blocking")
        let posture = postureScore.getScore(hitEntity)
        let dmg = calculateDamageTaken(player, props.damage, props.particle, hitEntity, "")
        let theBag = backShotCheck(player, hitEntity)
        let stunThreshold
        let statusses = JSON.parse(hitEntity.getDynamicProperty("resetingStatus"))
        let knoks = getKnockMap(props.knockType)
        hitEntity.typeId == "minecraft:player" ? stunThreshold = 1 : stunThreshold = hitEntity.getProperty("stat:stun_threshold")
        if(hitEntity.hasTag("parriable")) {
            generalis.getObjective("clash").setScore(hitEntity, 1)
            hitEntity.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, 2, 0.2)
            hitEntity.removeTag("attack")
            hitEntity.removeTag("parriable")
            if(hitEntity.typeId == "minecraft:player") {
                hitEntity.runCommand(`execute as @s run camerashake add @s 0.3 0.3`)
            }
            world.getDimension(hitEntity.dimension.id).playSound(`random.anvil_land`,hitEntity.location)
            resolve("attack_finished")
        } else if(hitEntity.hasTag("Immune")) {
            hitEntity.applyKnockback(hitEntity.getViewDirection().x, hitEntity.getViewDirection().z, 2, 0.2)
            if(hitEntity.typeId == "minecraft:player") {
                hitEntity.runCommand(`execute as @s run camerashake add @s 0.3 0.3`)
            }
            world.getDimension(hitEntity.dimension.id).playSound(`random.anvil_land`,hitEntity.location)
            resolve("attack_finished")
        }if(blocking && theBag) {
            hitEntity.playAnimation(`animation.zombie_paced.staggered_0.1`)
            hitEntity.removeTag("blocking")
            hitEntity.removeTag("attack")
            hitEntity.runCommand(`reload`)
            system.runTimeout(()=>{
                hitEntity.applyDamage(dmg)
                try{
                    hitEntity.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, launch_power[0], launch_power[1])
                } catch(err){
                    console.warn("no entity")
                }
            },1)
            resolve("attacking_finished")
        } else if(blocking && !theBag) {
            let equipment = hitEntity.getComponent("minecraft:equippable");
            let mainhand = equipment?.getEquipmentSlot(`Mainhand`)?.getItem()
            let weaponType = weapons[weaponTypeSplicer(mainhand)]
            let animpref = weaponType?.stylePrefixes[hitEntity.getProperty("fighting:style")]
            animpref == undefined || animpref == "" ? animpref = weaponType?.stylePrefixes[0] : animpref = animpref
            hitEntity.runCommand(`execute as @s run camerashake add @s 0.3 0.3`)
            let blocking_reduction = block_damage - weapons[weaponType].block_power
            blocking_reduction <= 0 ? blocking_reduction = 10 : blocking_reduction = blocking_reduction
            if((posture - blocking_reduction) <= 0) {
                stunnedScores.setScore(hell, 1)
                stunLock(hitEntity, 20)
                hitEntity.removeTag("blocking")
                hitEntity.removeTag("attack")
                hitEntity.runCommand(`reload`)
                statusses["blockRecovery"] = 30
                hitEntity.playAnimation(`animation.zombie_paced.staggered_0.1`)
                postureScore.setScore(hitEntity, 0)
                world.getDimension(hitEntity.dimension.id).playSound(`random.anvil_land`,hitEntity.location)
                system.runTimeout(()=>{
                    hitEntity.applyDamage(dmg)
                    try{
                        hitEntity.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, launch_power[0], launch_power[1])
                    } catch(err){
                        console.warn("no entity")
                    }
                },1)
            } else {
                system.runTimeout(()=>{
                    hell.playAnimation(`animation.${animpref}.block`, 
                    {
                            blendOutTime: 0.5,
                            stopExpression: "!query.is_using_item",
                            nextState: `animation.${animpref}.combat_stance`
                    })
                },12)
                world.getDimension(hitEntity.dimension.id).playSound(`random.anvil_land`,hitEntity.location)
                if(perf.get(hitEntity.id) == 1) {
                    hitEntity.playAnimation(`animation.${animpref}.parry`)
                    postureScore.setScore(hitEntity, (posture - Math.floor(blocking_reduction * 0.5)))
                    statusses["blockRecovery"] = 5
                    resolve("parried")
                } else {
                    hell.playAnimation(`animation.${animpref}.hit_on_block`)
                    postureScore.setScore(hitEntity, (posture - blocking_reduction))
                    statusses["blockRecovery"] = 10
                    resolve("blocked")
                }
            } 
        } else {
            hitEntity.applyDamage(dmg)
            try{
                hitEntity.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, launch_power[0], launch_power[1])
            } catch(err){
                console.warn("no entity")
            }
            
            if(dmg >= 8) {
                hitEntity.runCommand(`execute as @s run camerashake add @s 0.3 0.3`)
            } else {
                hitEntity.runCommand(`execute as @s run camerashake add @s 0.1 0.1`)
            }
            let che4ck = stunBreakScores.getScore(hitEntity)
            if(props.knockType == "knockdown" && (stun_meter - props.stunDamage) <= 0 && che4ck == 0) {
                try{
                    hitEntity.triggerEvent(`combat:cooldown_${knockType}`)
                    if(hitEntity.typeId == "minecraft:player") {
                        hitEntity.setDynamicProperty("attacking",1)
                        hitEntity.runCommandAsync("inputpermission set @s movement disabled")
                        system.runTimeout(()=>{
                            hitEntity.setDynamicProperty("attacking",0)
                            hitEntity.runCommandAsync("inputpermission set @s movement enabled")
                        },knoks[0])
                    } else {
                        hitEntity.addEffect("weakness", knoks[0], { amplifier: 100, showParticles: false })
                        hitEntity.addEffect("slowness", knoks[0], { amplifier: 100, showParticles: false })
                    }
                    stunTimerScores.setScore(hitEntity, 100)
                    stunCheckScores.setScore(hitEntity, 1)
                    stunnedScores.setScore(hitEntity, 1)
                    stunBreakScores.setScore(hitEntity, 1)
                } catch(err) {
                    hitEntity.addEffect("weakness", knoks[0], { amplifier: 100, showParticles: false })
                    hitEntity.addEffect("slowness", knoks[0], { amplifier: 100, showParticles: false })
                }
            } else if((stun_meter - props.stunDamage) <= 0 && props.knockType != "knockdown" && che4ck == 0) {
                try{
                    player.triggerEvent("stun:remove")
                    hitEntity.triggerEvent(`combat:remove_attack`)
                    hitEntity.triggerEvent(`stun:remove`)
                    if(hitEntity.typeId == "minecraft:player") {
                        hitEntity.setDynamicProperty("attacking",1)
                        hitEntity.runCommandAsync("inputpermission set @s movement disabled")
                        system.runTimeout(()=>{
                            hitEntity.setDynamicProperty("attacking",0)
                            hitEntity.runCommandAsync("inputpermission set @s movement enabled")
                        },100)
                    } else {
                        hitEntity.addEffect("weakness", 100, { amplifier: 100, showParticles: false })
                        hitEntity.addEffect("slowness", 100, { amplifier: 100, showParticles: false })
                    }
                    stunTimerScores.setScore(hitEntity, 100)
                    stunnedScores.setScore(hitEntity, 1)
                    stunCheckScores.setScore(hitEntity, 1)
                    stunBreakScores.setScore(hitEntity, 1)
                    hitEntity.playAnimation(`animation.zombie_paced.stun_broken`)
                } catch(err) {
                    if(hitEntity.typeId == "minecraft:player") {
                        hitEntity.setDynamicProperty("attacking",1)
                        hitEntity.runCommandAsync("inputpermission set @s movement disabled")
                        system.runTimeout(()=>{
                            hitEntity.setDynamicProperty("attacking",0)
                            hitEntity.runCommandAsync("inputpermission set @s movement enabled")
                        },100)
                    } else {
                        hitEntity.addEffect("weakness", 100, { amplifier: 100, showParticles: false })
                        hitEntity.addEffect("slowness", 100, { amplifier: 100, showParticles: false })
                    }
                    stunTimerScores.setScore(hitEntity, 100)
                    stunCheckScores.setScore(hitEntity, 1)
                    stunBreakScores.setScore(hitEntity, 1)
                    stunnedScores.setScore(hitEntity, 1)
                    hitEntity.playAnimation(`animation.zombie_paced.stun_broken`)
                }
            } else if((stun_meter - props.stunDamage) > 0 && che4ck == 0) {
                if(player.getProperty("stat:stun_meter") < 30) {
                    player.setProperty("stat:stun_meter",(player.getProperty("stat:stun_meter") + 3))
                }
                try{
                    if(che4ck != 1||che4ck == undefined) {
                        if(stunThreshold <= knockStrength.get(props.knockType)) {
                            stunTimerScores.setScore(hitEntity, 40)
                            stunCheckScores.setScore(hitEntity, 1)
                            stunnedScores.setScore(hitEntity, 1)
                        }
                        hitEntity.setProperty("stat:stun_meter", (stun_meter - props.stunDamage))
                    }
                } catch(err) {
                    console.warn("no entity")
                }
                try{
                    if(stunThreshold <= knockStrength.get(props.knockType)) {
                        hitEntity.triggerEvent(`combat:cooldown_${props.knockType}`)
                        if(hitEntity.typeId == "minecraft:player") {
                            hitEntity.runCommandAsync("inputpermission set @s movement disabled")
                            hitEntity.setDynamicProperty("attacking",1)
                            system.runTimeout(()=>{
                                hitEntity.runCommandAsync("inputpermission set @s movement enabled")
                                hitEntity.setDynamicProperty("attacking",0)
                            },knoks[0])
                        } else {
                            hitEntity.addEffect("weakness", knoks[0], { amplifier: 100, showParticles: false })
                            hitEntity.addEffect("slowness", knoks[0], { amplifier: 100, showParticles: false })
                        }
                    } 
                } catch(err) {
                    if(hitEntity.typeId == "minecraft:player") {
                        hitEntity.runCommandAsync("inputpermission set @s movement disabled")
                        system.runTimeout(()=>{
                            hitEntity.runCommandAsync("inputpermission set @s movement enabled")
                        },knoks[0])
                    } else {
                        
                        hitEntity.addEffect("weakness", knoks[0], { amplifier: 100, showParticles: false })
                        hitEntity.addEffect("slowness", knoks[0], { amplifier: 100, showParticles: false })
                    }
                }
                if(!hitEntity.hasTag("Unbreakable")) {
                    hitEntity.playAnimation(`animation.zombie_paced.${knoks[1]}`)
                }
                
            }
            for(let ce of props.effect) {
                if(ce != "00" && ce != "" && ce != undefined)
                try{
                    effects[ce].execute(player, hell, "", dmg)
                } catch(err) {
                    console.warn("no effect")
                }
            }
        }
        hitEntity.setDynamicProperty("resetingStatus", JSON.stringify(statusses))
        
    },props.atkspd);
    //projectileDamager(loc, projectile, props.owner, hitEntity, props.range, props.damage, props.blck_damage,  props.atkspd,  props.distance,  props.numberOfTargets,  props.target_type,  props.effect,  props.knockback,  props.knockType,  props.knockCheck,  props.particle,  props.stunDamage,  props.damageType,  props.hitNumber)
})

world.afterEvents.entityDie.subscribe((e) => {
    const {deadEntity, cause} = e
    if(deadEntity?.typeId == "minecraft:player") {
        deadEntity.dimension.getEntities({ type: "minced:middle_entity", closest: 1 }).forEach(e => {
            e.remove()
        })
        let statusDefaults = {
            reductions: [0,0,0,0,0,0,0,0],
            reductionsTimers: [0,0,0,0,0,0,0,0],
            reductionsTriggers: [0,0,0,0,0,0,0,0],
            Boost: 0,
            slashBoost: 0.0,
            bluntBoost: 0.0,
            pierceBoost: 0.0,
            blockRecovery: 0,
            selectedSlot: "",
            inputs: [],
            sneakTimer: 0,
            sneakCD: 0,
            powerBar: 0,
            powerBarTrigger: 0,
            oldposture: 0,
            oldstamina: 0,
            oldpowerbar: 0,
            magicBar: 0,
            AirTime: 0,
            slash: 0.0,
            blunt: 0.0,
            pierce: 0.0,
            Alldamage: 0.0,
            magicDamage: 0.0,
            counter: 0.0,
            aiming: false,
        }
        deadEntity.setDynamicProperty("resetingStatus",JSON.stringify(statusDefaults))
      }
})