import { EntityEquippableComponent, EntityHealthComponent, EquipmentSlot, Entity, ItemStack, world, system } from "@minecraft/server";
import { damageAOE, sprintCollision } from "./skills.js";

//技能物品

function applyStackedEffec(entity, effectType, defaultMaxLevel, effectLimits) {
    const currentEffect = entity.getEffect(effectType);
    let effectLevel = 0;

    if (currentEffect) {
        effectLevel = currentEffect.amplifier + 1;
    }

    let maxLevel = defaultMaxLevel;
    let hasValidTag = false;

    for (const [tag, limit] of Object.entries(effectLimits)) {
        if (entity.hasTag(tag)) {
            maxLevel = limit;
            hasValidTag = true;
        }
    }

    if (!hasValidTag) {
        entity.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"Equip Combat Suit to use this skill"}]}`);
        return;
    }

    if (effectLevel >= maxLevel) {
        effectLevel = maxLevel;
    }
    entity.runCommandAsync(`effect @s ${effectType} 999999999 ${effectLevel} true`);

    const formattedEffectName = effectType.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
    entity.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"${formattedEffectName} skill: +${effectLevel + 1} ${formattedEffectName}"}]}`);
}
function fDurability(itemStack, source) {
    const itemEnchantmentComp = itemStack.getComponent("minecraft:enchantable");
    const unbreakingLevel = itemEnchantmentComp?.getEnchantment("unbreaking")?.level ?? 0;

    const breakChance = 100 / (unbreakingLevel + 1);
    const randomizeChance = Math.random() * 100;

    if (breakChance < randomizeChance) return;

    const durabilityComp = itemStack.getComponent("durability");
    if (!durabilityComp) return;

    durabilityComp.damage += 1;

    const maxDurability = durabilityComp.maxDurability;
    const currentDamage = durabilityComp.damage;
    if (currentDamage >= maxDurability) {
        source.playSound('random.break', { pitch: 1, location: source.location, volume: 1 });
        const sourceEquippableComp = source.getComponent("equippable");
        if (sourceEquippableComp) {
            sourceEquippableComp.setEquipment("Mainhand", new ItemStack('minecraft:air', 1));
        }
    } else {
        const sourceEquippableComp = source.getComponent("equippable");
        if (sourceEquippableComp) {
            sourceEquippableComp.setEquipment("Mainhand", itemStack);
        }
    }
}

function moveForward(source) {
    const view = source.getViewDirection();
    source.applyKnockback(view.x, view.z, 0.8, 0.0);
}

