import { world,  system } from '@minecraft/server';


system.runInterval(js7_skeleton_armor_set, 19); 
system.runInterval(js7_wither_skeleton_armor_set, 19);
system.runInterval(js7_stray_armor_set, 19); 
system.runInterval(js7_bogged_armor_set, 19); 
// near 1 second

system.runInterval(js7_wither_skeleton_special_armor_set, 1);
system.runInterval(js7_stray_special_armor_set, 1); 
system.runInterval(js7_bogged_special_armor_set, 1); 
// instant

function js7_skeleton_armor_set() {
    const players = world.getPlayers();
    for (const player of players) {
        const equipment = player.getComponent("equippable");
     
        if (equipment == null) {
           
            continue;
        }
        const headEquipment = equipment.getEquipment("Head");
        const chestEquipment = equipment.getEquipment("Chest");
        const legsEquipment = equipment.getEquipment("Legs");
        const feetEquipment = equipment.getEquipment("Feet");
        
        const hasLegsEquipment = legsEquipment?.typeId === "mutant:mutant_skeleton_leggings"; 
        const hasFeetEquipment = feetEquipment?.typeId === "mutant:mutant_skeleton_boots"; 
        
        if (hasFeetEquipment)
        player.runCommandAsync(`effect @s jump_boost 5 1 true`);

        if (hasLegsEquipment)
        player.runCommandAsync(`effect @s speed 5 1 true`);
    }
}
function js7_wither_skeleton_armor_set() {
    const players = world.getPlayers();
    for (const player of players) {
        const equipment = player.getComponent("equippable");
     
        if (equipment == null) {
           
            continue;
        }
        const headEquipment = equipment.getEquipment("Head");
        const chestEquipment = equipment.getEquipment("Chest");
        const legsEquipment = equipment.getEquipment("Legs");
        const feetEquipment = equipment.getEquipment("Feet");
        
        const hasHeadEquipment = headEquipment?.typeId === "mutant:mutant_wither_skeleton_helmet"; 
        const hasChestEquipment = chestEquipment?.typeId === "mutant:mutant_wither_skeleton_chestplate"; 
        const hasLegsEquipment = legsEquipment?.typeId === "mutant:mutant_wither_skeleton_leggings"; 
        const hasFeetEquipment = feetEquipment?.typeId === "mutant:mutant_wither_skeleton_boots"; 
        
        if (hasFeetEquipment && hasLegsEquipment && hasChestEquipment && hasHeadEquipment){
            player.runCommandAsync(`effect @s fire_resistance 5 0 true`);
           
            player.runCommandAsync(`effect @s clear wither`);
            }
        if (hasChestEquipment)
            player.runCommandAsync(`effect @s resistance 5 2 true`);
        if (hasLegsEquipment)
        player.runCommandAsync(`effect @s speed 5 0 true`);
    }
}
function js7_wither_skeleton_special_armor_set() {
    const players = world.getPlayers();
    for (const player of players) {
        const equipment = player.getComponent("equippable");
     
        if (equipment == null) {
           
            continue;
        }
        const headEquipment = equipment.getEquipment("Head");
        const chestEquipment = equipment.getEquipment("Chest");
        const legsEquipment = equipment.getEquipment("Legs");
        const feetEquipment = equipment.getEquipment("Feet");
        
        const hasHeadEquipment = headEquipment?.typeId === "mutant:mutant_wither_skeleton_helmet"; 
        const hasChestEquipment = chestEquipment?.typeId === "mutant:mutant_wither_skeleton_chestplate"; 
        const hasLegsEquipment = legsEquipment?.typeId === "mutant:mutant_wither_skeleton_leggings"; 
        const hasFeetEquipment = feetEquipment?.typeId === "mutant:mutant_wither_skeleton_boots"; 
        
        if (hasFeetEquipment && hasLegsEquipment && hasChestEquipment && hasHeadEquipment){
       
        player.runCommandAsync(`effect @s clear wither`);
        }
    }
}

