// priority: 9
//黑金属自残
NativeEvents.onEvent($LivingHurtEvent, event => {
    let player = event.source.actual
    if (!player || !player.isPlayer()) return

    let time = player.persistentData.getInt('blackmetal_ingot') ?? 0
    let CD = Math.abs(player.age - time)
    if (CD < 5) return
    player.persistentData.putInt('blackmetal_ingot', player.age)

    let mainitem = player.getMainHandItem()
    let offitem = player.getOffHandItem()
    let level = simpleGetTetraEffectLevel(mainitem, 'blackmetal_ingot') + simpleGetTetraEffectLevel(offitem, 'blackmetal_ingot')

    if (level > 0) {
        let health = player.health
        player.setHealth(Math.max(health - level, 1))
        player.attack(1)
    }
})
//右键施法
ItemEvents.rightClicked(event => {
    let player = event.entity
    let mainitem = player.getMainHandItem()
    let offitem = player.getOffHandItem()

    let effectLevel_main = simpleGetTetraEffectLevel(mainitem, 'cast')
    let effectLevel_off = simpleGetTetraEffectLevel(offitem, 'cast')

    if (effectLevel_main > 0 || effectLevel_off > 0) {
        let $Utils = Java.loadClass('io.redspace.ironsspellbooks.api.util.Utils')
        $Utils.serverSideInitiateCast(player)
    }
})
//处决词条
ItemEvents.rightClicked(event => {
    let player = event.entity
    let item = player.getOffHandItem()
    if (item.item instanceof $ModularItem) {
        //获取处决效果
        let euclidean_dagger_level = simpleGetTetraEffectLevel(item, 'euclidean_dagger')
        //获取视线上的实体
        let entity_reach = player.getAttributeTotalValue('forge:entity_reach')
        let entity = player.rayTrace(entity_reach).entity
        //获取真实横扫
        let truesweep_level = simpleGetTetraEffectLevel(item, 'truesweep')
        if (euclidean_dagger_level > 0 && truesweep_level == 0) {
            //处于冷却不触发2
            if (player.getCooldowns().isOnCooldown(item)) return
            if (!entity) {
                //获取猛刺横扫攻击力
                let jab_level = simpleGetTetraEffectLevel(item, 'jab')
                let sweeping_level = simpleGetTetraEffectLevel(item, 'sweeping')
                let damage_value = item.item.getAttributeValue(item, $Attributes.ATTACK_DAMAGE) + 1

                let total_damage = damage_value * (jab_level / 100 + sweeping_level * 0.125)

                //触发自己写的真实横扫
                $hp_sweeping.truesweep(item, player, true, total_damage)
            }
        }
    }
})
//均衡词条
NativeEvents.onEvent($LivingHurtEvent, event => {
    let player = event.source.entity
    let entity = event.entity
    if (player && player.isPlayer() && entity) {
        let item = player.getOffHandItem()
        if (item.item instanceof $ModularItem) {
            let equilibrium_level = simpleGetTetraEffectLevel(item, 'equilibrium')
            if (equilibrium_level > 0) {
                event.amount = event.amount * (1 - equilibrium_level / 100)
            }
        }
    }
})
//伊甸碎片效果实现
ItemEvents.rightClicked(event => {
    let player = event.entity

    let item = player.getOffHandItem()
    if (player.getCooldowns().isOnCooldown(item)) return

    if (item.item instanceof $ModularItem) {
        let fragment_of_eden_level = simpleGetTetraEffectLevel(item, 'fragment_of_eden')
        //获取副手猛刺效果
        let jab = simpleGetTetraEffectLevel(item, 'jab')
        let block_reach = player.getAttributeTotalValue('forge:block_reach')
        let entity_reach = player.getAttributeTotalValue('forge:entity_reach')
        if (fragment_of_eden_level > 0 && jab > 0 && block_reach > entity_reach) {
            let entity = player.rayTrace(block_reach).entity
            item.getItem().jabEntity(item, jab, player, entity)
            player.swing("off_hand", true)
        }
    }
})
//怪异碎片效果实现
ItemEvents.firstLeftClicked(event => {
    let player = event.entity
    let itemStack = player.getMainHandItem();

    // 获取存储蓄力程度
    let attackStrength = player.persistentData.getInt('attackStrength')
    //移除存储的蓄力时间
    player.persistentData.putInt('attackStrength', 0)
    if (itemStack.item instanceof $ModularItem) {
        // 检查物品是否有真实横扫效果且蓄力足够
        if (attackStrength > 0.9 && $EffectHelper.getEffectLevel(itemStack, $ItemEffect.truesweep) > 0) {
            if (simpleGetTetraEffectLevel(itemStack, 'senior_sweep') > 0) {
                // 检查物品是否同时有横扫攻击效果
                let hasSweepingStrike = $EffectHelper.getEffectLevel(itemStack, $ItemEffect.sweepingStrike) > 0
                // 检查玩家是否在地面或者在冲刺，错开原版tetra自身的真实横扫，防止出现两次真实横扫
                if (!player.onGround() || player.isSprinting()) {
                    // 触发真实横扫效果
                    $SweepingEffect.truesweep(itemStack, player, !hasSweepingStrike);
                }
            }
        }
    }

})
//玩家刻事件
PlayerEvents.tick(event => {
    let player = event.entity
    // 检查攻击蓄力程度
    let attackStrength = player.getAttackStrengthScale(0.5)
    //存储蓄力程度
    player.persistentData.putInt('attackStrength', attackStrength)
})

