// priority: 1000

// 内存数据：格挡CD
var blockCD = {}

// 检查物品是否为指定类型的盾牌
function isShieldType(itemStack, shieldArray) {
  if (!itemStack || itemStack.isEmpty()) return false

  let itemId = itemStack.getId()
  return shieldArray.includes(itemId)
}

// 受击事件处理
EntityEvents.hurt(event => {

  let LARGE_SHIELDS = [
    "cataclysm:azure_sea_shield",
    "cataclysm:bulwark_of_the_flame",
    "minecraft:shield",
    "shieldexex:diamond_tower_shield",
    "shieldexex:golden_tower_shield",
    "shieldexex:iron_tower_shield",
    "shieldexex:netherite_tower_shield",
    "shieldexex:stone_tower_shield",
    "shieldexex:wooden_tower_shield",
  ]

  let SMALL_SHIELDS = [
    "call_of_yucutan:hematite_shield",
    "cataclysm:black_steel_targe",
    "endermanoverhaul:corrupted_shield",
    "shieldexex:diamond_shield",
    "shieldexex:golden_shield",
    "shieldexex:iron_shield",
    "shieldexex:netherite_shield",
    "shieldexex:stone_shield",
    "shieldexex:wooden_shield",
  ]
  let soldierTypes = [
    "hundred_years_war:shieldman",
  ]

  let attacker = event.source.actual
  if (!attacker || !attacker.type) return
  let entity = event.entity
  if (typeof entity.type !== 'string') return
  if (!entity || !entity.isLiving()) return
  let mainHandItem = entity.getMainHandItem()
  let offHandItem = entity.getOffHandItem()
  let blockChance = 0
  let reinforcement = 1.3

  // 检查副手（左手）持有大型盾牌 - 30%概率
  if (isShieldType(offHandItem, LARGE_SHIELDS)) {
    blockChance = 0.3
  }
  // 检查主手（右手）持有小型盾牌 - 15%概率
  else if (isShieldType(mainHandItem, SMALL_SHIELDS)) {
    blockChance = 0.15
  }
  if (soldierTypes.includes(entity.type)) {
    blockChance = blockChance * reinforcement
  }
  // 如果有格挡机会，进行概率判定
  if (blockChance > 0 && Math.random() < blockChance) {

    //播放音效
    let AABB = entity.boundingBox.inflate(40, 40, 40)
    entity.level.getEntitiesWithin(AABB).forEach(player => {
      if (player.type === "minecraft:player") {
        let pName = player.name.string
        player.runCommandSilent(`playsound minecraft:item.shield.block block ${pName} ${entity.x} ${entity.y} ${entity.z}`)
      }
    })

    // 取消本次伤害
    event.cancel()
  }


})