function js7_stray_armor_set() {
    const players = world.getPlayers();
    for (const player of players) {
        const equipment = player.getComponent("equippable");
     
        if (equipment == null) {
           
            continue;
        }
        const headEquipment = equipment.getEquipment("Head");
        const chestEquipment = equipment.getEquipment("Chest");
        const legsEquipment = equipment.getEquipment("Legs");
        const feetEquipment = equipment.getEquipment("Feet");
        
        const hasHeadEquipment = headEquipment?.typeId === "mutant:mutant_stray_helmet"; 
        const hasChestEquipment = chestEquipment?.typeId === "mutant:mutant_stray_chestplate"; 
        const hasLegsEquipment = legsEquipment?.typeId === "mutant:mutant_stray_leggings"; 
        const hasFeetEquipment = feetEquipment?.typeId === "mutant:mutant_stray_boots"; 
        
        if (hasFeetEquipment && hasLegsEquipment && hasChestEquipment && hasHeadEquipment){
         player.runCommandAsync(`effect @s strength 5 1 true`);
        player.runCommandAsync(`effect @s clear slowness`);
        }
        if (hasChestEquipment)
            player.runCommandAsync(`effect @s haste 5 1 true`);
        if (hasFeetEquipment)
        player.runCommandAsync(`effect @s jump_boost 5 2 true`);
    }
}
function js7_stray_special_armor_set() {
    const players = world.getPlayers();
    for (const player of players) {
        const equipment = player.getComponent("equippable");
     
        if (equipment == null) {
           
            continue;
        }
        const headEquipment = equipment.getEquipment("Head");
        const chestEquipment = equipment.getEquipment("Chest");
        const legsEquipment = equipment.getEquipment("Legs");
        const feetEquipment = equipment.getEquipment("Feet");
        
        const hasHeadEquipment = headEquipment?.typeId === "mutant:mutant_stray_helmet"; 
        const hasChestEquipment = chestEquipment?.typeId === "mutant:mutant_stray_chestplate"; 
        const hasLegsEquipment = legsEquipment?.typeId === "mutant:mutant_stray_leggings"; 
        const hasFeetEquipment = feetEquipment?.typeId === "mutant:mutant_stray_boots"; 
        
        if (hasFeetEquipment && hasLegsEquipment && hasChestEquipment && hasHeadEquipment){
        player.runCommandAsync(`effect @s clear slowness`);
        }
    }
}

function js7_bogged_armor_set() {
    const players = world.getPlayers();
    for (const player of players) {
        const equipment = player.getComponent("equippable");
     
        if (equipment == null) {
           
            continue;
        }
        const headEquipment = equipment.getEquipment("Head");
        const chestEquipment = equipment.getEquipment("Chest");
        const legsEquipment = equipment.getEquipment("Legs");
        const feetEquipment = equipment.getEquipment("Feet");
        
        const hasHeadEquipment = headEquipment?.typeId === "mutant:mutant_bogged_helmet"; 
        const hasChestEquipment = chestEquipment?.typeId === "mutant:mutant_bogged_chestplate"; 
        const hasLegsEquipment = legsEquipment?.typeId === "mutant:mutant_bogged_leggings"; 
        const hasFeetEquipment = feetEquipment?.typeId === "mutant:mutant_bogged_boots"; 

        if (hasFeetEquipment && hasLegsEquipment && hasChestEquipment && hasHeadEquipment){
            
            player.runCommandAsync(`effect @s conduit_power 11 0 true`);
           player.runCommandAsync(`effect @s clear poison`);
           player.runCommandAsync(`effect @s clear fatal_poison`);
           }
        if (hasChestEquipment)
            player.runCommandAsync(`effect @s health_boost 5 2 true`);
        if (hasFeetEquipment)
        player.runCommandAsync(`effect @s jump_boost 5 0 true`);
    }
}
function js7_bogged_special_armor_set() {
    const players = world.getPlayers();
    for (const player of players) {
        const equipment = player.getComponent("equippable");
     
        if (equipment == null) {
           
            continue;
        }
        const headEquipment = equipment.getEquipment("Head");
        const chestEquipment = equipment.getEquipment("Chest");
        const legsEquipment = equipment.getEquipment("Legs");
        const feetEquipment = equipment.getEquipment("Feet");
        
        const hasHeadEquipment = headEquipment?.typeId === "mutant:mutant_bogged_helmet"; 
        const hasChestEquipment = chestEquipment?.typeId === "mutant:mutant_bogged_chestplate"; 
        const hasLegsEquipment = legsEquipment?.typeId === "mutant:mutant_bogged_leggings"; 
        const hasFeetEquipment = feetEquipment?.typeId === "mutant:mutant_bogged_boots"; 

        if (hasFeetEquipment && hasLegsEquipment && hasChestEquipment && hasHeadEquipment){
            
         player.runCommandAsync(`effect @s conduit_power 11 0 true`);
        player.runCommandAsync(`effect @s clear poison`);
        player.runCommandAsync(`effect @s clear fatal_poison`);
        }
    }
}

world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:arrow") {
            const entity_range = entity.location;
            switch (eventId) {
                case "near_entity":    
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:arrow","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });
                    try {
                        for (const entityIn of entitiesIn) {
                            const direction = entity.getViewDirection();
                            const direction_x = direction.x;
                            const direction_z = direction.z;
                            // Adjust the vertical impulse value to have a stronger effect
                            const verticalImpulse = 0.3; // Adjust this value as needed
    
                            if (entityIn.typeId === "minecraft:player") {
                                entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.3, 0.6);
                            } else {
                                entityIn.applyImpulse({
                                    x: 0.0 * direction_x, // Keep the horizontal direction
                                    y: verticalImpulse,     // Stronger vertical impulse
                                    z: 0.0 * direction_z    // Keep the horizontal direction
                                });
                            }
                        }
                    } catch (error) {
                    }
                  
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});

