// priority: 9
//参考脆骨症夜鸢大佬的代码
//不清楚优化会不会更好，但是写起来方便一点
ItemEvents.rightClicked(event => {
    let player = event.player;
    if (!player || event.hand !== 'MAIN_HAND') return;
    let item = player.getMainHandItem();
    if (!item.item instanceof $ModularItem) return;

    let effects = getAllEffects(item);
    if (!effects) return;
    effects.forEach(effect => {
        let strategy = tetra_player_you_jian_strategies[effect.name] || tetra_player_you_jian_strategies.default;
        strategy(event, player, effect.level, item, effect.name, effect.efficiency);
    });
});


const tetra_player_you_jian_strategies = {
    'echo_sound_wave': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 1) return
        player.persistentData.putInt(effectname, player.age)

        // $UseAnim.BLOCK
        // $ChargedAbilityEffect.perform()
        
    //    let aa = $ComboPoints.get(player)
    //     console.log(aa)
    //     $ComboPoints.reset(player)
        
    //     console.log($ComboPoints.get(player))

        // // 不是特殊形态不让用
        // let mainHandItem = player.getMainHandItem();
        // if (!ShowModelHelper.getShowModels(mainHandItem).contains("form_6")) return

        // // 防止卡永久变形
        // let time1 = player.persistentData.getInt('echo_form') ?? 0
        // let CD1 = Math.abs(player.age - time1)
        // if (CD1 > 20 * 30 + 5) {
        //     if (!ShowModelHelper.getShowModels(mainHandItem).contains("form_6")) return
        //     let frameInterval = 2; // 每帧的间隔时间
        //     let baseModels = [
        //         "form_1",
        //         "form_2",
        //         "form_2",
        //         "form_3",
        //         "form_4",
        //         "form_5",
        //         "form_6",
        //         "form_6",
        //         "form_6"
        //     ];
        //     // 生成倒序序列（去除重复的首尾元素）
        //     let reversedModels = []

        //     // 从原数组最后一个元素开始遍历，依次添加到新数组
        //     for (let i = baseModels.length - 1; i >= 0; i--) {
        //         reversedModels.push(baseModels[i]);
        //     }
        //     // 播放
        //     reversedModels.forEach((model, index) => {
        //         let tickTime = index * frameInterval;
        //         player.getServer().scheduleInTicks(tickTime, () => {
        //             if (index > 0) {
        //                 ShowModelHelper.removeShowModel(item, reversedModels[index - 1]);
        //             }
        //             ShowModelHelper.addShowModel(item, model, "item");
        //         });
        //     });
        //     return
        // }

        // // 音效
        // player.server.runCommandSilent(`execute positioned ${player.x} ${player.y} ${player.z} run playsound minecraft:entity.warden.sonic_charge player @a ~ ~ ~ 0.7 1 0`)
        // player.server.runCommandSilent(`execute positioned ${player.x} ${player.y} ${player.z} run playsound minecraft:entity.warden.sonic_boom player @a ~ ~ ~ 0.3 1 0`)

        // // 获取玩家的基础攻击伤害
        let attack_damage = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let vec3Nor = player.getLookAngle().normalize();

        // 向右偏 30°
        let vecRight = rotateDirectionInLocalPlane(vec3Nor, 30, player);

        // 向左偏 30°（等价于 -30）
        let vecLeft = rotateDirectionInLocalPlane(vec3Nor, -30, player);

        let finalDamage = Math.max(effectLevel, 1) * Math.max(efficiency, 1) * attack_damage

        // performSonic(player, vec3Nor, 24, finalDamage)

        // player.getServer().scheduleInTicks(20 * 1, () => {
        //     performSonic(player, vecRight, 24, finalDamage)
        //     performSonic(player, vecLeft, 24, finalDamage)
        // });

        const totalBeams = 24;
        const angleStep = 360 / totalBeams; // 24°

        for (let index = 0; index < totalBeams + 3; index++) {
            let delayTicks = index * 2; 
            let currentAngle = index * angleStep; // 0, 24, 48, ..., 336
            player.getServer().scheduleInTicks(delayTicks, () => {
                let dir = rotateDirectionInLocalPlane(vec3Nor, currentAngle, player);
                // let dir1 = rotateDirectionInLocalPlane(rotateDirectionInLocalPlane(vec3Nor, -30, player), -currentAngle, player);
                performSonic(player, dir, 24, finalDamage);
                // performSonic(player, dir1, 24, finalDamage);
            });
        }
    },
    //改进型推进器
    'tui_jin_qi': function (event, player, effectLevel, item, effectname, efficiency) {
        player.sendData('tui_jin_qi', { 'effectLevel': effectLevel })

        let attack_damage = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let move_speed = player.getAttributeTotalValue('minecraft:generic.movement_speed')

        for (let i = 0; i <= 4; i++) {
            player.server.scheduleInTicks(i, () => {
                if (player.level.getEntities(player, player.getBoundingBox().inflate(0.1)).length > 0) {
                    player.level.getEntities(player, player.getBoundingBox().inflate(0.1)).forEach(entity => {
                        simpleAttackEntity(
                            false, player, entity, 'common',
                            attack_damage * (1 + get_gear_shift(player) / 100)
                        )
                    });
                    player.level.playSound(null, player.x, player.y, player.z,
                        'kubejs:music.man', 'players', 3, 3)
                }
            })
        }
    },
    //冥界骑士
    'underworld_ingot': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.getCooldowns().isOnCooldown(item)) return
        let CD = 1 / player.getAttributeTotalValue('minecraft:generic.attack_speed')
        player.addItemCooldown(item, CD * 20)

        let damage = player.getAttributeTotalValue('minecraft:generic.attack_damage') * effectLevel / 100
        $SwordWaveEntity.shoot(player.level, player, $RandomSource.create(), 1, damage, 1)
        player.swing()

    },
    //音波
    //参考脆骨症
    'sound_wave': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 1) return
        player.persistentData.putInt(effectname, player.age)

        // 不是特殊形态不让用
        let mainHandItem = player.getMainHandItem();
        let SculkLevel = simpleGetTetraEffectLevel(mainHandItem, 'sculkTaint')
        let SculkEfficiency = simpleGetEffectEfficiency(mainHandItem, 'sculkTaint')


        // 音效
        player.server.runCommandSilent(`execute positioned ${player.x} ${player.y} ${player.z} run playsound minecraft:entity.warden.sonic_charge player @a ~ ~ ~ 0.7 1 0`)
        player.server.runCommandSilent(`execute positioned ${player.x} ${player.y} ${player.z} run playsound minecraft:entity.warden.sonic_boom player @a ~ ~ ~ 0.3 1 0`)


        // 获取玩家的基础攻击伤害
        let attack_damage = player.getAttributeTotalValue('minecraft:generic.attack_damage')

        // 玩家向前进行射线追踪（最大距离24格，忽略液体）
        let ray = player.rayTrace(24, true);
        // 获取射线追踪的距离（从玩家到命中点的距离）
        let distance = ray.distance;
        // 获取玩家的视线方向向量并归一化（确保方向向量长度为1）
        let vec3Nor = player.getLookAngle().normalize();

        // 如果射线命中了生物实体（且是活体）
        if (ray.entity && ray.entity.isLiving()) {
            // 对命中的实体造成声波伤害
            // 伤害公式：效果等级 × 效率 × 基础攻击伤害
            simpleAttackEntity(false, player, ray.entity, 'minecraft:player_attack', Math.max(effectLevel, 1) * Math.max(efficiency, 1) * attack_damage);
            $SculkTaintEffect.perform(player.level, ray.entity.blockPosition(), SculkLevel, SculkEfficiency); // 触发幽匿效果
        }

        // 如果射线命中了方块（而非实体），更新距离为玩家到方块的实际距离
        if (ray.block) {
            distance = player.getPosition(1.0).distanceTo(ray.block.pos);
        }

        // 沿玩家视线方向，从玩家位置到命中点生成声波效果
        for (let i = 0; i < distance; i = i + 2) {
            // 计算当前位置：视线方向 × 步数 + 玩家眼睛位置（确保从玩家视角出发）
            let vec3 = vec3Nor.scale(i).add(player.getEyePosition());
            // 在当前位置生成"sonic_boom"（声波）粒子效果
            event.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(event.level, vec3, 3);
                // 遍历范围内的实体
                entityInRadius.forEach(e => {
                    // 忽略玩家自身（只对非玩家实体造成伤害）
                    if (!e.isPlayer()) {
                        // 对范围内的实体造成与射线命中实体相同的声波伤害
                        simpleAttackEntity(false, player, e, 'minecraft:player_attack', Math.max(effectLevel, 1) * Math.max(efficiency, 1) * attack_damage);
                        $SculkTaintEffect.perform(e.level, e.blockPosition(), SculkLevel, SculkEfficiency); // 触发幽匿效果
                    }
                });
            }
        }
    },
    //阴影石
    'shadow_stone': function (event, player, effectLevel, item, effectname, efficiency) {
        let lightLevel = getPlayerLightLevel(player)
        player.tell(lightLevel)
    },
    // 觉醒极光
    'dream_aurorian_awakened': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 20) {
            let remainingSeconds = Math.ceil((20 * 20 - CD) / 20)
            player.tell(`§d§d技能冷却中 (${remainingSeconds}秒)§r§d`)
            return
        }
        player.persistentData.putInt(effectname, player.age)

        // 获取武器伤害值
        let weaponDamage = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        // 播放特效和声音
        player.swing()
        player.level.playSound(null, player.x, player.y, player.z, 'minecraft:entity.ender_dragon.ambient', 'players', 1.0, 1.5)

        createAwakenedStartupEffects(player)
        // 执行10次攻击，每0.2秒(4tick)一次
        for (let i = 0; i < 12; i++) {
            Utils.server.scheduleInTicks(i * 4, () => {
                let entityList = getLivingWithinRadius(player.getLevel(), player.position(), 10)

                // 攻击范围内的敌人
                entityList.forEach(entity => {
                    if (entity.isLiving() && entity != player) {
                        simpleAttackEntity(true, player, entity, 'common', weaponDamage * 0.5)
                        // 攻击特效
                        dreamAurorianAttackParticles(entity)
                        drawSingleRandomSlashLineWithOffset(entity, 'minecraft:happy_villager', 0, player)
                    }
                })
                weaponDamage = weaponDamage * 1.1
                // 极光环绕特效
                dreamAurorianAuraParticles(player)
            })
        }

        // 11次攻击完成后（12*4=48tick + 16tick延迟）
        Utils.server.scheduleInTicks(48 + 16, () => {
            createJudgmentEye(player, weaponDamage * Math.pow(1.1, 12))
            Utils.server.scheduleInTicks(20 * 2, () => {
                let entityList = getLivingWithinRadius(player.getLevel(), player.position(), 10)
                entityList.forEach(entity => {
                    if (entity.isLiving() && entity != player) {
                        entity.potionEffects.add('minecraft:slowness', 20 * 3, 10)
                        simpleAttackEntity(true, player, entity, 'minecraft:out_of_world', player.getAttributeTotalValue('minecraft:generic.attack_damage') * 2)
                        // 攻击特效
                        dreamAurorianAttackParticles(entity)
                        drawTimeFissureSlash(entity, player, 3.0)
                    }
                })
            })
        })
    },
    //红石之心
    'redstone_heart': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 30) return
        player.persistentData.putInt(effectname, player.age)

        let Level = simpleGetTetraEffectLevel(item, 'redstone_heart')

        let effect_level = player.getAttributeTotalValue('minecraft:generic.armor') + player.getAttributeTotalValue('minecraft:generic.armor_toughness')

        player.potionEffects.add('minecraft:absorption', 20 * 15, (effect_level * Level) / 8)
    },
    // 融梦极光技能
    'dream_aurorian_steel': function (event, player, effectLevel, item, effectname, efficiency) {
        if (simpleGetTetraEffectLevel(item, 'dream_aurorian_awakened') > 0) return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 20) {
            let remainingSeconds = Math.ceil((20 * 20 - CD) / 20)
            player.tell(`§b§d技能冷却中(${remainingSeconds}秒)§r§b`)
            return
        }
        player.persistentData.putInt(effectname, player.age)

        // 获取武器伤害值
        let weaponDamage = player.getAttributeTotalValue('minecraft:generic.attack_damage')

        // 播放特效和声音
        player.swing()
        player.level.playSound(null, player.x, player.y, player.z, 'minecraft:entity.ender_dragon.ambient', 'players', 1.0, 1.5)

        // 执行10次攻击，每0.2秒(4tick)一次
        for (let i = 0; i < 8; i++) {
            Utils.server.scheduleInTicks(i * 4, () => {
                let entityList = getLivingWithinRadius(player.getLevel(), player.position(), 10)

                // 攻击范围内的敌人
                entityList.forEach(entity => {
                    if (entity.isLiving() && entity != player) {
                        simpleAttackEntity(true, player, entity, 'common', weaponDamage * 0.4)

                        dreamAurorianAttackParticles(entity)

                    }
                })
                // 极光环绕特效
                dreamAurorianAuraParticles(player)
            })
        }
    },
    //传送法杖
    'traveler_staff': function (event, player, effectLevel, item, effectname) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20) return
        player.persistentData.putInt(effectname, player.age)

        let offitem = player.getOffhandItem()
        if (offitem == 'waystones:warp_dust') {
            let viewVector = player.getViewVector(1.0);
            let normalizedVector = normalizeVector(viewVector);

            let count = offitem.count

            player.setPosition(player.x + normalizedVector.x * 100 * count, player.y, player.z + normalizedVector.z * 100 * count)
            offitem.shrink(count)
        } else {
            let level = player.getXpLevel()
            if (level < 2) {
                player.tell('经验不足')
                return
            }
            player.giveExperiencePoints(-10)


            let viewVector = player.getViewVector(1.0);
            let normalizedVector = normalizeVector(viewVector);

            player.teleportTo(player.level.getDimension(),
                player.x + normalizedVector.x * 16,
                player.y + normalizedVector.y * 16,
                player.z + normalizedVector.z * 16,
                player.yaw, player.pitch)
        }

    },
    //瞬移
    'teleport': function (event, player, effectLevel, item, effectname) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20) return
        player.persistentData.putInt(effectname, player.age)

        let offitem = player.getOffhandItem()
        if (offitem == 'waystones:warp_dust') {
            let viewVector = player.getViewVector(1.0);
            let normalizedVector = normalizeVector(viewVector);

            let count = offitem.count

            player.setPosition(player.x + normalizedVector.x * 100 * count, player.y, player.z + normalizedVector.z * 100 * count)
            offitem.shrink(count)
        } else {
            let level = player.getXpLevel()
            if (level < 2) {
                player.tell('经验不足')
                return
            }
            player.giveExperiencePoints(-10)
            player.sendData('teleport_effect')
        }

    },
    //遗魂头骨
    'remnant_skull': function (event, player, effectLevel, item, effectname) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 60 * 10) return
        player.persistentData.putInt(effectname, player.age)

        let offitem = player.getOffhandItem()
        let maxHealth = player.getMaxHealth()
        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        if (offitem == 'minecraft:sniffer_egg') {
            //创建实体
            let spawn_entity = player.level.createEntity('cataclysm:modern_remnant')
            spawn_entity.setPosition(player.x, player.y + 1, player.z)
            spawn_entity.mergeNbt({ Attributes: [{ Base: maxHealth, Name: "minecraft:generic.max_health" }, { Base: damageValue / 2, Name: "minecraft:generic.attack_damage" }] })
            //生成实体
            spawn_entity.spawn()
            spawn_entity.tame(player)
            player.swing()
            offitem.shrink(1)
        }
    },
    'default': function (event, player, effectLevel, item, effectname) {
        return
    }
}