//灼燃效果实现
NativeEvents.onEvent($LivingHurtEvent, event => {
    if (event.entity) {
        let entity = event.entity
        let type = event.getSource().getType().toString();
        if (type == "onFire") {
            let level = entity.persistentData.getInt('burn')
            if (level > 0) {
                entity.invulnerableTime = 0
                event.amount = event.amount + level
                entity.persistentData.putInt('burn', level - 2)
            }
        }
    }
})
//磁场构建效果实现
PlayerEvents.tick(event => {
    let player = event.entity
    if (!player) return
    if (player.age % 20 != 0) return

    let mainitem = player.getMainHandItem()
    let offitem = player.getOffHandItem()

    let magnetic_activator_level_main = simpleGetTetraEffectLevel(mainitem, 'magnetic_activator')
    let magnetic_activator_level_eff = simpleGetTetraEffectLevel(offitem, 'magnetic_activator')

    if (magnetic_activator_level_main > 0 || magnetic_activator_level_eff > 0) {
        let pole_level = Math.min(simpleGetTetraEffectLevel(mainitem, 'north_pole'), simpleGetTetraEffectLevel(offitem, 'south_pole')) / 10
        player.potionEffects.add('minecraft:strength', 20 * 3, pole_level * (magnetic_activator_level_eff / 100 + magnetic_activator_level_main / 100))
    }
})