world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
                case "zombie_damage":
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_zombie","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
                case "husk_damage":
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_husk","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
            
                case "bouldering_zombie_damage":
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_bouldering_zombie","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
           
                case "lobber_zombie_damage":
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_lobber_zombie","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
            
                case "drowned_damage":
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_drowned","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
                case "villager_damage":
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_villager","mutant:mutant_iron_golem","minecraft:iron_golem","minecraft:villager","minecraft:villager_2","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate","villager","irongolem"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
            
                case "zombie_villager_damage":
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_zombie_villager","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
                case "vindicator_damage":      
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_vindicator","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate", "vindicator","illager","vex"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});
world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
                case "piglin_brute_damage":    
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_piglin_brute","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.2; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});

world.afterEvents.dataDrivenEntityTrigger.subscribe(e => {
    try {
        const entity = e.entity;
        const eventId = e.eventId;

        if (entity.typeId === "mutant:smash_attack") {
            const entity_range = entity.location;
            switch (eventId) {
                case "piglin_brute_damage":    
                    let entitiesIn = entity.dimension.getEntities({
                        excludeTypes: ["mutant:smash_attack","mutant:mutant_piglin_brute","mutant:mutant_piglin","minecraft:piglin_brute","minecraft:piglin","item","xp_orb","lightning_bolt","evocation_fang","tnt","arrow"],
                        excludeFamilies: ["inanimate"],
                        location: entity_range,
                        minDistance: 0.0,
                        maxDistance: 2.0
                    });

                    for (const entityIn of entitiesIn) {
                        const direction = entity.getViewDirection();
                        const direction_x = direction.x;
                        const direction_z = direction.z;
                        entityIn.applyDamage(12,{cause:"contact"});
                        // Adjust the vertical impulse value to have a stronger effect
                        const verticalImpulse = 0.1; // Adjust this value as needed

                        if (entityIn.typeId === "minecraft:player") {
                            entityIn.applyKnockback(0 * direction_x, 0 * direction_z, 0.5, 0.6);
                        } else {
                            entityIn.applyImpulse({
                                x: 0.0 * direction_x, // Keep the horizontal direction
                                y: verticalImpulse,     // Stronger vertical impulse
                                z: 0.0 * direction_z    // Keep the horizontal direction
                            });
                        }
                    }
                    break;

                default:
                    break;
            }
        }
    } catch (error) {
        console.error("Error processing data-driven entity trigger: ", error);
    } finally {
        // Cleanup if needed
    }
});