function setsourceMovement(source, enabled) {
    const status = enabled ? "enabled" : "disabled";
    source.runCommandAsync(`inputpermission set @s movement ${status}`);
}
function setsourceCamera(source, enabled) {
    const status = enabled ? "enabled" : "disabled";
    source.runCommandAsync(`inputpermission set @s camera ${status}`);
}
function transferDurabilityAndEnchantments(oldItem, newItem) {
    const oldDurabilityComp = oldItem.getComponent("durability");
    if (oldDurabilityComp) {
        const newDurabilityComp = newItem.getComponent("durability");
        if (newDurabilityComp) {
            newDurabilityComp.damage = oldDurabilityComp.damage;
        }
    }

    const oldEnchantmentComp = oldItem.getComponent("minecraft:enchantments");
    if (oldEnchantmentComp) {
        const newEnchantmentComp = newItem.getComponent("minecraft:enchantments");
        if (newEnchantmentComp) {
            const enchantments = oldEnchantmentComp.enchantments;
            for (let enchantment of enchantments) {
                newEnchantmentComp.addEnchantment(enchantment);
            }
        }
    }
}
world.beforeEvents.worldInitialize.subscribe((data) => {
    const { itemComponentRegistry } = data
    itemComponentRegistry.registerCustomComponent("pm_m8:mode_switch", {
        onUse: (data) => {
            const { source } = data;

            const inventory = source.getComponent("minecraft:inventory").container;

            for (let i = 0; i < 36; i++) {
                const slot = inventory.getSlot(i);
                const currentItem = slot.getItem();

                if (!currentItem) continue;
                if (currentItem.typeId === "pm_m8:sword_gun_combination") {
                    const newItem = new ItemStack("pm_m8:sword_gun_combination1", 1);
                    transferDurabilityAndEnchantments(currentItem, newItem);
                    slot.setItem(newItem);
                    source.runCommandAsync(`title @s actionbar Switch to Blaster Mode`);
                    return;
                }
                if (currentItem.typeId === "pm_m8:sword_gun_combination1") {
                    const newItem = new ItemStack("pm_m8:sword_gun_combination", 1);
                    transferDurabilityAndEnchantments(currentItem, newItem);
                    slot.setItem(newItem);
                    source.runCommandAsync(`title @s actionbar Switch to Sword Mode`);
                    return;
                }
            }

            source.runCommandAsync("title @s actionbar No Sword-Blaster Combination found in inventory.");
        }
    });

    itemComponentRegistry.registerCustomComponent("pm_m8:battle_hardened", {
        onUse: (data) => {
            const { source } = data


            if (source.hasTag(`pyroclasm`)) {
                source.runCommandAsync('effect @s strength 180 0 true');
                source.runCommandAsync('title @s actionbar Battle Hardened Activated : +Strength 1');

                system.runTimeout(() => {
                    source.runCommandAsync('effect @s strength 180 1 true');
                    source.runCommandAsync('title @s actionbar Battle Hardened Activated : +Strength 2');
                }, 180 * 20);
                /* system.runTimeout(() => {
                    source.runCommandAsync('effect @s strength 180 2 true');
                    source.runCommandAsync('title @s actionbar Battle Hardened Activated : +Strength 3');
                }, 360 * 20); */
            } else source.runCommandAsync(`title @s actionbar Equip Pyroclasm Armor to use this skill`);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:strength", {
        onUse: (data) => {
            const { source } = data;

            const effectLimits = {
                "combat_uniform": 1,
                "juggernaut": 4,
                "cyclone_suit": 1,
                "inferno_exoskeleton": 1,
                "pyroclasm": 4
            };

            applyStackedEffec(source, "strength", 1, effectLimits);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:speed", {
        onUse: (data) => {
            const { source } = data;

            const effectLimits = {
                "combat_uniform": 2,
                "juggernaut": 2,
                "cyclone_suit": 4,
                "inferno_exoskeleton": 1,
                "pyroclasm": 2
            };

            applyStackedEffec(source, "speed", 1, effectLimits);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:regeneration", {
        onUse: (data) => {
            const { source } = data;

            const effectLimits = {
                "combat_uniform": 1,
                "juggernaut": 2,
                "cyclone_suit": 2,
                "inferno_exoskeleton": 4,
                "pyroclasm": 0
            };

            applyStackedEffec(source, "regeneration", 1, effectLimits);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:jump_boost1", {
        onUse: (data) => {
            const { source } = data;

            const effectLimits = {
                "combat_uniform": 2,
                "juggernaut": 2,
                "cyclone_suit": 2,
                "inferno_exoskeleton": 1,
                "pyroclasm": 2
            };

            applyStackedEffec(source, "jump_boost", 1, effectLimits);
        }
    });

    //
    itemComponentRegistry.registerCustomComponent("pm_m8:frost", {
        onUse: (data) => {
            const { source } = data
            
            if (source.hasTag(`inferno_exoskeleton`)) {
                setsourceMovement(source, false);
                source.setProperty('pm_m8:froest', 1);
                source.runCommand('playanimation @s animation.pm_m8.combat_suit.froest ');

                system.runTimeout(() => {
                    source.runCommand('function pm_m8/froest');
                }, 0.8 * 20);

                system.runTimeout(() => {
                    setsourceMovement(source, true);
                    source.setProperty('pm_m8:froest', 0);
                }, 1.5 * 20);
            } else source.runCommandAsync(`title @s actionbar Equip Inferno Exoskeleton Armor to use this skill`);
        }
    });
    //
    itemComponentRegistry.registerCustomComponent("pm_m8:glide", {
        onUse: (data) => {
            const { source } = data

            if (source.hasTag(`cyclone_suit`)) {
                // source.runCommandAsync(`playanimation @s animation.pm_m8.combat_suit.glide default 0.2`);
                source.runCommandAsync(`effect @s slow_falling 20 0 true`);
                source.applyKnockback(0, 0, 0, 1);
                source.setProperty('pm_m8:glide', 1);
                const glide = system.runInterval(() => {
                    const view = source.getViewDirection();
                    source.applyKnockback(view.x, view.z, 1, view.y);

                    if (source.isOnGround == true) {
                        if (source.getProperty('pm_m8:glide') === 1) {
                            source.setProperty('pm_m8:glide', 0);
                            source.runCommandAsync(`effect @s slow_falling 0 255 true`);
                            source.runCommandAsync(`stopsound @a pm_m8:new_glide`);
                        }
                        system.clearRun(glide);
                    }

                    

                }, 2);
                
                system.runTimeout(() => {
                    if (source.getProperty('pm_m8:glide') === 1) {
                        source.setProperty('pm_m8:glide', 0);
                        // source.runCommandAsync(`effect @s slow_falling 0 255 true`);
                    }
                    system.clearRun(glide);
                }, 8 * 20);
            } else source.runCommandAsync(`title @s actionbar Equip Cyclone Suit to use this skill`);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:multiple_hits", {
        onUse: (data) => {
            const { source } = data


            if (source.hasTag(`pyroclasm`)) {
                //
            } else source.runCommandAsync(`title @s actionbar Equip Pyroclasm Armor to use this skill`);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:sprint_collision", {
        onUse: (data) => {
            const { source } = data

            if (source.hasTag(`cyclone_suit`) || source.hasTag(`juggernaut`)) {
                let isJumping = false; // 添加变量来标记玩家是否腾空
                source.runCommandAsync(`playanimation @s animation.pm_m8.combat_suit.sprint_collision default 0.2`);
                const sprintC = system.runInterval(() => {
                    const view = source.getViewDirection();
                    source.applyKnockback(view.x, view.z, 1, 0.0);
                    sprintCollision(source);

                    if (!source.isOnGround && !isJumping) {
                        // 如果玩家离地且isJumping为false，则设置isJumping为true，并把玩家向上击退
                        isJumping = true;
                        source.applyKnockback(view.x, view.z, 0.0, 0.6);
                    } else if (source.isOnGround && isJumping) {
                        // 如果玩家落地且isJumping为true，则设置isJumping为false
                        isJumping = false;
                    }

                    system.runTimeout(() => {
                        system.clearRun(sprintC);
                    }, 3 * 20);

                }, 2);
            } else source.runCommandAsync(`title @s actionbar Equip Cyclone or Juggernaut Armor to use this skill`);
            
        }
    });
    //
    itemComponentRegistry.registerCustomComponent("pm_m8:axe", {
        onUse: (data) => {
            const { source } = data
            setsourceMovement(source, false);

            system.runTimeout(() => {
                source.runCommand('function pm_m8/axe');
            }, 0.44 * 20);

            system.runTimeout(() => {
                setsourceMovement(source, true);
            }, 0.8 * 20);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:transformation", {
        onUse: (data) => {
            const { source } = data

            if (!source.hasTag('pm_m8:monster_8')) {
                setsourceMovement(source, false);
                source.runCommand('event entity @s start_shapeshifting');
                source.runCommand('event entity @s pm_m8:monster_8');
                source.runCommand(`playsound pm_m8:monster_no_8_transformaton @s ~~~`);
                
                
                source.runCommand('tag @s add pm_m8:monster_8');
                // source.runCommand('playanimation @s animation.pixelmind_m8.monster_no.8.shapeshift_tpp default 0.0');
                
                source.runCommand('give @s[hasitem=[{item=pm_m8:titan_fist,quantity=0}]] pm_m8:titan_fist 1 0 {"minecraft:item_lock":{ "mode": "lock_in_inventory" },"minecraft:keep_on_death":{}}');
                source.runCommand('effect @s strength 999999999 0 true');
                source.runCommand('effect @s speed 999999999 0 true');
                source.runCommand('effect @s fire_resistance 999999999 0 true');
                source.runCommand('effect @s jump_boost 999999999 0 true');
                source.runCommand('effect @s fire_resistance 999999999 0 true');
                source.runCommand('effect @s regeneration 999999999 0 true');
                system.runTimeout(() => {
                    setsourceMovement(source, true);
                    source.runCommand('event entity @s stop_shapeshifting');
                }, 2.5 * 20);
            } else if (source.hasTag('pm_m8:monster_8')) {
                source.runCommand('effect @s clear');
                source.runCommand('event entity @s pm_m8:player');
                source.runCommand('tag @s remove pm_m8:monster_8');
                source.runCommand('tag @s remove pm_m8:knockback_enhancement');
            }
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:monster_core", {
        onUse: (data) => {
            const { source } = data

            if (source.hasTag(`pm_m8:monster_8`)) {
                source.runCommand(`clear @s pm_m8:monster_core 0 1`);
                source.runCommand('function pm_m8/m8effects');
                source.runCommand('effect @s instant_health 5 0 true');
                source.runCommand('effect @s saturation 10 0 true');
                source.runCommand('playsound random.burp @a ~~~');
            } else source.runCommand(`title @s actionbar Consume only as Titan Eight`);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:biological_essence", {
        onUse: (data) => {
            const { source } = data

            if (source.hasTag(`pm_m8:monster_8`)) {
                source.runCommand(`clear @s pm_m8:biological_essence 0 1`);
                source.runCommand('function pm_m8/m8effects');
                source.runCommand('effect @s regeneration 10 0 true');
                source.runCommand('playsound random.burp @a ~~~');
            } else source.runCommand(`title @s actionbar Consume only as Titan Eight`);
        }
    });

    itemComponentRegistry.registerCustomComponent("pm_m8:health_core", {    //人类可食用的物品
        onUse: (data) => {
            const { source } = data

            if (!source.hasTag(`pm_m8:monster_8`)) {
                source.runCommand(`clear @s pm_m8:health_core 0 1`);
                source.runCommand('effect @s instant_health 3 0 true');
                source.runCommand('effect @s saturation 10 0 true');
                source.runCommand('playsound random.burp @a ~~~');
            } else source.runCommand(`title @s actionbar Consume only as Human`);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:regenerative_essence", {
        onUse: (data) => {
            const { source } = data

            if (!source.hasTag(`pm_m8:monster_8`)) {
                source.runCommand(`clear @s pm_m8:regenerative_essence 0 1`);
                source.runCommand('effect @s regeneration 15 0 true');
                source.runCommand('playsound random.burp @a ~~~');
            } else source.runCommand(`title @s actionbar Consume only as Human`);
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:charged_punch", {  //m8的拳击
        onUse: (data) => {
            const { source } = data

            if (source.hasTag(`pm_m8:monster_8`)) {
                setsourceMovement(source, false);
                source.runCommand(`tag @s add pm_m8:charged_attack`);
                
                setsourceMovement(source, false);

                system.runTimeout(() => {
                    damageAOE(source, "pm_m8:charged_attack", 30, 6, 3, 0.5);
                    source.runCommand('camerashake add @a[r=5] 0.2 0.4 positional');
                    source.runCommand(`playsound pm_m8:monster_no_8_charged_punch @s ~~~`);
                }, 0.55 * 20);

                system.runTimeout(() => {
                    setsourceMovement(source, true);
                }, 1.2 * 20);
            } else source.runCommand(`title @s actionbar Only works on Titan Eight`);

        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:titan_fist", {  //m8的拳击
        onUse: (data) => {
            const { source } = data

            if (source.hasTag(`pm_m8:monster_8`)) {
                source.setProperty('pm_m8:titan_fist', 1);
                system.runTimeout(() => {
                    source.setProperty('pm_m8:titan_fist', 0);
                    source.runCommand(`execute positioned ^ ^1 ^2 run damage @e[family=!player,r=3,type=!item,family=!npc,family=!tool,family=!inanimate] 12 entity_attack entity @s`);

                }, 0.5 * 20);
            } else source.runCommand(`title @s actionbar Only works on Titan Eight`);

        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:charged_attack", {
        onUse: (data) => {
            const { source } = data

            if (source.hasTag(`juggernaut`)) {
                source.runCommand(`playanimation @s animation.pm_m8.monster_no.2.power_attack default 0.2`);
                source.runCommand(`tag @s add pm_m8:charged_attack`);
                source.runCommand(`playsound pm_m8:charged_attack @s ~~~`);
                setsourceMovement(source, false);

                system.runTimeout(() => {
                    damageAOE(source, "pm_m8:charged_attack", 10, 3, 3, 0.5);
                    source.runCommand('camerashake add @a[r=5] 0.2 0.4 positional');
                }, 0.45 * 20);

                system.runTimeout(() => {
                    setsourceMovement(source, true);
                    source.runCommand(`tag @s remove pm_m8:charged_attack`);
                }, 0.5 * 20);
            } else source.runCommand(`title @s actionbar Equip Juggernaut Armor to use this skill`);

        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:jump_act", {   //名字叫impact
        onUse: (data) => {
            const { source } = data
            if (source.hasTag(`pm_m8:monster_8`)) {
                source.runCommand(`camera @s set minecraft:third_person `);
                source.runCommand('event entity @s start_jump_acting');
                source.runCommand(`playsound pm_m8:monster_no_8_impact @s ~~~`);
                setsourceCamera(source, false);
                setsourceMovement(source, false);

                const view = source.getViewDirection()

                system.runTimeout(() => {
                    source.applyKnockback(view.x, view.z, 0, 3);
                }, 0.55 * 20);
                
                system.runTimeout(() => {
                    source.applyKnockback(view.x, view.z, 0, -8);
                }, 1.4 * 20);

                system.runTimeout(() => {
                    source.runCommand(`damage @e[r=8,type=!player,type=!item,family=!npc,family=!tool,family=!inanimate] 20 entity_attack entity @s`);
                    setsourceCamera(source, true);
                }, 1.9 * 20);

                system.runTimeout(() => {
                    setsourceCamera(source, true);
                    setsourceMovement(source, true);
                    source.runCommand(`camera @s clear`);
                    source.runCommand('event entity @s stop_jump_acting');
                }, 2.4 * 20);
            } else source.runCommand(`title @s actionbar Only works on Titan Eight`);
        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:movement_speed_boost", {
        onUse: (data) => {
            const { source } = data
            if (source.hasTag(`pm_m8:monster_8`)) {
                source.runCommand(`playsound pm_m8:monster_no_8_movement_speed_boost @s ~~~`);

                const speedEffect = source.getEffect('speed');
                const speedEffectAmplifier = speedEffect ? speedEffect.amplifier : 0;

                // 速度加成效果上限3
                const newAmplifier = Math.min(speedEffectAmplifier + 1, 2);

                system.runTimeout(() => {
                    source.runCommand(`title @s actionbar Movement Speed Boost is activated!`);
                    source.runCommand(`effect @s speed 99999 ${newAmplifier} true`);
                }, 0.0 * 20);


            } else source.runCommand(`title @s actionbar Only works on Titan Eight`);
        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:jump_boost_monster8", {
        onUse: (data) => {
            const { source } = data;
            if (source.hasTag(`pm_m8:monster_8`)) {
                source.runCommand(`playsound pm_m8:monster_no_8_jump_boost @s ~~~`);
    
                const jumpBoostEffect = source.getEffect('jump_boost');
                const jumpBoostEffectAmplifier = jumpBoostEffect ? jumpBoostEffect.amplifier : 0;
    
                // Ensure the amplifier does not exceed 2
                const newAmplifier = Math.min(jumpBoostEffectAmplifier + 1, 2);
    
                system.runTimeout(() => {
                    // source.runCommand(`title @s actionbar Jump Boost Activate!`);
                    source.runCommand(`effect @s jump_boost 99999 ${newAmplifier} true`);
                }, 0.0 * 20);
            } else {
                source.runCommand(`title @s actionbar Only works on Titan Eight`);
            }
        }
    });
    itemComponentRegistry.registerCustomComponent("pm_m8:ultimate", {   //uppercut
        onUse: (data) => {
            const { source } = data
            if (source.hasTag(`pm_m8:monster_8`)) {
                
                // 大招，4.0秒自己和目标全部击飞，然后5.3秒再次击飞);
                source.runCommand(`camera @s set minecraft:third_person `);
                source.runCommand('event entity @s start_ultimating');
                // source.runCommand(`playsound pm_m8:monster_no_8_uppercut @s ~~~`);
                setsourceCamera(source, false);
                setsourceMovement(source, false);

                const view = source.getViewDirection();

                system.runTimeout(() => {
                    source.runCommand('damage @e[r=8,type=!player,type=!item,family=!npc,family=!tool,family=!inanimate] 10 entity_attack entity @s');
                    source.runCommand('effect @e[r=8,type=!player] slowness 6 255 true');
                    
                }, 0.58 * 20);

                system.runTimeout(() => {
                    source.runCommand(`camera @s set minecraft:free pos ^ ^4 ^1 facing ~ ~2 ~`);
                    
                }, 1.0 * 20);

                system.runTimeout(() => {
                    source.runCommand(`camera @s set minecraft:free pos ^-2 ^0.5 ^ facing @s`);
                    
                }, 2.7 * 20);

                system.runTimeout(() => {
                    source.runCommand(`camera @s set minecraft:third_person `);
                    
                    source.applyKnockback(view.x, view.z, 0, 2.8);
                    
                    const aroundEntities = source.dimension.getEntities(entityQueryOptionCreator(source, 8));
                    if (aroundEntities && aroundEntities.length > 0) {
                        aroundEntities.forEach(ele => {
                            try {
                                ele.applyKnockback(view.x, view.z, 0, 3.5);
                            } catch (error) {
                                console.error('Failed to apply knockback on entity:', error);
                            }
                        });
                    }
                    // source.runCommand('damage @e[r=6,type=!player,type=!item,family=!npc,family=!tool,family=!inanimate] 5 entity_attack entity @s');
                }, 4.0 * 20);

                

                system.runTimeout(() => {
                    source.applyKnockback(view.x, view.z, 3, 0);
                    const aroundEntities = source.dimension.getEntities(entityQueryOptionCreator(source, 8));
                    if (aroundEntities && aroundEntities.length > 0) {
                        aroundEntities.forEach(ele => {
                            try {
                                ele.applyKnockback(view.x, view.z, 3, 0);
                            } catch (error) {
                                console.error('Failed to apply knockback on entity:', error);
                            }
                        });
                    }
                    source.runCommand('damage @e[r=8,type=!player,type=!item,family=!npc,family=!tool,family=!inanimate] 35 entity_attack entity @s');
                }, 4.75 * 20);

                system.runTimeout(() => {
                    source.applyKnockback(view.x, view.z, 0, -4);
                }, 5.3 * 20);

                


                system.runTimeout(() => {
                    setsourceMovement(source, true);
                    setsourceCamera(source, true);
                    source.runCommand(`camera @s clear`);
                    source.runCommand('event entity @s stop_ultimating');
                    
                }, 6.4 * 20);
                
            } else source.runCommand(`title @s actionbar Only works on Titan Eight`);
        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:roar_monster8", {
        onUse: (data) => {
            const { source } = data
            if (source.hasTag(`pm_m8:monster_8`)) {
                
                source.runCommand(`camera @s set minecraft:third_person_front `);
                source.runCommand('event entity @s start_roaring');
                source.runCommand(`playsound pm_m8:monster_no_8_roar @s ~~~`);
                setsourceCamera(source, false);
                setsourceMovement(source, false);

                const view = source.getViewDirection();

                system.runTimeout(() => {
                    setsourceCamera(source, true);
                    source.runCommand(`camera @s set minecraft:third_person `);
                }, 1.5 * 20);

                system.runTimeout(() => {
                    source.runCommand('event entity @s start_roaring_damage');
                    
                }, 2.0 * 20);

                system.runTimeout(() => {
                    source.runCommand('event entity @s stop_roaring');
                    
                }, 6.0 * 20);

                system.runTimeout(() => {
                    setsourceMovement(source, true);
                    setsourceCamera(source, true);
                    source.runCommand(`camera @s clear`);
                }, 6.5 * 20);
                
            } else source.runCommand(`title @s actionbar Only works on Titan Eight`);
        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:continuous_strike", {
        onUse: (data) => {
            const { source } = data
            if (source.hasTag(`pm_m8:monster_8`)) {
                setsourceMovement(source, false);
                system.runTimeout(() => {
                    source.runCommand(`playsound pm_m8:monster_no_8_continious_strike @s ~~~`);
                }, 0.1 * 20);
                

                system.runTimeout(() => {
                    source.runCommand('function pm_m8/continuous_strike');
                }, 0.5 * 20);

                system.runTimeout(() => {
                    source.runCommand('function pm_m8/continuous_strike');
                }, 0.75 * 20);

                system.runTimeout(() => {
                    source.runCommand('function pm_m8/continuous_strike');
                }, 1 * 20);

                system.runTimeout(() => {
                    source.runCommand('function pm_m8/continuous_strike');
                }, 1.25 * 20);

                system.runTimeout(() => {
                    source.runCommand('function pm_m8/continuous_strike');
                    // source.runCommand(`camera @s clear`);
                }, 1.5 * 20);

                system.runTimeout(() => {
                    setsourceMovement(source, true);
                    
                }, 2 * 20);
            } else source.runCommand(`title @s actionbar Only works on Titan Eight`);
        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:dual_swords", {
        onUse: (data) => {
            const { source } = data
            setsourceMovement(source, false);

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/dual_swords');
                moveForward(source);
            }, 0.38 * 20);

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/dual_swords');
                moveForward(source);
            }, 0.67 * 20);

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/dual_swords');
                moveForward(source);
            }, 1.08 * 20);

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/dual_swords');
                moveForward(source);
            }, 1.46 * 20);

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/dual_swords2');
                const view = source.getViewDirection();
                source.applyKnockback(view.x, view.z, 3, 0.0);
            }, 1.79 * 20);

            system.runTimeout(() => {
                setsourceMovement(source, true);
            }, 2 * 20);
        }
    })
    // itemComponentRegistry.registerCustomComponent("pm_m8:bomb_gun", {
    //     onUse: (data) => {
    //         const { source } = data
    //         const dimension = source.dimension;
    //         setsourceMovement(source, false);

    //         system.runTimeout(() => {
    //             const viewDirection = source.getViewDirection();
    //             const spawnLocation = {
    //                 x: source.location.x + viewDirection.x,
    //                 y: source.location.y + viewDirection.y + 1.8,
    //                 z: source.location.z + viewDirection.z
    //             };

    //             let shootentity = dimension.spawnEntity("pm_m8:bomb_gun_projectile", spawnLocation);

    //             let shootProjectileComp = shootentity.getComponent('minecraft:projectile');
    //             shootProjectileComp.owner = source;

    //             const shootingSpeed = 6;
    //             let velocity = {
    //                 x: viewDirection.x * shootingSpeed,
    //                 y: viewDirection.y * shootingSpeed,
    //                 z: viewDirection.z * shootingSpeed
    //             };

    //             shootProjectileComp.shoot(velocity);
    //         }, 0.25 * 20);

    //         system.runTimeout(() => {
    //             setsourceMovement(source, true);
    //         }, 0.8 * 20);
    //     }
    // })
    itemComponentRegistry.registerCustomComponent("pm_m8:chainsaw_axe", {
        onUse: (data) => {
            const { source } = data

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/chainsaw_axe');
            }, 0.42 * 20);
        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:chainsaw_sword", {
        onUse: (data) => {
            const { source } = data

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/chainsaw_sword');
            }, 0.46 * 20);

        }
    })
    itemComponentRegistry.registerCustomComponent("pm_m8:energy_sword", {
        onUse: (data) => {
            const { source } = data

            system.runTimeout(() => {
                source.runCommandAsync('function pm_m8/energy_sword');
            }, 0.52 * 20);
        }
    })
})


function entityQueryOptionCreator(entity, distance){
    return {
        location: entity.location,
        maxDistance: distance,
        excludeTypes: ["minecraft:item"],
        excludeFamilies: [ "npc", "tool", "inanimate" ],
    }
}