//副手磁极—南效果实现
ItemEvents.rightClicked(event => {
    let player = event.entity

    let item = player.getOffHandItem()
    if (player.getCooldowns().isOnCooldown(item)) return

    let time = player.persistentData.getInt('south_pole') ?? 0
    let CD = Math.abs(player.age - time)
    if (CD < 20 / player.getAttributeTotalValue('minecraft:generic.attack_speed')) return
    player.persistentData.putInt('south_pole', player.age)



    if (item.item instanceof $ModularItem) {
        let effectLevel = simpleGetTetraEffectLevel(item, 'south_pole')
        let effectEfficiency = simpleGetEffectEfficiency(item, 'south_pole')
        if (effectLevel > 0) {
            player.swing("off_hand", true)

            let strength_level = 0
            if ((player.hasEffect('minecraft:strength'))) {
                strength_level = player.getEffect('minecraft:strength').amplifier + 1
            }

            //获取物品攻击力
            let damageValue = item.item.getAttributeValue(item, $Attributes.ATTACK_DAMAGE) + 1 + strength_level * 3
            //获取唤雷等级
            let call_thunder_level = get_call_thunder_level(player, item).level
            //获取主手磁极等级
            let north_pole_effect_level = simpleGetTetraEffectLevel(player.getMainHandItem(), 'north_pole')

            // 获取周围实体
            let entityList = getLivingWithinRadius(player.getLevel(), player.position(), 12 + effectEfficiency)
            // 遍历实体列表
            entityList.forEach(entity => {
                if (entity.isLiving() && entity != player) {
                    for (let i = 0; i < call_thunder_level; i++) {
                        entity.getServer().scheduleInTicks(5 * i, () => {
                            simple_call_thunder(
                                entity, player,
                                damageValue * (north_pole_effect_level / 100) * (effectLevel / 100)
                            )
                        })
                    }
                }
            })
        }
    }

})
//神秘宝石移除箭矢
//暗影侵袭破除免疫弹射物
NativeEvents.onEvent($ProjectileImpactEvent, event => {
    let { rayTraceResult, entity } = event


    let player = entity.getOwner()
    if (!player || !player.isPlayer()) return
    if (entity instanceof $Arrow) {
        if (rayTraceResult.type === $HitResult.Type.BLOCK) {
            let item = player.getMainHandItem()
            let effect_level = simpleGetTetraEffectLevel(item, 'occult_gem')
            if (effect_level > 0 && entity && entity.server) {
                entity.server.scheduleInTicks(5, () => {
                    if (entity) {
                        entity.kill()
                    }
                })
            }
        }


        if (rayTraceResult.type === $HitResult.Type.ENTITY) {
            if (rayTraceResult.getEntity().type != 'hellstone_golem:hellstone_golem') {
                if (entity.owner && entity.owner.isPlayer()) {
                    let player = entity.owner
                    let item = player.getMainHandItem()

                    let effect_level = simpleGetTetraEffectLevel(item, 'shadow_erosion')
                    if (effect_level > 0) {
                        let arrow_strength = player.getAttributeTotalValue('tetra:draw_strength')
                        simpleAttackEntity(
                            false,
                            player,
                            rayTraceResult.getEntity(),
                            'arrow',
                            arrow_strength * (1 + 0.5 * Math.random())
                        )
                        entity.kill()
                        event.setCanceled(true)
                    }
                }
            }
        }
    }
    if (entity.type == 'block_factorys_bosses:sword_wave') {
        let strength = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let underworld_ingot_level = simpleGetTetraEffectLevel(player.getMainHandItem(), 'underworld_ingot')
        if (rayTraceResult.type === $HitResult.Type.ENTITY) {
            simpleAttackEntity(
                false,
                player,
                rayTraceResult.getEntity(),
                'arrow',
                strength * underworld_ingot_level / 100
            )
            event.setCanceled(true)
        }
    }
});
//泪宝石锁定攻速
PlayerEvents.tick(event => {
    let player = event.entity
    if (!player) return
    if (player.age % 10 != 0) return
    let item = player.getMainHandItem()
    if (!item) return
    let level_constant = simpleGetTetraEffectLevel(item, 'constant')
    let level_counterweight = simpleGetTetraEffectLevel(item, 'counterweight')

    // 先清除之前的加成
    player.modifyAttribute('minecraft:generic.attack_speed', 'constant', 0, 'addition')
    player.modifyAttribute('minecraft:generic.attack_speed', 'counterweight', 0, 'addition')

    // 如果有constant效果，直接设置攻击速度为1.2
    if (level_constant > 0) {
        let current_speed = player.getAttributeTotalValue('minecraft:generic.attack_speed')
        if (current_speed < 1.2) {
            player.modifyAttribute('minecraft:generic.attack_speed', 'constant', 1.2 - current_speed, 'addition')
        }
    } else if (level_counterweight > 0) {
        let current_speed = player.getAttributeTotalValue('minecraft:generic.attack_speed')
        if (current_speed < 1) {
            player.modifyAttribute('minecraft:generic.attack_speed', 'counterweight', 1 - current_speed, 'addition')
        }
    }
});
//连携效果实现
ItemEvents.firstLeftClicked(event => {
    let player = event.entity
    let entity = player.rayTrace().entity

    let itemstack = player.getMainHandItem()
    let offitem = player.getOffHandItem()

    //获取连携效果等级
    let main_effect = simpleGetTetraEffectLevel(itemstack, 'connected')
    let off_effect = simpleGetTetraEffectLevel(offitem, 'connected')
    //检查主副手是否同时含有连携buff
    if (main_effect == 0 || off_effect == 0) return


    // 获取存储蓄力程度
    let attackStrength = player.persistentData.getInt('attackStrength')
    //移除存储的蓄力时间
    player.persistentData.putInt('attackStrength', 0)
    // 检查物品是否蓄力足够
    if (attackStrength < 0.9) return

    //获取副手真实横扫的等级
    let truesweep = simpleGetTetraEffectLevel(offitem, 'truesweep')
    //获取副手猛刺效果
    let jab = simpleGetTetraEffectLevel(offitem, 'jab')

    //副手有真实横扫的情况
    if (truesweep > 0) {
        player.getServer().scheduleInTicks(5, () => {
            let time = 0
            if (entity) {
                time = entity.invulnerableTime
                entity.invulnerableTime = 0
            }
            //副手挥舞效果
            player.swing("off_hand", true)
            // 触发真实横扫效果
            $SweepingEffect.truesweep(offitem, player, true)
            if (entity && time != 0) {
                entity.invulnerableTime = time
            }
        })
    } else if (jab > 0) {
        if (entity) {
            player.getServer().scheduleInTicks(5, () => {
                let time = entity.invulnerableTime
                entity.invulnerableTime = 0
                offitem.getItem().jabEntity(offitem, jab, player, entity)
                player.swing("off_hand", true)
                entity.invulnerableTime = time
            })
        }
    }

})
//玩家刻事件获取存储的蓄力程度
PlayerEvents.tick(event => {
    let player = event.entity
    if (!player) return
    // 检查攻击蓄力程度
    let attackStrength = player.getAttackStrengthScale(0.5)
    //存储蓄力程度
    player.persistentData.putInt('attackStrength', attackStrength)
})