world.afterEvents.dataDrivenEntityTrigger.subscribe(e=>{
    try{
      const entity=e.entity;
      const eventId=e.eventId;
      if(entity.typeId==="mutant:mutant_wither_skeleton"){
        const entity_range=entity.location;
        switch(eventId){
    
          case "melee_knockback_attack":
          let entitiesIn=entity.dimension.getEntities({excludeTypes:["mutant:mutant_wither_skeleton"],excludeFamilies:["inanimate"],location:entity_range,minDistance:0.0,maxDistance:4.0});
          for(const entityIn of entitiesIn){
              entityIn.applyDamage(6,{cause:"contact",damagingEntity:(entity ?? null)});
              const direction = entity.getViewDirection();
              const direction_x = direction.x;
              const direction_z = direction.z;
              const verticalImpulse = 0.2;

              if(entityIn.typeId==="minecraft:player"){
                entityIn.applyKnockback(15 * direction_x,15 * direction_z,0.75,0.4);
              }
              else{
                entityIn.applyImpulse({ x: 0.5 * direction_x, y: 0.35 * verticalImpulse, z: 0.5 * direction_z });
              }
            
          }
          break;
          default:
          break;
        }
      }
    }catch(error){}finally{}
  });

  world.afterEvents.entityHitEntity.subscribe(event => {
    try {
        const attacker = event.damagingEntity;
        const victim = event.hitEntity;

        if (!attacker || !victim) return; 

        if (attacker.typeId === "mutant:mutant_pillager") {
            const entity_range = victim.location;
            const victimDimension = victim.dimension;
            let entitiesIn = victimDimension.getEntities({
                excludeTypes: ["mutant:mutant_pillager"],
                excludeFamilies: ["inanimate"],
                location: entity_range,
                minDistance: 0.0,
                maxDistance: 2.0
            });

            for (const entityIn of entitiesIn) {
                entityIn.applyDamage(6, { cause: "contact", damagingEntity: attacker });
                const direction = attacker.getViewDirection();
                const direction_x = direction.x;
                const direction_z = direction.z;
                const verticalImpulse = 0.2;
                if (entityIn.typeId === "minecraft:player") {
                    entityIn.applyKnockback(15 * direction_x, 15 * direction_z, 3, 0.75);
                } else {
                    entityIn.applyImpulse({ x: 1.75 * direction_x, y: 1.5 * verticalImpulse, z: 1.75 * direction_z });
                }
            }
        }
    }catch(error){}finally{}
});

  world.afterEvents.entityHitEntity.subscribe(e=>{
    try{
      const attacker=e.damagingEntity;
      const attackerId=attacker.typeId;
      const victim=e.hitEntity;
      const victimId=victim.typeId;
      if(attackerId==="mutant:mutant_creeper"){
        if(victimId==="minecraft:player"){
            const viewDirection = attacker.getViewDirection();
          victim.applyKnockback(15 * viewDirection.x,15 * viewDirection.z,0.75,0.4);
        }
        else{
            const viewDirection = attacker.getViewDirection();
            victim.applyImpulse({ x: 0.5 * viewDirection.x, y: 0.25, z: 0.5 * viewDirection.z });
        }
      }
    }catch(error){}finally{}
  });
 
  world.afterEvents.entityHitEntity.subscribe(e=>{
    try{
      const attacker=e.damagingEntity;
      const attackerId=attacker.typeId;
      const victim=e.hitEntity;
      const victimId=victim.typeId;
      if(attackerId==="mutant:mutant_villager"){
        if(victimId==="minecraft:player"){
            const viewDirection = attacker.getViewDirection();
          victim.applyKnockback(10 * viewDirection.x,10 * viewDirection.z,1.25,0.25);
        }
        else{
            const viewDirection = attacker.getViewDirection();
            victim.applyImpulse({ x: 0.5 * viewDirection.x, y: 0.075, z: 0.5 * viewDirection.z });
        }
      }
    }catch(error){}finally{}
  });
   
  world.afterEvents.entityHitEntity.subscribe(e=>{
    try{
      const attacker=e.damagingEntity;
      const attackerId=attacker.typeId;
      const victim=e.hitEntity;
      const victimId=victim.typeId;
      if(attackerId==="mutant:mutated_evoker_fangs"){
        if(victimId==="minecraft:player"){
            const viewDirection = attacker.getViewDirection();
          victim.applyKnockback(10 * viewDirection.x,10 * viewDirection.z,1.25,0.25);
        }
        else{
            const viewDirection = attacker.getViewDirection();
            victim.applyImpulse({ x: 0.5 * viewDirection.x, y: 0.075, z: 0.5 * viewDirection.z });
        }
      }
    }catch(error){}finally{}
  });
     
  world.afterEvents.entityHitEntity.subscribe(e=>{
    try{
      const attacker=e.damagingEntity;
      const attackerId=attacker.typeId;
      const victim=e.hitEntity;
      const victimId=victim.typeId;
      if(attackerId==="mutant:mutant_enderman"){
        if(victimId==="minecraft:player"){
            const viewDirection = attacker.getViewDirection();
          victim.applyKnockback(10 * viewDirection.x,10 * viewDirection.z,1.25,0.25);
        }
        else{
            const viewDirection = attacker.getViewDirection();
            victim.applyImpulse({ x: 0.5 * viewDirection.x, y: 0.075, z: 0.5 * viewDirection.z });
        }
      }
    }catch(error){}finally{}
  });
  
  const mobConfigs = {
    "mutant:smash_attack": {
        typeId: "mutant:smash_attack",
        impulseY: 0.5,
        knockbackHorizontal: 1,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutated_evoker_fangs": {
        typeId: "mutant:mutated_evoker_fangs",
        impulseY: 0.85,
        knockbackHorizontal: 0.5,
        knockbackVertical: 0.85,
        randomKnockback: false,
    },
    "mutant:mutant_iron_golem": {
        typeId: "mutant:mutant_iron_golem",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_villager": {
        typeId: "mutant:mutant_villager",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_vindicator": {
        typeId: "mutant:mutant_vindicator",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_evoker": {
        typeId: "mutant:mutant_evoker",
        impulseY: 0.5,
        knockbackHorizontal: 6,
        knockbackVertical: 0.75,
        randomKnockback: false,
    },
  
    "mutant:mutant_zombie": {
        typeId: "mutant:mutant_zombie",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_husk": {
        typeId: "mutant:mutant_husk",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_drowned": {
        typeId: "mutant:mutant_drowned",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_zombie_villager": {
        typeId: "mutant:mutant_zombie_villager",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_zombie_pigman": {
        typeId: "mutant:mutant_zombie_pigman",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_zombified_piglin": {
        typeId: "mutant:mutant_zombified_piglin",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_piglin": {
        typeId: "mutant:mutant_zombie_pigman",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_piglin_brute": {
        typeId: "mutant:mutant_zombified_piglin",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_skeleton": {
        typeId: "mutant:mutant_skeleton",
        impulseY: 0.5,
        knockbackHorizontal: 4,
        knockbackVertical: 0.5,
        randomKnockback: false,
    },
    "mutant:mutant_stray": {
        typeId: "mutant:mutant_stray",
        impulseY: 0.5,
        knockbackHorizontal: 4,
        knockbackVertical: 0.5,
        randomKnockback: false,
    },
    "mutant:mutant_wither_skeleton": {
        typeId: "mutant:mutant_wither_skeleton",
        impulseY: 0.5,
        knockbackHorizontal: 3,
        knockbackVertical: 0.25,
        randomKnockback: false,
    },
    "mutant:mutant_bogged": {
        typeId: "mutant:mutant_bogged",
        impulseY: 0.5,
        knockbackHorizontal: 4,
        knockbackVertical: 0.5,
        randomKnockback: false,
    },
};
  world.afterEvents.entityHurt.subscribe((event) => {
    const damagingEntity = event.damageSource.damagingEntity;
    const hurtEntity = event.hurtEntity;
    const hurtCause = "melee_knockback_attack"; // Replace with the actual cause value from the event

    // Early exit if entities are missing
    if (!damagingEntity || !hurtEntity)
        return;
    // Check if the entities are still valid
    if (!damagingEntity.isValid() || !hurtEntity.isValid()) {
        return;
    }
    // Define a set of valid entity types that support getViewDirection
    const validEntityTypes = new Set([
        "mutant:mutant_skeleton",
        "mutant:mutant_stray",
        "mutant:mutant_bogged",
        "mutant:mutant_wither_skeleton",

        "mutant:mutant_iron_golem",
        "mutant:mutant_villager",
        "mutant:mutant_vindicator",
        "mutant:mutant_evoker",

        "mutant:mutated_evoker_fangs",

        "mutant:mutant_zombie",
        "mutant:mutant_husk",
        "mutant:mutant_drowned",
        "mutant:mutant_zombie_villager",
        "mutant:mutant_zombie_pigman",
        "mutant:mutant_zombified_piglin",
     
        "mutant:mutant_piglin",
        "mutant:mutant_piglin_brute",
        // Add other entity types that should have getViewDirection
    ]);
    // Only proceed if the entity type is in the valid set
    if (!validEntityTypes.has(damagingEntity.typeId)) {
        return; // Exit if the entity type is not valid
    }
    // Get the view direction of the damaging entity
    const direction = damagingEntity.getViewDirection();
    const direction_x = direction.x;
    const direction_z = direction.z;
    const mobConfig = mobConfigs[damagingEntity.typeId];
    if (!mobConfig)
        return; // If mob is not configured, exit
    // Utility function to apply impulse or knockback
    function applyImpulseOrKnockback(entity, x, z, y, horizontal, vertical) {
       
        if (damagingEntity.hasTag("mutant_golem_attack_1")) {
            const variable_horizontal = 0; // Random value 0
            const variable_vertical = 1.75
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }
        if (damagingEntity.hasTag("mutant_golem_attack_2")) {
            const variable_horizontal = 1.25; // Random value 0
            const variable_vertical = 0.4
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }
        if (damagingEntity.hasTag("mutant_golem_attack_3")) {
            const variable_horizontal = 0.75; // Random value 0
            const variable_vertical = 1.0
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }

        if (damagingEntity.hasTag("mutant_spin_attacking")) {
            const variable_horizontal = 1.15; // Random value 0
            const variable_vertical = 0.25
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }
        if (damagingEntity.hasTag("mutant_roar_throw")) {
            const variable_horizontal = 0; // Random value 0
            const variable_vertical = 1.75
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }
        if (damagingEntity.hasTag("mutant_roar_smash")) {
            const variable_horizontal = 0; // Random value 0
            const variable_vertical = -1
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }
        if (damagingEntity.hasTag("mutant_melee_ribcage_attacking")) {
            const variable_horizontal = -3.5; // Random value 0
            const variable_vertical = 1.5
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }
        if (damagingEntity.hasTag("mutant_melee_skeleton_attacking")) {
            const variable_horizontal = 2.5; // Random value 0
            const variable_vertical = 0.4
            if (entity.typeId === "minecraft:player") {
             
                hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
            }
            else {
                hurtEntity.applyImpulse({ x: variable_horizontal * direction_x, y: variable_vertical, z: variable_horizontal * direction_z });
             
            }
          
        }
        if (damagingEntity.hasTag("mutated_fangs_breach_attacking")) {
            if (!entity.isValid()) {
                return;
            }
            if (entity.typeId === "minecraft:player") {
                entity.applyKnockback(x, z, horizontal, vertical);
            }
            else {
                entity.applyImpulse({ x, y, z });
            }
        }
        // Check if the entity is still valid
        if (damagingEntity.hasTag("mutant_melee_attacking")) {
        if (!entity.isValid()) {
            return;
        }
        if (entity.typeId === "minecraft:player") {
            entity.applyKnockback(x, z, horizontal, vertical);
        }
        else {
            entity.applyImpulse({ x, y, z });
        }
    }
}
    if (mobConfig.randomKnockback) {
        const variable_horizontal = Math.random() * (6.7 - 4.4) + 4.4; // Random value between 4.4 and 6.7
        const variable_vertical = Math.random() / 7; // Random value between 0 and 1
        hurtEntity.applyKnockback(direction_x, direction_z, variable_horizontal, variable_vertical);
        return;
    }
    if (mobConfig.radiusSquared !== undefined) {
        const position_of_mob = damagingEntity.location;
        const position_of_target = hurtEntity.location;
        // Calculate the distance in 3D space
        const deltaX = position_of_target.x - position_of_mob.x;
        const deltaY = position_of_target.y - position_of_mob.y;
        const deltaZ = position_of_target.z - position_of_mob.z;
        const distanceSquared = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
        // Check if the target is within the radius in 3D space
        if (distanceSquared <= mobConfig.radiusSquared) {
            applyImpulseOrKnockback(hurtEntity, direction_x, direction_z, mobConfig.impulseY, mobConfig.knockbackHorizontal, mobConfig.knockbackVertical);
        }
    }
    else {
        applyImpulseOrKnockback(hurtEntity, direction_x, direction_z, mobConfig.impulseY, mobConfig.knockbackHorizontal, mobConfig.knockbackVertical);
    }
});

