EntityEvents.hurt(event => {
    if (!event.entity) return
    let entity = event.entity
    let eUuid = entity.uuid.toString()
    if (!event.source.actual) return
    let attacker = event.source.actual
    let aUuid = attacker.uuid.toString()
    if (attacker.type === "hundred_years_war:warrior") {
        if (Math.random() < 0.75) return
        let extraDamage = event.damage / 2
        event.server.runCommandSilent(`execute as ${eUuid} at @s run damage @s ${extraDamage} minecraft:generic by ${aUuid} from ${aUuid}`)
        entity.level.spawnParticles("minecraft:sweep_attack", false, entity.x, entity.y + 0.5, entity.z, 0.2, 0.5, 0.2, 1, 0.05)

    }
})

// 弓箭手连续射击
EntityEvents.spawned(event => {
    let arrow = event.entity
    if (arrow.type !== "minecraft:arrow") return
    if (arrow.tags.contains("skill_arrow")) return
    let entity = arrow.getOwner()
    if (!entity) return
    let eData = entity.persistentData
    if (!eData) return
    let sSoldierData = eData.getCompound("soldier")
    if (!sSoldierData) return
    let target = entity.getTarget()
    if (!target) return

    if (sSoldierData.getString("Type") === "archer" || sSoldierData.getString("Type") === "poisoned_archer") {
        if (Math.random() < 0.75) return
        let arrowsBase = 3           // 箭矢数量
        let intervalTicks = 3        // 箭矢射出间隔
        ////////////////////
        arrow.addTag("skill_arrow")
        let totalArrows = Math.floor(arrowsBase)
        // 保存第一支箭的初始向量
        let baseMotionX = arrow.motionX
        let baseMotionY = arrow.motionY
        let baseMotionZ = arrow.motionZ
        // 发射额外箭矢
        for (let i = 1; i < totalArrows; i++) {
            entity.server.scheduleInTicks(i * intervalTicks, () => {
                if (!entity.isAlive() || entity.isRemoved()) return false

                let newArrow = Items.ARROW.createArrow(entity.level, "minecraft:arrow", entity)
                newArrow.setPos(entity.x, entity.y + entity.getEyeHeight(), entity.z)

                // 添加轻微随机散布
                let randomSpread = (Math.random() - 0.5) * 0.45

                // 使用保存的初始向量计算运动，而不是实时获取
                let motionX = baseMotionX + randomSpread
                let motionY = baseMotionY + 0.1
                let motionZ = baseMotionZ + randomSpread

                // 应用运动效果
                newArrow.mergeNbt({ Motion: [motionX, motionY, motionZ] })
                newArrow.pickup = "disallowed"
                newArrow.addTag("skill_arrow")
                entity.level.addFreshEntity(newArrow)

                // 视听效果 - 使用实体位置而不是箭的位置
                entity.level.spawnParticles("minecraft:poof", false, entity.x, entity.y + entity.getEyeHeight(), entity.z, motionX, motionY, motionZ, 3, 0)
                entity.level.playSound(null, entity.x, entity.y, entity.z, 'minecraft:entity.arrow.shoot', 'players', 0.8, 0.8)
            })
        }
        return false
    }
})

// 侵蚀祭司远程投掷
EntityEvents.spawned(event => {
    let projectile = event.entity
    if (projectile.type !== "minecraft:potion") return
    if (!projectile.getOwner()) return
    let entity = projectile.getOwner()
    if (!entity.getTarget()) return
    let target = entity.getTarget()

    // 检查是否为侵蚀祭司
    if (
        entity.type.toString() === "hundred_years_war:priest" &&
        entity.tags.contains("snk_minion")
    ) {
        // 计算抛射物位置和目标位置
        let projPos = [projectile.x, projectile.y, projectile.z]
        let targetPos = [target.x, target.y + target.getBbHeight() * 0.5, target.z]

        // 计算水平距离
        let dx = targetPos[0] - projPos[0]
        let dz = targetPos[2] - projPos[2]
        let horizontalDistance = Math.sqrt(dx * dx + dz * dz)

        // 计算高度差（目标高度 - 投掷高度）
        let dy = targetPos[1] - projPos[1]

        // 根据距离调整弹道参数
        // 基础速度和重力参数
        let baseSpeed = 0.8
        let gravity = -0.03 // Minecraft重力加速度

        // 距离越远，需要更高的抛射角度
        let distanceFactor = Math.min(horizontalDistance / 20.0, 2.0) // 限制最大影响因子

        // 计算水平方向速度
        let horizontalSpeed = baseSpeed * (1.0 + distanceFactor * 0.3)

        // 计算水平方向单位向量
        let dirX = dx / horizontalDistance
        let dirZ = dz / horizontalDistance

        // 计算垂直速度
        // 使用抛体运动公式：dy = vy * t + 0.5 * g * t²
        // 其中 t = horizontalDistance / horizontalSpeed
        let flightTime = horizontalDistance / horizontalSpeed

        // 避免除零错误
        if (flightTime < 0.1) flightTime = 0.1

        // 计算所需的垂直速度
        let verticalSpeed = (dy - 0.5 * gravity * flightTime * flightTime) / flightTime

        // 确保有足够的上抛速度，使轨迹更平滑
        let minVerticalSpeed = 0.3 + distanceFactor * 0.2
        if (verticalSpeed < minVerticalSpeed) {
            verticalSpeed = minVerticalSpeed
        }

        // 限制最大垂直速度，防止抛得太高
        let maxVerticalSpeed = 1.5
        if (verticalSpeed > maxVerticalSpeed) {
            verticalSpeed = maxVerticalSpeed
        }

        // 应用计算出的运动向量
        let motionX = dirX * horizontalSpeed
        let motionY = verticalSpeed
        let motionZ = dirZ * horizontalSpeed

        // 添加轻微随机散布，使弹道更自然
        let spread = 0.05
        motionX += (Math.random() - 0.5) * spread
        motionY += (Math.random() - 0.5) * spread * 0.5
        motionZ += (Math.random() - 0.5) * spread

        // 设置抛射物的运动向量
        projectile.mergeNbt({
            Motion: [
                motionX,
                motionY,
                motionZ
            ]
        })

        // 添加视听效果
        projectile.level.spawnParticles(
            "minecraft:witch",
            false,
            projPos[0], projPos[1], projPos[2],
            motionX * 0.5, motionY * 0.5, motionZ * 0.5,
            2,
            0
        )
        projectile.level.playSound(
            null,
            projPos[0], projPos[1], projPos[2],
            'minecraft:entity.witch.throw',
            'neutral',
            0.7,
            0.9 + Math.random() * 0.2
        )
    }
})