//下界砖
BlockEvents.broken(event => {
    let player = event.player
    if (!player) return

    let item = player.getMainHandItem()
    let netherBrickLevel = simpleGetTetraEffectLevel(item, 'nether_brick')
    if (netherBrickLevel > 0 && event.block.id === 'minecraft:netherrack') {
        let dropChance = 0.1 + (netherBrickLevel - 1) * 0.1

        if (Math.random() < dropChance) {
            // 掉落1-3个金粒
            let goldCount = Math.floor(Math.random() * 3) + 1
            let blockPos = event.block.pos

            // 在方块位置掉落金粒
            for (let i = 0; i < goldCount; i++) {
                event.block.popItem('minecraft:gold_nugget')
            }
        }
    }
})
//雷灵自主御敌
function lei_ling(event) {
    let entity = event.entity
    let player = event.getNewTarget()
    if (player && player.isPlayer() && !entity.persistentData.contains('owner') && !entity.persistentData.contains('biao_ji')) {

        let item = player.getMainHandItem()
        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage');
        if (!hasItemEffect(item, 'lei_ling')) return

        simple_call_thunder(entity, player, damageValue * 5)
        entity.persistentData.put('biao_ji', 1)
    }
}

//连锁effect
BlockEvents.broken(event => {
    let player = event.player
    if (!player) return

    let time = player.persistentData.getInt('chain_destruction') ?? 0
    let CD = Math.abs(player.age - time)
    if (CD < 2) return
    player.persistentData.putInt('chain_destruction', player.age)

    let item = player.getMainHandItem()
    let level = simpleGetTetraEffectLevel(item, 'chain_destruction')


    if (!player.persistentData.getBoolean('chain_destruction_switch') && level > 0) {

        chain_destruction(event, level)

    }
})
//活体剑刃造成伤害
function otherplayerattack_2(event) {
    let player = event.source.player;
    let type = event.getSource().getType().toString();
    let item = player.getMainHandItem();

    // 检测来源
    if (!(item.item instanceof $ModularItem)) return;

    let itemNbt = item.nbt;
    let maxhealth = player.maxHealth;

    // 是否为活体剑刃
    if (hasItemEffect(item, 'huo_ti_jian_ren')) {
        // 如果不是近战伤害类型返回
        if (type !== 'player') {
            event.amount = event.amount * 0.1
            return
        };

        let huo_ti_jian_ren_level = simpleGetTetraEffectLevel(item, 'huo_ti_jian_ren')
        let huo_ti_jian_ren_efficiency = simpleGetEffectEfficiency(item, 'huo_ti_jian_ren')

        // 活化增伤
        let livingEffect = player.hasEffect('kubejs:living')
            ? player.getEffect('kubejs:living')
            : null;
        let level_1 = livingEffect ? livingEffect.getAmplifier() : 0;

        // 噬咬增伤
        let effectData = getPlayerCuriosEffectData(player, 'devouring_bites');
        let effect_level = effectData ? effectData.efficiency : 0;
        let curYingYangCount = player.persistentData.getInt(YingYangCount);

        let level_2 = Math.min(curYingYangCount * effect_level / 100, curYingYangCount);
        if (level_2 < 0) level_2 = 0;

        updateYingYangCount(player, curYingYangCount - level_2);

        // 计算最终伤害
        event.amount = event.amount * (1 - huo_ti_jian_ren_efficiency / 100) + maxhealth * (huo_ti_jian_ren_level / 100 + level_1 * 0.05) + level_2
    }
}
//时之沙效果
function EquipmentChange(event) {
    let player = event.entity
    let item = player.getMainHandItem()
    if (item.nbt && item.nbt.kubejs_damage) {
        player.modifyAttribute('minecraft:generic.attack_damage', 'kubejs_damage', item.nbt.kubejs_damage, 'addition');
    } else {
        player.removeAttribute('minecraft:generic.attack_damage', 'kubejs_damage');
    }
}
//铁块防御buff
PlayerEvents.tick(event => {
    let player = event.player
    if (player.age % 20 != 0 || !player) return;

    let item = player.getMainHandItem()
    let effect_level = simpleGetTetraEffectLevel(item, 'iron_blocks_defense')


    if (player.hasEffect('kubejs:iron_blocks_defense') && effect_level > 0) {
        let effect = player.getEffect('kubejs:iron_blocks_defense')
        let level = effect.getAmplifier() + 1
        // 更新护甲值
        player.modifyAttribute('minecraft:generic.armor', 'iron_blocks_defense', level * effect_level, 'addition')
        player.modifyAttribute('minecraft:generic.armor_toughness', 'iron_blocks_defense', (level * effect_level) / 2, 'addition')
    } else {
        // 如果buff消失，移除护甲加成
        player.removeAttribute('minecraft:generic.armor', 'iron_blocks_defense')
        player.removeAttribute('minecraft:generic.armor_toughness', 'iron_blocks_defense')
    }
})