world.beforeEvents.worldInitialize.subscribe(e => {
    e.itemComponentRegistry.registerCustomComponent("mutant_script:shard_durability", {onHitEntity: hit_event, onUse: use_creepershard_event, onBeforeDurabilityDamage: durability_damage_event});
});

function durability_damage_event(e) {
    // Cancel vanilla damage event
    e.durabilityDamage = 0;
}


function hit_event(e) {
    // Get data from event
    const source = e.attackingEntity;
    const itemStack = e.itemStack;

    // Get Damage
    const durabilityComponent = itemStack.getComponent('durability');
    const damage = durabilityComponent.damage;
    
    if (damage != 0) {
        durabilityComponent.damage = Math.max(damage - 1, 0);
        source.getComponent("equippable").setEquipment("Mainhand", itemStack);
       
    }
    else if (damage == 0) {
        source.sendMessage("This Creeper Shard is fully charged")
    }
  

  
}


function use_creepershard_event(e) {
    const player = e.source;
    const itemStack = e.itemStack;

    const durabilityComponent = itemStack.getComponent('durability');
    const damage = durabilityComponent.damage;

    const cooldown = 3 * 20; // 3 seconds

    if (damage == 0 && cooldowns.has(player)) {
        const lastUse = cooldowns.get(player);
        const currentTick = system.currentTick;

        if (currentTick - lastUse < cooldown) {
            player.sendMessage("Wait for 3 seconds");
            return;
        }
    }

    cooldowns.set(player, system.currentTick); 

    if (damage == 0) {
        player.runCommandAsync('replaceitem entity @s[m=!c] slot.weapon.mainhand 1 mutant:creeper_shard 1 35');
        const explosionLocation = { x: player.location.x, y: player.location.y + 1.675, z: player.location.z };
        player.addEffect("resistance", 1, { amplifier: 10 });
        player.addEffect("slow_falling", 1, { amplifier: 10 });
        player.dimension.createExplosion(explosionLocation, 7, { breaksBlocks: true });
    } 
    else if (damage >= 30) {
        player.sendMessage("This Creeper Shard must be charged");
    } 
    else if (damage >= 18) {
        player.sendMessage("This Creeper Shard is 25% charged");
    } 
    else if (damage >= 11) {
        player.sendMessage("This Creeper Shard is 50% charged");
    } 
    else if (damage >= 4) {
        player.sendMessage("This Creeper Shard is 75% charged");
    } 
    else if (damage >= 1) {
        player.sendMessage("This Creeper Shard is almost fully charged");
    }
}
world.beforeEvents.worldInitialize.subscribe(e => {
    e.itemComponentRegistry.registerCustomComponent("mutant_script:endersoul_teleport", { onUse: use_endersoul_teleport_event});
});
function use_endersoul_teleport_event(e) {
    const itemStack = e.itemStack;
    
    // Get Damage
    const durabilityComponent = itemStack.getComponent('durability');
    const damage = durabilityComponent.damage;
    
    const entity = e.source;
    if (entity.isSneaking && damage != 240) {
      
        const projectile = "mutant:endersoul_pearl";
        


        const arrow = entity.dimension.spawnEntity(projectile, entity.getHeadLocation());
        const projComp = arrow.getComponent("projectile");
        projComp.owner = entity;

        // Increase projectile speed by multiplying view direction
        const viewDirection = entity.getViewDirection();
        const speedMultiplier = 90;  // Increase this value to make the projectile faster

        const increasedSpeed = {
            x: viewDirection.x * speedMultiplier,
            y: viewDirection.y * speedMultiplier,
            z: viewDirection.z * speedMultiplier
        };

        projComp.shoot(increasedSpeed);
        entity.addEffect("resistance", 2, {amplifier: 50});
        if (entity.getGameMode() !== "creative") {
            durabilityComponent.damage = Math.max(damage + 1, 0);
        }
      
        entity.runCommandAsync('playsound mob.mutant_endersoul_hand.teleport @s[r=65] ~ ~ ~ 100 1');
        entity.getComponent("equippable").setEquipment("Mainhand", itemStack);
    }
   else if (entity.isSneaking == false && damage != 240) {
      
        
    const projectile = "mutant:endersoul_block_catcher<endersoul_hand_throw>";


        const arrow = entity.dimension.spawnEntity(projectile, entity.getHeadLocation());
        const projComp = arrow.getComponent("projectile");
        projComp.owner = entity;

        // Increase projectile speed by multiplying view direction
        const viewDirection = entity.getViewDirection();
        const speedMultiplier = 3;  // Increase this value to make the projectile faster

        const increasedSpeed = {
            x: viewDirection.x * speedMultiplier,
            y: viewDirection.y * speedMultiplier,
            z: viewDirection.z * speedMultiplier
        };

        projComp.shoot(increasedSpeed);
         if (entity.getGameMode() !== "creative") {
            durabilityComponent.damage = Math.max(damage + 1, 0);
        }
        entity.getComponent("equippable").setEquipment("Mainhand", itemStack);
    }
    else if (entity.isSneaking && damage == 240) {
      
        const projectile = "mutant:endersoul_pearl";
        


        const arrow = entity.dimension.spawnEntity(projectile, entity.getHeadLocation());
        const projComp = arrow.getComponent("projectile");
        projComp.owner = entity;

        // Increase projectile speed by multiplying view direction
        const viewDirection = entity.getViewDirection();
        const speedMultiplier = 90;  // Increase this value to make the projectile faster

        const increasedSpeed = {
            x: viewDirection.x * speedMultiplier,
            y: viewDirection.y * speedMultiplier,
            z: viewDirection.z * speedMultiplier
        };

        projComp.shoot(increasedSpeed);
        entity.addEffect("resistance", 2, {amplifier: 50});
        if (entity.getGameMode() !== "creative") {
            entity.runCommandAsync('clear @s mutant:endersoul_hand 240 1');
        entity.runCommandAsync('playsound random.break');
        }
      
        entity.runCommandAsync('playsound mob.mutant_endersoul_hand.teleport @s[r=65] ~ ~ ~ 100 1');
        entity.getComponent("equippable").setEquipment("Mainhand", itemStack);
    }
   else if (entity.isSneaking == false && damage == 240) {
      
        
    const projectile = "mutant:endersoul_block_catcher<endersoul_hand_throw>";


        const arrow = entity.dimension.spawnEntity(projectile, entity.getHeadLocation());
        const projComp = arrow.getComponent("projectile");
        projComp.owner = entity;

        // Increase projectile speed by multiplying view direction
        const viewDirection = entity.getViewDirection();
        const speedMultiplier = 3;  // Increase this value to make the projectile faster

        const increasedSpeed = {
            x: viewDirection.x * speedMultiplier,
            y: viewDirection.y * speedMultiplier,
            z: viewDirection.z * speedMultiplier
        };

        projComp.shoot(increasedSpeed);
        if (entity.getGameMode() !== "creative") {
            entity.runCommandAsync('clear @s mutant:endersoul_hand 240 1');
        entity.runCommandAsync('playsound random.break');
        }
        entity.getComponent("equippable").setEquipment("Mainhand", itemStack);
    }
}

const cooldowns = new Map();

world.beforeEvents.worldInitialize.subscribe(e => {
    e.itemComponentRegistry.registerCustomComponent("mutant_script:hulk_hammer", {
    
      onUseOn: lt => {
      
        const cooldown = 30; // 1.5 seconds
        const delay = 1;
        const holder = lt.source;
        const itemStack = holder.getComponent("equippable").getEquipment("Mainhand");
        
        if (!itemStack) return; // Ensure item exists
        
        const durabilityComponent = itemStack.getComponent("durability");
        const damage = durabilityComponent.damage;

        const blockL = lt.block.location;
        const direction = holder.getViewDirection();
       
        if (cooldowns.has(holder)) {
          const lastHitTick = cooldowns.get(holder);
          const currentTick = system.currentTick;
      
          if (currentTick - lastHitTick < cooldown) 
            return;
        }
  
        cooldowns.set(holder, system.currentTick);
        
        if (damage !== 64) {
            // Reduce durability by 1
            if (holder.getGameMode() !== "creative") {
                durabilityComponent.damage = Math.min(damage + 1, 64);
                holder.getComponent("equippable").setEquipment("Mainhand", itemStack);
            }
            holder.getComponent("equippable").setEquipment("Mainhand", itemStack);
        } else {
            // Run a command when durability is exactly 64
            if (holder.getGameMode() !== "creative") {
                holder.runCommandAsync('clear @s mutant:hulk_hammer 64 1');
                holder.runCommandAsync('playsound random.break');
                holder.getComponent("equippable").setEquipment("Mainhand", itemStack);
            }
        }

        // Summon entities with delay
        for (let i = 0; i <= 7; i++) {
          system.runTimeout(() => {
            const x = blockL.x + direction.x * i;
            const y = blockL.y + 1;
            const z = blockL.z + direction.z * i;
            holder.addEffect("resistance", 2, {amplifier: 50});
            holder.runCommandAsync(`summon mutant:smash_attack ${x} ${y} ${z} zombie_damage`);
          }, delay * i);
        }
      }
    });
});
  const mutation_information = [
    { mob: "minecraft:axolotl", mutate_into: "mutant:mutant_axolotl" },
    { mob: "minecraft:bogged", mutate_into: "mutant:mutant_bogged" },
    { mob: "minecraft:creeper", mutate_into: "mutant:mutant_creeper" },
    { mob: "minecraft:drowned", mutate_into: "mutant:mutant_drowned" },
    { mob: "minecraft:enderman", mutate_into: "mutant:mutant_enderman" },
    { mob: "minecraft:evocation_illager", mutate_into: "mutant:mutant_evoker" },
    { mob: "minecraft:husk", mutate_into: "mutant:mutant_husk" },
    { mob: "minecraft:iron_golem", mutate_into: "mutant:mutant_iron_golem" },
    { mob: "minecraft:ocelot", mutate_into: "mutant:mutant_ocelot" },
    { mob: "minecraft:piglin", mutate_into: "mutant:mutant_piglin" },
    { mob: "minecraft:piglin_brute", mutate_into: "mutant:mutant_piglin_brute" },
    { mob: "minecraft:pillager", mutate_into: "mutant:mutant_pillager" },
    { mob: "minecraft:skeleton", mutate_into: "mutant:mutant_skeleton" },
    { mob: "minecraft:stray", mutate_into: "mutant:mutant_stray" },
    { mob: "minecraft:snow_golem", mutate_into: "mutant:mutant_snow_golem" },
    { mob: "minecraft:villager_v2", mutate_into: "mutant:mutant_villager" },
    { mob: "minecraft:wither_skeleton", mutate_into: "mutant:mutant_wither_skeleton" },
    { mob: "minecraft:vindicator", mutate_into: "mutant:mutant_vindicator" },
    { mob: "minecraft:vex", mutate_into: "mutant:mutant_vex" },
    { mob: "minecraft:wolf", mutate_into: "mutant:mutant_wolf" },
    { mob: "minecraft:zombie", mutate_into: "mutant:mutant_zombie" },
    { mob: "minecraft:zombie_pigman", mutate_into: "mutant:mutant_zombified_piglin" },
    { mob: "minecraft:zombie_villager_v2", mutate_into: "mutant:mutant_zombie_villager" },

    { mob: "mutant:endolotl", mutate_into: "mutant:mutant_endolotl" },
    { mob: "mutant:bouldering_zombie_minion", mutate_into: "mutant:mutant_bouldering_zombie" },
    { mob: "mutant:lobber_zombie_minion", mutate_into: "mutant:mutant_lobber_zombie" },
    { mob: "mutant:skeleton_wolf", mutate_into: "mutant:mutant_skeleton_wolf" },
    { mob: "mutant:skeleton_wolf<minecraft:is_baby>", mutate_into: "mutant:mutant_skeleton_wolf" },
  
];