/**
 * 从玩家位置沿视线方向释放一道音波攻击
 * @param {Internal.Player} player - 发起攻击的玩家
 * @param {Internal.RayTraceResultJS} vec3Nor - 音爆发射的方向
 * @param {number} maxDistance - 射程（格）
 * @param {number} finalDamage - 伤害公式
 */
function performSonic(player, vec3Nor,  maxDistance, finalDamage) {
    if (!player || player.level.isClientSide()) return;

    let level = player.level;
    let mainHandItem = player.getMainHandItem();

    let attackSource = 'minecraft:player_attack';

    let sculkLevel = simpleGetTetraEffectLevel(mainHandItem, 'sculkTaint')
    let sculkEfficiency = simpleGetEffectEfficiency(mainHandItem, 'sculkTaint')

    // if (finalDamage == null) finalDamage = 1;

    // // 计算实际作用距离
    let distance = maxDistance;
    // 获取玩家的视线方向向量并归一化（确保方向向量长度为1）
    // let vec3Nor = player.getLookAngle().normalize();

    // 沿视线生成粒子并检测范围伤害
    for (let i = 0; i < distance; i += 2) {
        // 当前音波位置 = 眼睛位置 + 方向 * 距离
        let vec3 = vec3Nor.scale(i + 5).add(player.getEyePosition());

        // 生成粒子（sonic_boom）
        level.spawnParticles('sonic_boom', false, vec3.x(), vec3.y(), vec3.z(), 0, 0, 0, 1, 0);

        // 每间隔1格（i为偶数时）检测范围内的实体
        if (i % 2 == 0) {
            // 获取当前位置周围2格内的所有活体实体
            let entityInRadius = getLivingWithinRadius(player.level, vec3, 3);
            // 遍历范围内的实体
            entityInRadius.forEach(e => {
                // 忽略玩家自身（只对非玩家实体造成伤害）
                if (!e.isPlayer()) {
                    simpleAttackEntity(false, player, e, attackSource, finalDamage);
                    $SculkTaintEffect.perform(e.level, e.blockPosition(), sculkLevel, sculkEfficiency);
                }
            });
        }
    }
}


/**
 * 在玩家视线的局部平面内旋转方向向量，ai真是太好用了
 * @param {Vec3d} forward - 原始方向向量
 * @param {number} angleDegrees - 旋转角度（正数：向右偏，负数：向左偏）
 * @param {Player} player - 用于获取位置构造向量
 * @returns {Vec3d} 旋转后的新方向（归一化）
 */
function rotateDirectionInLocalPlane(forward, angleDegrees, player) {
    let tempPos = player.position();
    let worldUp = tempPos.add(0, 1, 0).subtract(tempPos);      // (0,1,0)
    let worldEast = tempPos.add(1, 0, 0).subtract(tempPos);    // (1,0,0)

    // 选择参考轴：避免与 forward 平行
    let refAxis = (Math.abs(forward.y()) < 0.99) ? worldUp : worldEast;

    // 计算右向量（局部平面的“右”）
    let rightVec = forward.cross(refAxis);
    if (rightVec.lengthSqr() < 1e-8) {
        // fallback
        rightVec = forward.cross(worldEast);
    }
    rightVec = rightVec.normalize();

    const PI = 3.141592653589793;
    let angleRad = angleDegrees * PI / 180.0;
    let cos = Math.cos(angleRad);
    let sin = Math.sin(angleRad);

    // 手动计算旋转后分量
    let x = forward.x() * cos + rightVec.x() * sin;
    let y = forward.y() * cos + rightVec.y() * sin;
    let z = forward.z() * cos + rightVec.z() * sin;

    // 用 position 差值法构造新向量（KubeJS 安全）
    let origin = player.position();
    return origin.add(x, y, z).subtract(origin).normalize();
}