world.afterEvents.entityHitEntity.subscribe((event) => {
    const attacker = event.damagingEntity;
    const victim = event.hitEntity;

    if (!attacker || !victim || !victim.isValid()) return;

    const attackerId = attacker.typeId;
    const victimId = victim.typeId;

    if (attackerId !== "mutant:chemical_x_ghost") return;

    const mutation = mutation_information.find(info => info.mob === victimId);
    const victimDimension = victim.dimension;
    
    victim.runCommandAsync(`effect @s[type=!creaking] fatal_poison 10 0 true`); 

    let particleLoop = system.runInterval(() => {
        if (!victim.isValid()) {
            system.clearRun(particleLoop); 
            return;
        }
        
        try {
            victimDimension.spawnParticle("mutant:chemical_x_affected_particle", victim.location);
        } catch (error) {
        }

        victim.runCommandAsync(`effect @s resistance 10 21 true`);
        victim.runCommandAsync(`effect @s slowness 10 0 true`);
    }, 1);
   
    system.runTimeout(() => {
        if (!victim.isValid()) {
            system.clearRun(particleLoop);
            return;
        }

        const updatedLocation = victim.location;
        if (mutation) { 
            if (Math.random() < 0.25) {
                // 25% chance to explode
                const explode = victimDimension.spawnEntity("mutant:chemical_x_ghost<js7_mutant:mutation_explosion>", updatedLocation);
                if (explode) {
                    victim.remove();
                }
            } else {
                // Mutation
                victim.remove();
                const mutatedEntity = victimDimension.spawnEntity(mutation.mutate_into, updatedLocation);
                if (mutatedEntity) {
                    victimDimension.playSound("mob.zombie.remedy", updatedLocation);
                    
                    try {
                        victimDimension.spawnParticle("mutant:chemical_x_affected_explosion_particle", updatedLocation);
                    } catch (error) {
                        // Suppress any errors if the particle fails
                    }
                }
            }
        } else {
            // Non-Mutants and custom entities
            victimDimension.spawnEntity("mutant:chemical_x_ghost<js7_mutant:mutation_explosion>", updatedLocation);
            victim.remove();
        }

        system.clearRun(particleLoop);
    }, 160); // 8 seconds
});
world.afterEvents.entityDie.subscribe((event) => {
    const victim = event.deadEntity;
    const killer = event.damageSource.damagingEntity;

    if (!victim || !killer) return;

    if (killer.typeId === "mutant:mutant_spider_pig" && 
        (victim.typeId === "minecraft:spider" || victim.typeId === "minecraft:pig")) {

        const victimLocation = victim.location;
        const victimDimension = victim.dimension;

        // Spawn the mutant in place of the victim
        const transformedEntity = victimDimension.spawnEntity("mutant:mutant_spider_pig", victimLocation);

        if (transformedEntity) {
            victim.remove();
            victimDimension.spawnParticle("mutant:chemical_x_affected_explosion_particle", victimLocation);
            victimDimension.playSound("mob.zombiepig.zpigdeath", victimLocation);
        }
    }
});