import { world, ItemStack, system, Player, MolangVariableMap } from '@minecraft/server';
import { Vector } from './Vector';

world.afterEvents.playerSpawn.subscribe(({ player }) => {
    if (player.hasTag("nature_journal")) return;
    const item = new ItemStack('ph_wild:nature_journal');
    const lore = [
      `§r§7Page 0 of 40`,
    ];
    item.setLore(lore);

    const inv = player.getComponent("inventory").container;
    inv.addItem(item);
    player.addTag("nature_journal");
});

export const entity_list = {
    "ph_wild:bird": {},
    "ph_wild:bison": {},
    "ph_wild:bison_baby": {},
    "ph_wild:butterfly": {},
    "ph_wild:elephant": {
        food_list: [
          "minecraft:apple",
          "minecraft:wheat",
          "minecraft:carrot",
          "minecraft:potato",
          "minecraft:beetroot",
          "minecraft:sugar",
          "minecraft:sugar_cane"
        ]
    },
    "ph_wild:great_white_shark": {},
    "ph_wild:grizzly_bear": {
        food_list: [
          "minecraft:apple",
          "minecraft:beef",
          "minecraft:beetroot",
          "minecraft:brown_mushroom",
          "minecraft:carrot",
          "minecraft:chicken",
          "minecraft:clownfish",
          "minecraft:cooked_beef",
          "minecraft:cooked_chicken",
          "minecraft:cooked_fish",
          "minecraft:cooked_porkchop",
          "minecraft:cooked_rabbit",
          "minecraft:cooked_salmon",
          "minecraft:fish",
          "minecraft:glow_berries",
          "minecraft:honeycomb",
          "minecraft:melon_slice",
          "minecraft:muttonCooked",
          "minecraft:muttonRaw",
          "minecraft:porkchop",
          "minecraft:potato",
          "minecraft:pufferfish",
          "minecraft:rabbit",
          "minecraft:red_mushroom",
          "minecraft:rotten_flesh",
          "minecraft:salmon",
          "minecraft:sweet_berries",
          "ph_wild:banana",
          "ph_wild:bison_cooked",
          "ph_wild:bison_raw",
          "ph_wild:elephant_cooked",
          "ph_wild:elephant_raw",
          "ph_wild:hippo_raw",
          "ph_wild:hippo_cooked",
          "ph_wild:octopus_leg_cooked",
          "ph_wild:octopus_leg_raw",
          "ph_wild:shark_meat_cooked",
          "ph_wild:shark_meat_raw",
          "ph_wild:shark_fin",
        ]
    },
    "ph_wild:gorilla": {
        food_list: [
          "minecraft:apple",
          "minecraft:melon_slice",
          "ph_wild:banana",
        ]
    },
    "ph_wild:gorilla.silverback": {
        food_list: [
          "minecraft:apple",
          "minecraft:melon_slice",
          "ph_wild:banana",
        ]
    },
    "ph_wild:hamster": {},
    "ph_wild:hippo": {
        food_list: [
          "minecraft:melon_block",
          "minecraft:pumpkin",
        ]
    },
    "ph_wild:jaguar": {},
    "ph_wild:jellyfish": {},
    "ph_wild:leopard": {},
    "ph_wild:lion": {},
    "ph_wild:lioness": {},
    "ph_wild:lizard": {
        loot: "ph_wild:lizard_1_tail"
    },
    "ph_wild:octopus": {},
    "ph_wild:red_panda": {},
    "ph_wild:shark_hammerhead": {},
    "ph_wild:snake": {},
    "ph_wild:snow_leopard": {},
    "ph_wild:stingray": {},
    "ph_wild:tiger": {},

    "ph_wild:nature_journal": {},
};

function getNearbyBlocks(entity, range) {
    const blocks = [];
    const startX = entity.location.x - range / 2;
    const startY = entity.location.y - range / 2;
    const startZ = entity.location.z - range / 2;

    for (let x = startX; x < startX + range; x++) {
        for (let y = startY; y < startY + range; y++) {
            for (let z = startZ; z < startZ + range; z++) {
                const block = entity.dimension.getBlock({ x, y, z });
                blocks.push(block);
            }
        }
    }
    return blocks;
}

function calculateDistance(loc1, loc2) {
  const dx = loc2.x - loc1.x;
  const dy = loc2.y - loc1.y;
  const dz = loc2.z - loc1.z;
  return Math.sqrt(dx ** 2 + dy ** 2 + dz ** 2);
}

function setTarget(entity, target) {
    const healthComponent = entity.getComponent("health");
    const currentHealth = healthComponent.currentValue;
    healthComponent.setCurrentValue(currentHealth + 1);
    entity.addEffect('instant_health', 1, { amplifier: 0, showParticles: false });
    entity.applyDamage(1, { cause: "suicide", damagingEntity: target });
    entity.removeEffect('instant_health');
    healthComponent.setCurrentValue(currentHealth);
}

function playDistantSound(entity, player, sound, minVolume, maxVolume, minVolumeDistance, maxVolumeDistance, pitch) {
    const distance = Math.sqrt(
        (player.location.x - entity.location.x) ** 2 +
        (player.location.y - entity.location.y) ** 2 +
        (player.location.z - entity.location.z) ** 2
    );
    const volume = Math.max(minVolume, maxVolume - (distance - minVolumeDistance) / (maxVolumeDistance - minVolumeDistance));

    player.runCommandAsync(`playsound ${sound} @s ${entity.location.x} ${entity.location.y} ${entity.location.z} ${volume} ${pitch} ${volume}`);
}

function viewDirectionKnockback(source, target, horizontalStrength, verticalStrength) {
    const viewDirection = source.getViewDirection();

    const magnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
    const normalizedX = viewDirection.x / magnitude;
    const normalizedZ = viewDirection.z / magnitude;

    target.applyKnockback(
        normalizedX,
        normalizedZ,
        horizontalStrength,
        verticalStrength
    );
}

function elephantAttack(source, target, horizontalStrength, verticalStrength, baseTuskDurabilityDamage, applyAttack) {
    try {
        const leftTusk = source.getProperty('ph_wild:left_tusk');
        const rightTusk = source.getProperty('ph_wild:right_tusk');
        const leftTuskDurability = source.getProperty('ph_wild:left_tusk_durability');
        const rightTuskDurability = source.getProperty('ph_wild:right_tusk_durability');
        const isTamed = source.getComponent("is_tamed");

        const calculateTuskDamage = (tusk) => {
            if (tusk === 1) return 1;
            if (tusk === 2) return 2;
            if (tusk === 3) return 1;
            if (tusk === 4) return 4;
            if (tusk === 5) return 6;
            if (tusk === 6) return 8;
            return 0;
        };
        const calculateTuskKnockback = (tusk) => {
            if (tusk === 1 || tusk === 2) return 0.5;
            if (tusk === 3) return 1;
            if (tusk === 4) return 0.25;
            if (tusk === 5) return 0.25;
            if (tusk === 6) return 0.25;
            return 0.35;
        };
        const baseDamage = calculateTuskDamage(leftTusk) + calculateTuskDamage(rightTusk);
        const damage = (isTamed ? baseDamage + 2 : baseDamage) + 2;

        const knockbackFactor = calculateTuskKnockback(leftTusk) + calculateTuskKnockback(rightTusk);
        
        const adjustedHorizontalStrength = horizontalStrength * knockbackFactor;
        const adjustedVerticalStrength = verticalStrength * knockbackFactor + 0.25 * Math.min(knockbackFactor, 1);

        if (applyAttack) {
            target.applyDamage(damage, { cause: "ramAttack", damagingEntity: source });
            viewDirectionKnockback(source, target, adjustedHorizontalStrength, adjustedVerticalStrength);
        }

        const viewDirection = source.getViewDirection();
        const spawnLocation = {
            x: source.location.x + viewDirection.x * 2,
            y: source.location.y + 1.5,
            z: source.location.z + viewDirection.z * 2,
        };

        if (leftTuskDurability == 0 && leftTusk >= 1) {
            const tuskItem = new ItemStack("ph_wild:broken_elephant_tusk", 1);
            source.dimension.spawnItem(tuskItem, spawnLocation);
            source.dimension.playSound('mob.wither.break_block', spawnLocation, { pitch: 1.0, volume: 1.0, });
            source.setProperty(`ph_wild:left_tusk`, 0);
        };
        if (rightTuskDurability == 0 && rightTusk >= 1) {
            const tuskItem = new ItemStack("ph_wild:broken_elephant_tusk", 1);
            source.dimension.spawnItem(tuskItem, spawnLocation);
            source.dimension.playSound('mob.wither.break_block', spawnLocation, { pitch: 1.0, volume: 1.0, });
            source.setProperty(`ph_wild:right_tusk`, 0);
        };
        source.setProperty(`ph_wild:left_tusk_durability`, Math.max(0, leftTuskDurability - baseTuskDurabilityDamage));
        source.setProperty(`ph_wild:right_tusk_durability`, Math.max(0, rightTuskDurability - baseTuskDurabilityDamage));
        //console.warn(`\nLeft Tusk: ${leftTusk}.  Right Tusk: ${rightTusk}.  Tamed: ${isTamed ? 'true' : 'false'}\n${applyAttack ? `Horizontal Knockback: ${adjustedHorizontalStrength}.  Vertical Knockback: ${adjustedVerticalStrength}.  Damage: ${damage}\n` : ''}Left Tusk Durability: ${leftTuskDurability}.  Right Tusk Durability: ${rightTuskDurability}`);
        return true;
    } catch {
        return false;
    }
}

world.afterEvents.dataDrivenEntityTrigger.subscribe(xm => {
    const { entity } = xm;
    const event = xm.eventId;

    const entity_id = entity_list[entity?.typeId];

    if (entity.typeId == "ph_wild:hippo") {
        if (event == "boat_attack") {
            let target = entity.dimension.getEntities({
                families: ["boat"],
                location: entity.location,
                closest: 1,
                maxDistance: 16
            })[0];

            if (target != null) {
                system.runTimeout(() => {
                    let time = 0;
                    const attack = system.runInterval(() => {
                        try {
                            let target = entity.dimension.getEntities({
                                families: ["boat"],
                                location: entity.location,
                                closest: 1,
                                maxDistance: 16
                            })[0];

                            if (target == null) {
                                system.clearRun(attack);
                                return;
                            }

                            let zDelta = target.location.z - entity.location.z;
                            let yDelta = target.location.y - entity.location.y;
                            let xDelta = target.location.x - entity.location.x;
                            let angle = Math.atan(zDelta / xDelta);
                            let xAngle = Math.cos(angle) * (xDelta >= 0 ? 1 : -1);
                            let zAngle = Math.sin(angle) * (xDelta >= 0 ? 1 : -1);

                            entity.applyKnockback(xAngle, zAngle, 0.5, 0);
                            entity.setRotation({ x: 0, y: (xAngle > 0 ? -180 + (90 + zAngle * 90) : 180 - (90 + zAngle * 90)) });

                            const distanceToTarget = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2) + Math.pow(zDelta, 2));
                            if (distanceToTarget <= 2.5) {
                                entity.runCommand(`playanimation @s animation.ph_wild.hippo.attack`);
                                world.playSound('ph_wild.attack_boat', entity.location);
                                target.applyDamage(Math.floor(Math.random() * 10) + 5);
                                system.clearRun(attack);
                                return;
                            }
                            if (!entity.isValid()) {
                                system.clearRun(attack);
                                return;
                            }
                            if (time >= 2.0) {
                                system.clearRun(attack);
                                return;
                            }
                        } catch {
                        }

                        time += 0.25;
                    }, 5);
                }, 40);
            }
        }
        if (event == "out_anim") {
            entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
        }
        if (event == "is_eat") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 1.25) {
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.runCommand('replaceitem entity @s slot.inventory 0 air');
                        system.clearRun(eat);
                        return;
                    }
                    entity.dimension.playSound('random.eat', entity.location);
                    entity.dimension.spawnParticle('minecraft:heart_particle', entity.location);
                    time += 0.25;
                } catch { }
            }, 5)
        }
    }
    if (entity.typeId == "ph_wild:leopard" || entity.typeId == "ph_wild:snow_leopard" || entity.typeId == "ph_wild:jaguar" || entity.typeId == "ph_wild:tiger" || entity.typeId == "ph_wild:lion" || entity.typeId == "ph_wild:lioness") {
        if (event == "dash_attack") {
            const entityType = entity.typeId.split(":")[1];
            entity.dimension.playSound(`ph_wild.${entityType}.jump`, entity.location);
        }
        if (event == "entity_spawned") {
            if (entity.typeId == "ph_wild:lion") {
                entity.dimension.spawnEntity(`ph_wild:lioness<entity_born>`, entity.location);
                let times = Math.floor(Math.random() * 4) + 1; // 生成1到4的随机次数
                for (let i = 0; i < times; i++) {
                    entity.dimension.spawnEntity(`ph_wild:lioness<adult>`, entity.location);
                }
            }
        }
        if (event == "is_eat") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }
                    // const on_hurt = entity.getProperty("ph_wild:on_hurt");
                    // if (on_hurt) {
                    //     entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                    //     world.playSound("random.burp", entity.location);
                    //     entity.dimension.spawnItem(new ItemStack("minecraft:bone", 1), entity.location);
                    //     entity.triggerEvent("eat_up");
                    //     system.clearRun(eat);
                    //     return;
                    // }
                    if (time >= 4.0) {
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        world.playSound("random.burp", entity.location);
                        entity.dimension.spawnItem(new ItemStack("minecraft:bone", 1), entity.location);
                        entity.triggerEvent("eat_up");
                        system.clearRun(eat);
                        return;
                    }
                    // 随机生成心型粒子的矢量位置
                    const randomOffset = {
                        x: (Math.random() * 0.8) - 0.8, // -2 到 2 之间的随机数
                        y: (Math.random() * 1.0) - 0.2,
                        z: (Math.random() * 0.8) - 0.8
                    };

                    const particleLocation = {
                        x: entity.location.x + randomOffset.x,
                        y: entity.location.y + randomOffset.y,
                        z: entity.location.z + randomOffset.z
                    };

                    entity.dimension.playSound('random.eat', entity.location);
                    entity.dimension.spawnParticle('minecraft:heart_particle', particleLocation);
                    time += 0.25;
                } catch { }
            }, 5)
        }
    }
    if (entity.typeId == "ph_wild:hamster") {
        if (event == "not_riding") {
            entity.runCommand('/ride @s stop_riding');
        }
        if (event == "eat_food") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 2.0) {
                        entity.runCommand('/replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.triggerEvent("eat_up");
                        system.clearRun(eat);
                        return;
                    }
                    // 随机生成心型粒子的矢量位置
                    const randomOffset = {
                        x: (Math.random() * 0.8) - 0.5,
                        y: (Math.random() * 0.8) - 0,
                        z: (Math.random() * 0.8) - 0.5
                    };

                    const particleLocation = {
                        x: entity.location.x + randomOffset.x,
                        y: entity.location.y + randomOffset.y,
                        z: entity.location.z + randomOffset.z
                    };

                    entity.dimension.playSound('random.eat', entity.location);
                    entity.dimension.spawnParticle('minecraft:heart_particle', particleLocation);
                    time += 0.25;
                } catch { }
            }, 5)
        }
    }
    if (entity.typeId == "ph_wild:great_white_shark" || entity.typeId == "ph_wild:shark_hammerhead") {
        if (event == "boat_attack") {

            let target = entity.dimension.getEntities({ families: ["boat"], location: entity.location, closest: 1, maxDistance: 16 })[0];
            if (target != null) {
                // 计算实体与目标之间的方向向量
                let z_value = target.location.z - entity.location.z;
                let y_value = target.location.y - entity.location.y;
                let x_value = target.location.x - entity.location.x;
                let yaw = Math.atan2(z_value, x_value) * (180 / Math.PI); // 将弧度转换为度数
                let distance = Math.sqrt(x_value * x_value + z_value * z_value);
                let pitch = Math.atan2(y_value, distance) * (180 / Math.PI); // 计算俯仰角

                // 将 pitch 转换为 -90 到 90 度之间
                if (pitch < -90) pitch = -90;
                if (pitch > 90) pitch = 90;

                // 将 yaw 转换为 -180 到 180 度之间
                if (yaw < -180) yaw += 360;
                if (yaw > 180) yaw -= 360;

                entity.setRotation({ x: pitch, y: yaw }); // 设置实体的旋转角度

                system.runTimeout(() => {
                    let time = 0;
                    const attack = system.runInterval(() => {
                        let target = entity.dimension.getEntities({ families: ["boat"], location: entity.location, closest: 1, maxDistance: 16 })[0];
                        if (target == null) {
                            system.clearRun(attack);
                            return;
                        }
                        try {
                            let z_value = target.location.z - entity.location.z;
                            let y_value = target.location.y - entity.location.y;
                            let x_value = target.location.x - entity.location.x;
                            let yaw = Math.atan2(z_value, x_value) * (180 / Math.PI); // 将弧度转换为度数
                            let distance = Math.sqrt(x_value * x_value + z_value * z_value);
                            let pitch = Math.atan2(y_value, distance) * (180 / Math.PI); // 计算俯仰角

                            // 将 pitch 转换为 -90 到 90 度之间
                            if (pitch < -90) pitch = -90;
                            if (pitch > 90) pitch = 90;

                            // 将 yaw 转换为 -180 到 180 度之间
                            if (yaw < -180) yaw += 360;
                            if (yaw > 180) yaw -= 360;

                            // 检查实体是否到达目标2格以内
                            let distanceToTarget = Math.sqrt(x_value * x_value + y_value * y_value + z_value * z_value);
                            if (distanceToTarget <= 2.5) {
                                // world.sendMessage("攻击！");
                                entity.runCommand(`playanimation @s animation.ph_wild.shark.attack`);
                                world.playSound('ph_wild.attack_boat', entity.location);
                                target.applyDamage(Math.floor(Math.random() * 10) + 5);
                                entity.triggerEvent("is_avoid");
                                system.clearRun(attack);
                            }
                            if (!entity.isValid()) {
                                system.clearRun(attack);
                                return;
                            }
                            if (time >= 5.5) {
                                entity.triggerEvent("is_avoid");
                                system.clearRun(attack);
                                return;
                            }
                            if (!entity.isInWater) return;

                            // 设置 applyImpulse 值为实体与目标之间的方向向量

                            entity.setRotation({ x: pitch, y: yaw }); // 设置实体的旋转角度
                            entity.applyImpulse(Vector.multiply({ x: x_value, y: y_value, z: z_value }, 0.05)); // 调整冲刺力度
                        } catch (error) {
                            console.error(error);
                        }
                        time += 0.25;
                    }, 5);
                }, 40);
            }
        }
        if (event == "attack_impulse") {
            entity.setProperty('ph_wild:move_rotation', true);
            const viewDirection = entity.getViewDirection();
            let time = 0;
            const attack_move = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(attack_move);
                        return;
                    }
                    if (time >= 1.0) {
                        system.clearRun(attack_move);
                        entity.triggerEvent("add:track_target");
                        entity.setProperty('ph_wild:move_rotation', false);
                        return;
                    }
                    const magnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.y ** 2 + viewDirection.z ** 2);

                    const normalizedDirection = {
                        x: viewDirection.x / magnitude,
                        y: viewDirection.y / magnitude,
                        z: viewDirection.z / magnitude,
                    };

                    const impulseStrength = 0.5;
                    const impulseDirection = {
                        x: normalizedDirection.x * impulseStrength,
                        y: normalizedDirection.y * impulseStrength,
                        z: normalizedDirection.z * impulseStrength,
                    };
                    
                
                    entity.applyImpulse(impulseDirection);
                    time += 0.25;
                } catch { }
            }, 5)
        }
    }
    if (entity.typeId == "ph_wild:octopus") {
        if (event == "is_land_hurt") {
            if (entity.isValid() == false) return;

            //world.sendMessage("受到惊吓");
            entity.dimension.spawnParticle("ph_wild:octopus_ink", entity.location);
        }
        if (event == "is_hurt") {
            if (entity.isValid() == false) return;

            //world.sendMessage("受到惊吓");
            entity.dimension.spawnParticle("ph_wild:octopus_ink", entity.location);
        }
        if (event == "is_scared") {
            if (!entity.isValid()) return;

            const camouflage = system.runInterval(() => {
                try {
                    if (!entity.isValid()) {
                        system.clearRun(camouflage);
                        return;
                    }


                    const block_1 = entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y, z: entity.location.z });
                    const block_2 = entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 1, z: entity.location.z });

                    if (block_2.typeId !== "minecraft:water" && block_2.typeId !== "minecraft:air" && block_2.typeId !== "minecraft:seagrass" && !block_2.typeId.includes("coral")) {
                        if (block_1.typeId == "minecraft:water") {
                            entity.teleport({ x: block_2.location.x + 0.5, y: block_2.location.y + 1, z: block_2.location.z + 0.5 }, { facingLocation: { x: 0, y: 0, z: 0 } });
                            entity.triggerEvent("camouflage");
                            system.clearRun(camouflage);
                        }
                    }
                } catch { }
            }, 4);
        }
    }
    if (entity.typeId == "ph_wild:bison") {
        if (event == "snow_shake") {
            let time = 0;
            let shakedOff = false;
            const drop = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(drop);
                        return;
                    }
                    if (time >= 0.2 && !shakedOff) {
                        entity.dimension.playSound("hit.powder_snow", entity.location);
                        entity.dimension.spawnParticle('ph_wild:snow_shake_1', entity.location);
                    }
                    if (time >= 2.0 && !shakedOff) {
                        const itemLocation = {
                            x: entity.location.x,
                            y: entity.location.y + 1.2,
                            z: entity.location.z
                        };
                        const snowballCount = Math.floor(Math.random() * 3) + 1;
                        const snowball = new ItemStack("minecraft:snowball", snowballCount);
                        entity.dimension.spawnItem(snowball, itemLocation);
                        shakedOff = true;
                    }
                    if (time >= 2.5) {
                        system.clearRun(drop);
                        return;
                    }
                    time += 0.25;
                } catch { }
            }, 5)
        };
        if (event == "remove_snow") {
            entity.dimension.playSound("use.snow", entity.location);
        };
    }
    if (entity.typeId == "ph_wild:bison_baby") {
        if (event == "remove_snow") {
            entity.dimension.playSound("use.snow", entity.location);
        };
    }
    if (entity.typeId == "ph_wild:stingray") {
        if (event == "move_to_random") {
            if (entity.isValid() == false) return;

            //world.sendMessage("卧沙")
            let time = 0;
            system.runTimeout(() => {
                if (entity.isValid() == false) return;
                const hide = system.runInterval(() => {
                    try {
                        if (entity.isValid() == false) {
                            system.clearRun(hide);
                            return;
                        }
                        if (time >= 1.5) {
                            system.clearRun(hide);
                            return;
                        }
                        if (Math.random() < 0.6) {
                            const blocks = [
                                entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 1, z: entity.location.z })
                            ];

                            for (const block of blocks) {
                                if (block.typeId == "minecraft:sand" || block.typeId == "minecraft:red_sand") {
                                    entity.teleport({ x: block.location.x + 0.5, y: block.location.y + 1, z: block.location.z + 0.5 });
                                    entity.triggerEvent("camouflage_on");
                                    if (block.typeId == "minecraft:sand") {
                                        entity.dimension.spawnParticle("ph_wild:lizard_3", entity.location);
                                    } else {
                                        entity.dimension.spawnParticle("ph_wild:lizard_4", entity.location);
                                    }

                                    system.clearRun(hide);
                                    break;
                                }
                            }

                        }
                    } catch { }
                    time += 0.2;
                }, 4);
            }, 30)
        }
    }
    if (entity.typeId == "ph_wild:butterfly") {
        // if (event == "is_nectar") {
        //     let time = 0;
        //     const eat = system.runInterval(() => {
        //         try {
        //             if (!entity.isValid()) {
        //                 system.clearRun(eat);
        //                 return;
        //             }
        //             if (time >= 4.0) {
        //                 const block = entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 0.2, z: entity.location.z });
        //                 if (block.typeId === "minecraft:dandelion") {
        //                     entity.triggerEvent("hover");
        //                 }
        //                 system.clearRun(eat);
        //                 return;
        //             }
        //             const block = entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 0.2, z: entity.location.z });
        //             if (block.typeId === "minecraft:dandelion") {
        //                 entity.triggerEvent("hover");
        //                 system.clearRun(eat);
        //                 return;
        //             }
        //             time += 0.05;
        //         } catch (error) {
        //             console.error(error);
        //         }
        //     }, 4);
        // }
        if (event == "is_flying") {
            let time = 0;
            const fly = system.runInterval(() => {
                try {
                    if (!entity.isValid()) {
                        system.clearRun(fly);
                        return;
                    }
                    if (time >= 1.0) {
                        const block = entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 0.2, z: entity.location.z });
                        const blockTypeId = block.typeId;

                        const flowerMap = {
                            "minecraft:torchflower": ["orange_dye", 1],
                            "minecraft:dandelion": ["yellow_dye", 2],
                            "minecraft:poppy": ["red_dye", 3],
                            "minecraft:blue_orchid": ["light_blue_dye", 4],
                            "minecraft:allium": ["magenta_dye", 5],
                            "minecraft:azure_bluet": ["light_gray_dye", 6],
                            "minecraft:red_tulip": ["red_dye", 7],
                            "minecraft:orange_tulip": ["orange_dye", 8],
                            "minecraft:white_tulip": ["light_gray_dye", 9],
                            "minecraft:pink_tulip": ["pink_dye", 10],
                            "minecraft:oxeye_daisy": ["light_gray_dye", 11],
                            "minecraft:cornflower": ["blue_dye", 12],
                            "minecraft:lily_of_the_valley": ["white_dye", 13],
                        };

                        if (flowerMap[blockTypeId]) {
                            const [dye, foodValue] = flowerMap[blockTypeId];
                            entity.runCommand(`/replaceitem entity @s slot.weapon.mainhand 0 ${dye}`);
                            entity.setDynamicProperty("ph_wild:food", foodValue);
                        }

                        system.clearRun(fly);
                        return;
                    }
                    time += 1;
                } catch (error) {
                    console.error(error);
                }
            }, 1);
        }

        if (event == "eat_item") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (!entity.isValid()) {
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 2.0) {
                        entity.runCommand("/replaceitem entity @s slot.weapon.mainhand 0 air");
                        entity.setProperty("ph_wild:nectar", false);
                        entity.setProperty("ph_wild:eat_item", false);
                        system.clearRun(eat);
                        return;
                    }
                    entity.dimension.playSound('random.eat', entity.location);
                    entity.dimension.spawnParticle('minecraft:heart_particle', entity.location);
                    time += 0.25;
                } catch (error) {
                    console.error(error);
                }
            }, 5);
        }
        if (event == "drop_item") {
            try {
                const nectar = entity.getProperty("ph_wild:nectar");
                if (nectar) {
                    const food = entity.getDynamicProperty("ph_wild:food");
                    entity.runCommand("/replaceitem entity @s slot.weapon.mainhand 0 air");
                    entity.setProperty("ph_wild:is_scared", false);
                    entity.setProperty("ph_wild:nectar", false);

                    const nectarItems = [
                        "minecraft:orange_dye",      // 1
                        "minecraft:yellow_dye",      // 2
                        "minecraft:red_dye",         // 3
                        "minecraft:light_blue_dye",  // 4
                        "minecraft:magenta_dye",     // 5
                        "minecraft:light_gray_dye",  // 6
                        "minecraft:red_dye",         // 7
                        "minecraft:orange_dye",      // 8
                        "minecraft:light_gray_dye",  // 9
                        "minecraft:pink_dye",        // 10
                        "minecraft:light_gray_dye",  // 11
                        "minecraft:blue_dye",        // 12
                        "minecraft:white_dye"        // 13
                    ];

                    const nectarIndex = (food - 1) % nectarItems.length; // 调整索引
                    const nectarItem = nectarItems[nectarIndex];

                    entity.dimension.spawnItem(new ItemStack(nectarItem, 1), entity.location);
                }
            } catch { }
        }
    }
    if (entity.typeId == "ph_wild:bird") {
        if (event == "not_riding") {
            entity.runCommand('/ride @s stop_riding');
        }
        if (event === "find_jukebox") {
            if (!entity.isValid()) return;
            // world.sendMessage("There is a music box nearby");

            let time = 0;
            const find_block = system.runInterval(() => {
                try {
                    if (!entity.isValid()) {
                        system.clearRun(find_block);
                        return;
                    }
                    if (time >= 2) {
                        // world.sendMessage("没在播放");
                        system.clearRun(find_block);
                        return;
                    }
                    if (entity.isValid()) {
                        const blocks = getNearbyBlocks(entity, 8);

                        for (const block of blocks) {
                            if (block.typeId === "minecraft:jukebox") {
                                const inventory = block.getComponent("inventory");
                                const jukeboxItem = inventory?.container ? inventory.container.getItem(0) : null;
                                if (jukeboxItem && jukeboxItem.typeId.includes("music")) {
                                    // world.sendMessage("在播放！开始跳舞!!!");
                                    entity.triggerEvent("is_dance");
                                    entity.setProperty('ph_wild:state', 1);
                                    system.clearRun(find_block);
                                    return;
                                }
                            }
                        }
                    }
                    time += 1;
                } catch (error) {
                    // world.sendMessage("发生错误：" + error.message);
                    system.clearRun(find_block);
                }
            });
        }
        if (event == "is_find") {
            system.runTimeout(() => {
                if (!entity.isValid()) return;
                try {
                    const block = entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 1, z: entity.location.z });

                    if (block && block.typeId == "minecraft:grass_block") {
                        const items = [
                            "minecraft:beetroot_seeds",
                            "minecraft:melon_seeds",
                            "minecraft:pumpkin_seeds",
                            "minecraft:wheat_seeds"
                        ];

                        const randomItem = items[Math.floor(Math.random() * items.length)];
                        entity.dimension.spawnItem(new ItemStack(randomItem, 1), entity.location);
                    }
                } catch { }
            }, 40);
        }
        if (event == "eat_item") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (!entity.isValid()) {
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 2.0) {
                        entity.runCommand('/replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.setProperty("ph_wild:seed", 0);
                        entity.setProperty('ph_wild:eat_item', false);
                        system.clearRun(eat);
                        return;
                    }

                    // 随机生成心型粒子的矢量位置
                    const randomOffset = {
                        x: (Math.random() * 0.8) - 0.8, // -2 到 2 之间的随机数
                        y: (Math.random() * 0.8) - 0.8,
                        z: (Math.random() * 0.8) - 0.8
                    };

                    const particleLocation = {
                        x: entity.location.x + randomOffset.x,
                        y: entity.location.y + randomOffset.y,
                        z: entity.location.z + randomOffset.z
                    };

                    entity.dimension.playSound('random.eat', entity.location);
                    entity.dimension.spawnParticle('minecraft:heart_particle', particleLocation);
                    time += 0.25;
                } catch { }
            }, 5);
        }
        if (event == "drop_item") {
            const seed = entity.getProperty("ph_wild:seed");
            if (seed > 0) {
                entity.setProperty("ph_wild:scared", false);
                entity.setProperty("ph_wild:seed", 0);

                const seedItems = {
                    1: "minecraft:beetroot_seeds",
                    2: "minecraft:melon_seeds",
                    3: "minecraft:pumpkin_seeds",
                    4: "minecraft:wheat_seeds"
                };

                const seedItem = seedItems[seed];
                if (seedItem) {
                    entity.dimension.spawnItem(new ItemStack(seedItem, 1), entity.location);
                }
            }
        }
    }
    if (entity.typeId == "ph_wild:gorilla") {
        if (event == "update") {
            if (!entity.isValid()) return;
            const groupIdValue = entity.getProperty('ph_wild:group_id');
            const isBaby = entity.getComponent('is_baby');

            if (groupIdValue > 0) {
                const nearbyEntities = entity.dimension.getEntities({
                  location: entity.location,
                  closest: 1,
                  maxDistance: 24,
                  type: 'ph_wild:gorilla.silverback',
                  propertyOptions: [{ propertyId: 'ph_wild:group_id', value: { equals: groupIdValue } }]
                });
    
                if (nearbyEntities.length > 0) {
                  for (const nearbyEntity of nearbyEntities) {
                    if (!isBaby) {
                        setTarget(entity, nearbyEntity);
                    }
                  }
                } else {
                    if (Math.random() < 0.5) {
                        entity.setProperty('ph_wild:group_id', groupIdValue);
                    } else {
                        entity.setProperty('ph_wild:group_id', 0);
                        entity.triggerEvent("add:remove_target");
                        if (Math.random() < 0.25 && !isBaby) {
                            entity.triggerEvent("transfor_into_silverback");
                        }
                    }
                }
            }
        };
        if (event == "idle_roll_state") {
            if (!entity.isValid()) return;
            const viewDirection = entity.getViewDirection();

            const magnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
            const normalizedDirection = {
                x: viewDirection.x / magnitude,
                y: 0,
                z: viewDirection.z / magnitude,
            };

            const impulseDirection = {
                x: normalizedDirection.x * 1,
                y: 0.1,
                z: normalizedDirection.z * 1,
            };
        
            entity.applyImpulse(impulseDirection);
        };
        if (event == "idle_eat_state") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }
                    const animState = entity.getProperty('ph_wild:anim_state');
                    const foodType = entity.getProperty('ph_wild:food_type');
                    if (time < 1.0 && animState != 13) {
                        const viewDirection = entity.getViewDirection();
                        const spawnLocation = {
                            x: entity.location.x + viewDirection.x * 1,
                            y: entity.location.y + 1,
                            z: entity.location.z + viewDirection.z * 1,
                        };
                        entity.dimension.spawnItem(new ItemStack(entity_id.food_list[foodType-1], 1), spawnLocation);
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 1.0) {
                        if (foodType == 2 || foodType == 3) {
                            const viewDirection = entity.getViewDirection();
                            const spawnLocation = {
                                x: entity.location.x + viewDirection.x * 1,
                                y: entity.location.y + 1,
                                z: entity.location.z + viewDirection.z * 1,
                            };
                            if (foodType == 2) entity.dimension.spawnItem(new ItemStack('minecraft:melon_seeds', 1), spawnLocation);
                            if (foodType == 3) entity.dimension.spawnItem(new ItemStack('ph_wild:banana_peel', 1), spawnLocation);
                        }
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.dimension.playSound("random.burp", entity.location);
                        entity.triggerEvent('add:anim_state.0');
                        system.clearRun(eat);
                        return;
                    }
                    entity.dimension.playSound('random.eat', entity.location);
                    time += 0.2;
                } catch { }
            }, 4)
        };
        if (event == "grow_up") {
            entity.runCommand('/ride @s stop_riding');
        };
    }
    if (entity.typeId == "ph_wild:gorilla.silverback") {
        if (event == "update") {
            if (!entity.isValid()) return;
            const groupIdValue = entity.getProperty('ph_wild:group_id');

            const groupSize = entity.dimension.getEntities({
              location: entity.location,
              closest: 4,
              maxDistance: 16,
              type: 'ph_wild:gorilla',
              propertyOptions: [{ propertyId: 'ph_wild:group_id', value: { equals: groupIdValue } }]
            });
            if (groupSize.length < 8) {
                const nearbyEntities = entity.dimension.getEntities({
                  location: entity.location,
                  closest: Math.max(0, 5 - Math.max(0, groupSize.length - 3)),
                  maxDistance: 16,
                  type: 'ph_wild:gorilla',
                  propertyOptions: [{ propertyId: 'ph_wild:group_id', value: { equals: 0 } }]
                });
                if (nearbyEntities.length > 0) {
                  for (const nearbyEntity of nearbyEntities) {
                    nearbyEntity.setProperty('ph_wild:group_id', groupIdValue);
    
                    entity.dimension.spawnParticle('ph_wild:group_assigned', entity.location);
                    entity.dimension.spawnParticle('ph_wild:group_assigned', nearbyEntity.location);
    
                    system.runTimeout(() => {
                        nearbyEntity.triggerEvent("update");
                    }, 1);
                  }
                } else {
                }
            }
        };
        if (event == "add:has_target") {
            if (!entity.isValid()) return;
            entity.dimension.playSound('ph_wild.gorilla.silverback.warning', entity.location);
        };
        if (event == "move_to_threat.stare_state" || event == "idle_chest_state") {
            if (!entity.isValid()) return;

            for (const player of entity.dimension.getPlayers({ location: entity.location, maxDistance: 32 })) {
                playDistantSound(entity, player, 'ph_wild.gorilla.silverback.chest', 0, 1, 4, 32, 1);
            }
        };
        if (event == "idle_roll_state") {
            if (!entity.isValid()) return;
            const viewDirection = entity.getViewDirection();

            const magnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
            const normalizedDirection = {
                x: viewDirection.x / magnitude,
                y: 0,
                z: viewDirection.z / magnitude,
            };

            const impulseDirection = {
                x: normalizedDirection.x * 2,
                y: 0.1,
                z: normalizedDirection.z * 2,
            };
        
            entity.applyImpulse(impulseDirection);
        };
        if (event == "idle_eat_state") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }
                    const animState = entity.getProperty('ph_wild:anim_state');
                    const foodType = entity.getProperty('ph_wild:food_type');
                    if (time < 1.0 && animState != 13) {
                        const viewDirection = entity.getViewDirection();
                        const spawnLocation = {
                            x: entity.location.x + viewDirection.x * 1,
                            y: entity.location.y + 1,
                            z: entity.location.z + viewDirection.z * 1,
                        };
                        entity.dimension.spawnItem(new ItemStack(entity_id.food_list[foodType-1], 1), spawnLocation);
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 1.0) {
                        if (foodType == 2 || foodType == 3) {
                            const viewDirection = entity.getViewDirection();
                            const spawnLocation = {
                                x: entity.location.x + viewDirection.x * 1,
                                y: entity.location.y + 1,
                                z: entity.location.z + viewDirection.z * 1,
                            };
                            if (foodType == 2) entity.dimension.spawnItem(new ItemStack('minecraft:melon_seeds', 1), spawnLocation);
                            if (foodType == 3) entity.dimension.spawnItem(new ItemStack('ph_wild:banana_peel', 1), spawnLocation);
                        }
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.dimension.playSound("random.burp", entity.location);
                        entity.triggerEvent('add:anim_state.0');
                        system.clearRun(eat);
                        return;
                    }
                    entity.dimension.playSound('random.eat', entity.location);
                    time += 0.2;
                } catch { }
            }, 4)
        };
    }
    if (entity.typeId == "ph_wild:elephant") {
        if (!entity.isValid()) return;

        if (event == "blocked:perform_charge_attack") {
            elephantAttack(entity, null, 0, 0, 4, false);
        };
        if (event == "charge_to_attack_trumpet_state") {
            for (const player of entity.dimension.getPlayers({ location: entity.location, maxDistance: 32 })) {
                playDistantSound(entity, player, 'ph_wild.elephant.trumpet.agressive', 0, 1, 16, 32, 1);
            }
        };
        if (event == "idle_trumpet_state") {
            const isBaby = entity.getComponent("is_baby");

            for (const player of entity.dimension.getPlayers({ location: entity.location, maxDistance: (isBaby ? 16 : 32) })) {
                playDistantSound(entity, player, 'ph_wild.elephant.trumpet.passive', 0, (isBaby ? 0.5 : 1), (isBaby ? 4 : 8), (isBaby ? 16 : 32), (isBaby ? 2 : 1));
            }
        };
        if (event == "idle_eat_state") {
            entity.dimension.playSound("ph_wild.elephant.eat", entity.location);
        };
        if (event == "idle_feed_state") {
            let time = 0;
            let consumed_item = false;
            const eat = system.runInterval(() => {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }

                    if (time >= 2.0 && !consumed_item) {
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        consumed_item = true;
                    }
                    if (time >= 3.0) {
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.triggerEvent('add:anim_state.0');
                        system.clearRun(eat);
                        return;
                    }
                    time += 0.2;
            }, 4)
            entity.dimension.playSound("ph_wild.elephant.eat", entity.location);
        };
        if (event == "add:carpet") {
            const inventory = entity.getComponent("inventory");
            const slot = inventory.container.getSlot(1);

            const carpetType = {
                "minecraft:black_carpet": 1,
                "minecraft:blue_carpet": 2,
                "minecraft:brown_carpet": 3,
                "minecraft:cyan_carpet": 4,
                "minecraft:gray_carpet": 5,
                "minecraft:green_carpet": 6,
                "minecraft:light_blue_carpet": 7,
                "minecraft:light_gray_carpet": 8,
                "minecraft:lime_carpet": 9,
                "minecraft:magenta_carpet": 10,
                "minecraft:orange_carpet": 11,
                "minecraft:pink_carpet": 12,
                "minecraft:purple_carpet": 13,
                "minecraft:red_carpet": 14,
                "minecraft:white_carpet": 15,
                "minecraft:yellow_carpet": 16,
            };

            entity.setProperty('ph_wild:skin', carpetType[slot.typeId]);
        };
        if (event == "remove:carpet") {
            entity.setProperty('ph_wild:skin', 0);
        };
        if (event == "has_rider.run_state") {
            let time = 0;
            let cooldown = 0;
            const run_attack = system.runInterval(() => {
                if (!entity.isValid()) {
                    system.clearRun(run_attack);
                    return;
                }
                if (time >= 25) {
                    system.clearRun(run_attack);
                    entity.setProperty('ph_wild:exhausted', false);
                    return;
                }

                const isExausted = entity.getProperty('ph_wild:exhausted');

                if (!isExausted && time >= 15) {
                    const animState = entity.getProperty('ph_wild:anim_state');
                    if (animState === 2 || animState === 1) {
                        entity.triggerEvent('has_rider.walk_state');
                    }
                    entity.setProperty('ph_wild:exhausted', true);
                };

                const velocity = entity.getVelocity();
                const speed = Math.sqrt(velocity.x ** 2 + velocity.z ** 2) * 20;

                if (!isExausted && speed >= 7 && time >= cooldown) {
                    const viewDirection = entity.getViewDirection();
                    const location = entity.location;
    
                    const boxSize = 3;
                    const distance = 5;

                    const centerX = location.x + viewDirection.x * 1;
                    const centerY = location.y + 1;
                    const centerZ = location.z + viewDirection.z * 1;
    
                    const nearbyTargets = entity.dimension.getEntities({
                        location: { x: centerX, y: centerY, z: centerZ },
                        maxDistance: boxSize,
                        closest: 3,
                        excludeTypes: ['item', 'xp_orb'],
                    }).filter((target) => target.id !== entity.id);
                    
                    function hasLineOfSight(target) {
                        const targetLocation = target.location;
                        const rayResult = entity.dimension.getBlockFromRay(
                            entity.location,
                            { x: targetLocation.x - location.x, y: targetLocation.y - location.y, z: targetLocation.z - location.z },
                            { maxDistance: distance, ignoreBlockCollision: false }
                        );
    
                        return rayResult === undefined;
                    }
    
                    const visibleTargets = nearbyTargets.filter((target) => {
                        const isRiddenEntity = entity.hasComponent("rideable") 
                            ? entity.getComponent("rideable").getRiders().some(rider => rider.id === target.id) 
                            : false;

                        return !isRiddenEntity && hasLineOfSight(target);
                    });

                    let executedSuccessfully = false;

                    visibleTargets.forEach((target) => {
                        executedSuccessfully = elephantAttack(entity, target, 2.0, 0.6, 1, true);
                    });
                    if (executedSuccessfully) {
                        entity.playAnimation('animation.ph_wild.elephant.fast_attack', { controller: "fast_attack", nextState: "default", stopExpression: "q.all_animations_finished" });
                        cooldown = time + 0.6;
                    }
                }
                time += 0.25;
            }, 5);
        };
    }
    if (entity.typeId == "ph_wild:red_panda") {
        if (event == "idle_roll_state") {
            if (!entity.isValid()) return;
            const viewDirection = entity.getViewDirection();

            const magnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
            const normalizedDirection = {
                x: viewDirection.x / magnitude,
                y: 0,
                z: viewDirection.z / magnitude,
            };

            const impulseDirection = {
                x: normalizedDirection.x * 1,
                y: 0.1,
                z: normalizedDirection.z * 1,
            };
        
            entity.applyImpulse(impulseDirection);
        };
        if (event == "idle_feed_state") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 2.0) {
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.setProperty('ph_wild:anim_state', 0);
                        entity.setProperty('ph_wild:is_trusting', true);
                        world.playSound("random.burp", entity.location);
                        system.clearRun(eat);
                        return;
                    }
                    entity.dimension.playSound('random.eat', entity.location);
                    time += 0.2;
                } catch { }
            }, 4)
        };
        if (event == "found_block") {
            const blocks = getNearbyBlocks(entity, 4);

            for (const block of blocks) {
                if (block.typeId === "minecraft:oak_log") {
                    entity.teleport({ x: block.location.x + 1.25, y: block.location.y, z: block.location.z + 0.5 });
                    entity.setProperty('ph_wild:is_climbing', true);
                    return;
                }
            }
        };
        if (event == "climb_state") {
        };
    }
    if (entity.typeId == "ph_wild:grizzly_bear") {
        if (event == "idle_eat_state") {
            let time = 0;
            const eat = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(eat);
                        return;
                    }
                    const animState = entity.getProperty('ph_wild:anim_state');
                    const foodType = entity.getProperty('ph_wild:food_type');
                    if (time < 1.5 && animState != 15) {
                        const viewDirection = entity.getViewDirection();
                        const spawnLocation = {
                            x: entity.location.x + viewDirection.x * 1,
                            y: entity.location.y + 1,
                            z: entity.location.z + viewDirection.z * 1,
                        };
                        entity.dimension.spawnItem(new ItemStack(entity_id.food_list[foodType-1], 1), spawnLocation);
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        system.clearRun(eat);
                        return;
                    }
                    if (time >= 1.5) {
                        if (foodType == 2 || (foodType >= 6 && foodType <= 14) || (foodType >= 18 && foodType <= 20) || (foodType >= 22 && foodType <= 23) || (foodType >= 25 && foodType <= 26) || (foodType >= 29 && foodType <= 34)) {
                            const viewDirection = entity.getViewDirection();
                            const spawnLocation = {
                                x: entity.location.x + viewDirection.x * 1,
                                y: entity.location.y + 1,
                                z: entity.location.z + viewDirection.z * 1,
                            };
                            entity.dimension.spawnItem(new ItemStack('minecraft:bone', 1), spawnLocation);
                        }
                        entity.runCommand('replaceitem entity @s slot.weapon.mainhand 0 air');
                        entity.dimension.playSound("random.burp", entity.location);
                        entity.setProperty('ph_wild:anim_state', 0);
                        system.clearRun(eat);
                        return;
                    }
                    entity.dimension.playSound('random.eat', entity.location);
                    time += 0.2;
                } catch { }
            }, 4)
        };
        if (event == "idle_stand_state") {
            entity.dimension.playSound("ph_wild.grizzly_bear.idle_stand", entity.location);
        };
        if (event == "shake_body_state") {
            let time = 0;
            let shakedOff = false;
            const isSnowCovered = entity.getProperty('ph_wild:is_snow_covered');
            const isWet = entity.getProperty('ph_wild:is_wet');
            const drop = system.runInterval(() => {
                try {
                    if (entity.isValid() == false) {
                        system.clearRun(drop);
                        return;
                    }
                    if (isSnowCovered) {
                        if (time >= 0.2 && !shakedOff) {
                            entity.dimension.playSound("hit.powder_snow", entity.location);
                            entity.dimension.spawnParticle('ph_wild:snow_shake_1', entity.location);
                        }
                        if (time >= 2.0 && !shakedOff) {
                            const itemLocation = {
                                x: entity.location.x,
                                y: entity.location.y + 1.2,
                                z: entity.location.z
                            };
                            const snowballCount = Math.floor(Math.random() * 3) + 1;
                            const snowball = new ItemStack("minecraft:snowball", snowballCount);
                            entity.dimension.spawnItem(snowball, itemLocation);
                            entity.setProperty('ph_wild:is_snow_covered', false);
                            shakedOff = true;
                        }
                    }
                    if (isWet) {
                        if (time == 0.2) {
                            entity.dimension.playSound("mob.wolf.shake", entity.location);
                        }
                        if (time >= 0.2 && !shakedOff) {
                            entity.dimension.spawnParticle('ph_wild:water_shake_1', entity.location);
                        }
                        if (time >= 2.0 && !shakedOff) {
                            entity.setProperty('ph_wild:is_wet', false);
                            shakedOff = true;
                        }
                    }
                    if (time >= 3.0) {
                        entity.setProperty('ph_wild:anim_state', 0);
                        entity.setProperty('ph_wild:is_snow_covered', false);
                        entity.setProperty('ph_wild:is_wet', false);
                        entity.setProperty('ph_wild:shake_body', false);
                        system.clearRun(drop);
                        return;
                    }
                    time += 0.2;
                } catch { }
            }, 4)
        };
        if (event == "has_rider.attack") {
            entity.playAnimation('animation.ph_wild.bear.claw_attack', { controller: "attack", nextState: "default", stopExpression: "q.all_animations_finished" });
            entity.dimension.playSound("ph_wild.grizzly_bear.idle", entity.location);
            const viewDirection = entity.getViewDirection();
            const location = entity.location;

            const boxSize = 3;
            const distance = 3;

            const centerX = location.x + viewDirection.x * 1;
            const centerY = location.y + 1;
            const centerZ = location.z + viewDirection.z * 1;

            const nearbyTargets = entity.dimension.getEntities({
                location: { x: centerX, y: centerY, z: centerZ },
                maxDistance: boxSize,
                closest: 3,
                excludeTypes: ['item', 'xp_orb'],
            }).filter((target) => target.id !== entity.id);
            
            function hasLineOfSight(target) {
                const targetLocation = target.location;
                const rayResult = entity.dimension.getBlockFromRay(
                    entity.location,
                    { x: targetLocation.x - location.x, y: targetLocation.y - location.y, z: targetLocation.z - location.z },
                    { maxDistance: distance, ignoreBlockCollision: false }
                );

                return rayResult === undefined;
            }

            const visibleTargets = nearbyTargets.filter((target) => {
                const isRiddenEntity = entity.hasComponent("rideable") 
                    ? entity.getComponent("rideable").getRiders().some(rider => rider.id === target.id) 
                    : false;

                return !isRiddenEntity && hasLineOfSight(target);
            });

            visibleTargets.forEach((target) => {
                system.runTimeout(() => {
                    if (entity.isValid()) {
                        target.applyDamage(6, { cause: "ramAttack", damagingEntity: entity });
                        viewDirectionKnockback(entity, target, 1.2, 0.4);
                    }
                }, 8);
            });
        };
        if (event == "remove_snow") {
            entity.dimension.playSound("use.snow", entity.location);
        };
    }
    if (entity.typeId == "ph_wild:nature_journal") {
        if (event == "minecraft:entity_spawned") {
            entity.dimension.playSound('ph_wild.nature_journal.open', entity.location);
        };
        if (event == "add_close_timer") {
            entity.dimension.playSound('ph_wild.nature_journal.close', entity.location);
        };
        if (event == "book_closed") {
            const current_page = entity.getProperty('ph_wild:current_page');
            const storedData = {
                currentPage: current_page,
            }
        
            const storeStrData = JSON.stringify(storedData);

            const item = new ItemStack('ph_wild:nature_journal');
            item.setDynamicProperty('ph_wild:item_data', storeStrData);

            const lore = [
              `§r§7Page ${current_page} of 40`,
            ];

            item.setLore(lore);

            const spawnLocation = {
                x: entity.location.x,
                y: entity.location.y + 1,
                z: entity.location.z,
            };
            entity.dimension.spawnItem(item, spawnLocation);

            entity.remove();
        };
    }
}, { entityTypes: Object.keys(entity_list) } );

world.afterEvents.entityHurt.subscribe((xm) => {
    const damageSource = xm.damageSource;
    const damagingEntity = xm.damageSource.damagingEntity;
    const entity = xm.hurtEntity;
    const entity_id = entity_list[entity?.typeId];

    if (entity.isValid() == false) return;

    if (entity.typeId == "ph_wild:lizard") {
        if (entity.isValid() == false) return;
        const tail = entity.getProperty('ph_wild:tail');
        if (!tail) return;

        try {
            entity.setProperty('ph_wild:tail', false);
            const skin_id = entity.getProperty('ph_wild:skin');
            const tail_item = new ItemStack(entity_id.loot.replace("1", `${skin_id}`), 1);
            entity.dimension.spawnItem(tail_item, entity.location);

        } catch { }
        const handleTeleport = (block, particle, sound, anim, hideEvent) => {
            entity.dimension.spawnParticle(particle, entity.location);
            entity.dimension.playSound(sound, entity.location);
            entity.teleport({ x: block.location.x + 0.5, y: block.location.y + 1, z: block.location.z + 0.5 }, { keepVelocity: false });
            entity.triggerEvent(anim);
            system.runTimeout(() => {
                if (entity.isValid()) {
                    entity.teleport({ x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 }, { keepVelocity: false });
                    entity.triggerEvent(hideEvent);
                }
            }, 18);
        };

        let time = 0;
        system.runTimeout(() => {
            if (!entity.isValid()) return;
            const hide = system.runInterval(() => {
                if (!entity.isValid() || time >= 1.5) {
                    system.clearRun(hide);
                    return;
                }
                if (Math.random() < 0.6) {
                    const blocks = [
                        entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y, z: entity.location.z }),
                        entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 1, z: entity.location.z })
                    ];
                    const grass = ["fern", "tall_fern", "short_grass", "tall_grass"];
                    const processBlock = (block) => {
                        if (grass.some(grassType => block.typeId.includes(grassType))) {
                            handleTeleport(block, "", "ph_wild.lizard.dig_down", "anim_1", "add:hide");
                            system.clearRun(hide);
                        } else if (block.typeId.includes("leaves")) {
                            const particle = block.typeId === "minecraft:cherry_leaves" ? "ph_wild:lizard_2" : "ph_wild:lizard_1";
                            handleTeleport(block, particle, "ph_wild.lizard.dig_down", "anim_1", "add:hide");
                            system.clearRun(hide);
                        } else if (["minecraft:sand", "minecraft:red_sand"].includes(block.typeId)) {
                            const particle = block.typeId === "minecraft:sand" ? "ph_wild:lizard_3" : "ph_wild:lizard_4";
                            handleTeleport(block, particle, "ph_wild.lizard.dig_down", "anim_1", "add:hide");
                            system.clearRun(hide);
                        }
                    };
                    blocks.forEach(processBlock);
                }
                time += 0.2;
            }, 4);
        }, 30);
    }
    if (entity.typeId == "ph_wild:jellyfish") {
        if (damageSource.cause == "entityAttack") {
            damageSource.damagingEntity.addEffect("poison", 200, { amplifier: 2 });
        }
    }
    if (damagingEntity?.typeId == "ph_wild:snake") {
        const skin_id = damagingEntity.getProperty('ph_wild:skin');
        if (skin_id == 1) {
            entity.addEffect("poison", 800, { amplifier: 3 });
            entity.addEffect("nausea", 600, { amplifier: 5 });
            entity.addEffect("slowness", 400, { amplifier: 2 });
        }
        if (skin_id == 2) {
            entity.addEffect("poison", 1200, { amplifier: 5 });
            entity.addEffect("nausea", 600, { amplifier: 5 });
            entity.addEffect("slowness", 400, { amplifier: 5 });
            entity.addEffect("blindness", 600, { amplifier: 0 });
        }
        if (skin_id == 3) {
            entity.addEffect("poison", 400, { amplifier: 1 });
            entity.addEffect("nausea", 600, { amplifier: 5 });
        }
        if (skin_id == 4) {
            entity.addEffect("nausea", 600, { amplifier: 5 });
            entity.addEffect("slowness", 600, { amplifier: 1 });
        }
        if (skin_id == 5) {
            entity.addEffect("nausea", 600, { amplifier: 5 });
        }
    }
    if (damagingEntity?.typeId == "ph_wild:stingray") {
        entity.addEffect("poison", 400, { amplifier: 1 });
        entity.addEffect("slowness", 400, { amplifier: 2 });
    }
    if (damagingEntity?.typeId == "ph_wild:bison") {
        if (entity instanceof Player) {
            entity.applyKnockback(Math.floor(Math.random() * 7) - 3, Math.floor(Math.random() * 7) - 3, 1.5, 0.5);
        }
    }
    if (entity.typeId == "ph_wild:gorilla" && damagingEntity?.typeId != "ph_wild:gorilla.silverback") {
        if (!entity.isValid()) return;
        const groupIdValue = entity.getProperty('ph_wild:group_id');

        if (groupIdValue > 0) {
            const nearbyEntities = entity.dimension.getEntities({
              location: entity.location,
              closest: 1,
              maxDistance: 32,
              type: 'ph_wild:gorilla.silverback',
              propertyOptions: [{ propertyId: 'ph_wild:group_id', value: { equals: groupIdValue } }]
            });
            if (nearbyEntities.length > 0) {
              for (const nearbyEntity of nearbyEntities) {
                setTarget(nearbyEntity, damagingEntity);
                setTarget(entity, nearbyEntity);
                nearbyEntity.setProperty('ph_wild:has_target', true);
                entity.setProperty('ph_wild:has_target', false);
              }
            } else {
                entity.triggerEvent("add:remove_target");
                system.runTimeout(() => {
                    setTarget(entity, damagingEntity);
                }, 1);
            }
        }
    }
    if (damagingEntity?.typeId == "ph_wild:gorilla.silverback") {
        viewDirectionKnockback(damagingEntity, entity, 1.5, 0.75);
    }
    if (damagingEntity?.typeId == "ph_wild:gorilla") {
        viewDirectionKnockback(damagingEntity, entity, 1.25, 0.5);
    }
    if (damagingEntity?.typeId == "ph_wild:elephant" && damageSource.cause == 'entityAttack') {
        damagingEntity.triggerEvent("remove:perform_charge_attack");
        elephantAttack(damagingEntity, entity, 3.5, 0.8, 1, true);
    }
    if (entity.typeId == "ph_wild:elephant") {
        const is_baby = entity.getComponent('is_baby');
        if (is_baby) return;

        entity.triggerEvent("add:has_target");
    }
    if (entity.typeId == "ph_wild:red_panda" && damagingEntity?.typeId == "minecraft:player") {
        entity.setProperty('ph_wild:is_trusting', false);
    }
    if (damagingEntity?.typeId == "ph_wild:grizzly_bear") {
        const animState = damagingEntity.getProperty('ph_wild:anim_state');
        if (animState == 5) {
            viewDirectionKnockback(damagingEntity, entity, 1.4, 0.6);
        }
    }
    if (entity.typeId == "ph_wild:grizzly_bear") {
        const animState = entity.getProperty('ph_wild:anim_state');
        if (animState >= 6 && animState <= 15) {
            entity.triggerEvent("add:anim_state.0");
        }
    }
});



world.beforeEvents.playerInteractWithEntity.subscribe((entityInteract) => {
    const { itemStack, player, target } = entityInteract;

    const itemId = itemStack?.typeId;
    const entity = target?.typeId;

    const entity_id = entity_list[entity];

    const animState = target.getProperty('ph_wild:anim_state');

    if (entity == "ph_wild:elephant") {
        if ((entity_id.food_list.includes(itemId) && animState != 0) || (animState > 2 && animState != 4)) {
            entityInteract.cancel = true;
        }
    }
    if (entity == "ph_wild:gorilla.silverback" || entity == "ph_wild:gorilla") {
        if (entity_id.food_list.includes(itemId) && animState != 0) {
            entityInteract.cancel = true;
        }
    }
    if (entity == "ph_wild:hippo") {
        if (entity_id.food_list.includes(itemId) && animState == 13) {
            entityInteract.cancel = true;
        }
    }

    //console.warn(`ItemId: ${itemStack.typeId}\n EntityId: ${target.typeId}`);

    if (!itemId) return;
    if (itemId.replace('_spawn_egg', '') == entity) {
        entityInteract.cancel = true;
        system.run(() => {
            const spawn_entity = target.dimension.spawnEntity(target.typeId, target.location);
            try {
                spawn_entity.triggerEvent("minecraft:entity_born");
            } catch {
                try {
                    spawn_entity.triggerEvent("spawn_baby");
                } catch {
                    try {
                        spawn_entity.triggerEvent("baby");
                    } catch {
                        try {
                            spawn_entity.triggerEvent("entity_born");
                        } catch {
                        }
                    }
                }
            }
        });
    };
});
world.afterEvents.playerInteractWithEntity.subscribe((entityInteract) => {
    const { itemStack, player, target } = entityInteract;

    const itemId = itemStack?.typeId;
    const entity = target?.typeId;

    const entity_id = entity_list[entity];

    const animState = target.getProperty('ph_wild:anim_state');

    if (entity == "ph_wild:elephant") {
        const leftTusk = target.getProperty('ph_wild:left_tusk');
        const rightTusk = target.getProperty('ph_wild:right_tusk');
        if (["ph_wild:reinforced_copper_tusk", "ph_wild:reinforced_gold_tusk", "ph_wild:reinforced_iron_tusk", "ph_wild:reinforced_diamond_tusk", "ph_wild:reinforced_netherite_tusk"].includes(itemId) && (leftTusk == 0 || rightTusk == 0)) {
            const tuskLevels = {
              "ph_wild:reinforced_copper_tusk": 2,
              "ph_wild:reinforced_gold_tusk": 3,
              "ph_wild:reinforced_iron_tusk": 4,
              "ph_wild:reinforced_diamond_tusk": 5,
              "ph_wild:reinforced_netherite_tusk": 6,
            };
        
            const newTuskValue = tuskLevels[itemId];
            const tuskSide = (leftTusk == 0 && rightTusk == 0) ? (Math.random() <= 0.5 ? 'left_tusk' : 'right_tusk') : (leftTusk == 0 && rightTusk > 0) ? 'left_tusk' : 'right_tusk';
            target.setProperty(`ph_wild:${tuskSide}`, newTuskValue);
        
            const inv = player.getComponent("inventory").container;
            const selectedSlot = player.selectedSlotIndex;
            const currentItem = inv.getItem(selectedSlot);
            const itemDurability = currentItem.getComponent("durability");
            inv.setItem(selectedSlot, undefined);

            target.dimension.playSound('mob.horse.armor', target.location, { pitch: 0.8, volume: 1.0, });

            target.setProperty(`ph_wild:${tuskSide}_durability`, (itemDurability.maxDurability - itemDurability.damage));
        }
        if (["minecraft:shears"].includes(itemId) && (leftTusk > 1 || rightTusk > 1)) {
            const tuskLevels = {
                2: "ph_wild:reinforced_copper_tusk",
                3: "ph_wild:reinforced_gold_tusk",
                4: "ph_wild:reinforced_iron_tusk",
                5: "ph_wild:reinforced_diamond_tusk",
                6: "ph_wild:reinforced_netherite_tusk",
            };
            const tuskSide = (leftTusk > 1 && rightTusk > 1) ? (Math.random() <= 0.5 ? 'left_tusk' : 'right_tusk') : (leftTusk > 1 && rightTusk <= 1) ? 'left_tusk' : 'right_tusk';
            const tuskValue = target.getProperty(`ph_wild:${tuskSide}`);
            const tuskItemName = tuskLevels[tuskValue];

            const viewDirection = target.getViewDirection();
            const spawnLocation = {
                x: target.location.x + viewDirection.x * 2,
                y: target.location.y + (animState == 4 ? 0.5 : 1.5),
                z: target.location.z + viewDirection.z * 2,
            };

            const tuskItem = new ItemStack(tuskItemName, 1);
            const itemDurability = tuskItem.getComponent("durability");
            const itemDamage = (itemDurability.maxDurability - target.getProperty(`ph_wild:${tuskSide}_durability`));
            itemDurability.damage = itemDamage;

            target.dimension.spawnItem(tuskItem, spawnLocation);

            target.dimension.playSound('mob.horse.armor', target.location, { pitch: 1.0, volume: 1.0, });

            target.setProperty(`ph_wild:${tuskSide}`, 0);
            target.setProperty(`ph_wild:${tuskSide}_durability`, 0);
        }
        if (entity_id.food_list.includes(itemId) && animState != 14) {
            target.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${itemId}`);
        }
    }
    if (entity == "ph_wild:gorilla.silverback" || entity == "ph_wild:gorilla") {
        if (entity_id.food_list.includes(itemId) && animState != 13) {
            target.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${itemId}`);
        }
    }
    if (entity == "ph_wild:hippo") {
        if (entity_id.food_list.includes(itemId) && animState != 13) {
            target.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${itemId}`);
        }
    }
    if (entity == "ph_wild:red_panda") {
        if (["minecraft:apple", "minecraft:carrot", "minecraft:potato", "minecraft:beetroot", "minecraft:sweet_berries", "minecraft:melon_slice", "minecraft:bamboo"].includes(itemId) && animState != 2) {
            target.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${itemId}`);
            target.setProperty('ph_wild:anim_state', 2);
        }
    }
    if (entity == "ph_wild:nature_journal") {
        const current_page = target.getProperty('ph_wild:current_page');
        const is_sneaking = player.isSneaking;

        if (!is_sneaking) {
            if (current_page < 40) {
                target.dimension.playSound('item.book.page_turn', target.location);
                target.setProperty('ph_wild:next_page', 1);

                target.setProperty('ph_wild:current_page', current_page + 1);
                system.runTimeout(() => {
                    if (!target.isValid()) return;
                    try {
                        target.setProperty('ph_wild:next_page', 0);
                    } catch { }
                }, 8);
            }
            if (current_page == 40) {
                target.dimension.playSound('ph_wild.nature_journal.flipping', target.location);
                target.setProperty('ph_wild:next_page_start', 1);

                let time = 0;
                const loop = system.runInterval(() => {
                    const current_page = target.getProperty('ph_wild:current_page');
                    if (!target.isValid() || time >= 0.8 || current_page == 34) {
                        target.setProperty('ph_wild:next_page_start', 0);
                        target.setProperty('ph_wild:current_page', 0);
                        system.clearRun(loop);
                        return;
                    }
                    target.setProperty('ph_wild:current_page', current_page - 1);
                    time += 0.05;
                });
            }
        };
        if (is_sneaking) {
            if (current_page > 0) {
                target.dimension.playSound('item.book.page_turn', target.location);
                target.setProperty('ph_wild:previous_page', 1);

                target.setProperty('ph_wild:current_page', current_page - 1);
                system.runTimeout(() => {
                    if (!target.isValid()) return;
                    try {
                        target.setProperty('ph_wild:previous_page', 0);
                    } catch { }
                }, 8);
            }
            if (current_page == 0) {
                target.dimension.playSound('ph_wild.nature_journal.flipping', target.location);
                target.setProperty('ph_wild:previous_pag_end', 1);

                let time = 0;
                const loop = system.runInterval(() => {
                    const current_page = target.getProperty('ph_wild:current_page');
                    if (!target.isValid() || time >= 0.8 || current_page == 10) {
                        target.setProperty('ph_wild:previous_pag_end', 0);
                        target.setProperty('ph_wild:current_page', 40);
                        system.clearRun(loop);
                        return;
                    }
                    target.setProperty('ph_wild:current_page', current_page + 1);
                    time += 0.05;
                });
            }
        };
    }
});

//world.afterEvents.entityHitEntity.subscribe(xm => {
//    const { entity } = xm;
//});


world.afterEvents.projectileHitBlock.subscribe((pEvent) => {
  const { projectile, source } = pEvent;

  if (projectile.typeId == "ph_wild:custom_splash_potion") {
    const StrData = projectile.getDynamicProperty('ph_wild:projectile_data');

    if (StrData) {
        const itemSavedData = JSON.parse(StrData);

        source.dimension.playSound(itemSavedData.hit_sound, projectile.location, { volume: 0.5, pitch: 0.8 });

        const nearbyEntities = source.dimension.getEntities({
            location: projectile.location,
            maxDistance: 4,
        });
    
        nearbyEntities.forEach((entity) => {
          itemSavedData.effects.forEach((effect) => {
              entity.addEffect(effect.type, effect.duration, {
                  amplifier: effect.amplifier,
                  showParticles: effect.particles,
              });
          });
        });
    };

    const molangVariables = new MolangVariableMap();

    molangVariables.setColorRGB('variable.color', {
        red: 0.28,
        green: 0.53,
        blue: 0.17
    });
  
    projectile.dimension.spawnParticle("ph_wild:splash_spell_emitter", projectile.location, molangVariables);
    projectile.remove();
  }
  if (projectile.typeId == "ph_wild:banana_peel") {
    const StrData = projectile.getDynamicProperty('ph_wild:projectile_data');

    if (StrData) {
        const itemSavedData = JSON.parse(StrData);

        source.dimension.playSound(itemSavedData.hit_sound, projectile.location, { volume: 0.5, pitch: 0.8 });
    };
    projectile.dimension.spawnItem(new ItemStack('ph_wild:banana_peel', 1), projectile.location);
    projectile.remove();
  }
});

world.afterEvents.projectileHitEntity.subscribe((pEvent) => {
  const { projectile, source } = pEvent;
  const entity_hit = pEvent.getEntityHit().entity;

  if (projectile.typeId == "ph_wild:custom_splash_potion") {
    const typeFamily = entity_hit.getComponent("type_family");

    if (!typeFamily?.hasTypeFamily("mob") && !typeFamily?.hasTypeFamily("player")) return;

    const StrData = projectile.getDynamicProperty('ph_wild:projectile_data');

    if (StrData) {
        const itemSavedData = JSON.parse(StrData);

        source.dimension.playSound(itemSavedData.hit_sound, projectile.location, { volume: 0.5, pitch: 0.8 });

        const nearbyEntities = source.dimension.getEntities({
            location: projectile.location,
            maxDistance: 4,
        });
    
        nearbyEntities.forEach((entity) => {
            itemSavedData.effects.forEach((effect) => {
              entity.addEffect(effect.type, effect.duration, {
                  amplifier: effect.amplifier,
                  showParticles: effect.particles,
              });
          });
        });
    };

    const molangVariables = new MolangVariableMap();

    molangVariables.setColorRGB('variable.color', {
        red: 0.28,
        green: 0.53,
        blue: 0.17
    });
  
    projectile.dimension.spawnParticle("ph_wild:splash_spell_emitter", projectile.location, molangVariables);
    projectile.remove();
  }
  if (projectile.typeId == "ph_wild:banana_peel") {
    const typeFamily = entity_hit.getComponent("type_family");

    if (!typeFamily?.hasTypeFamily("mob") && !typeFamily?.hasTypeFamily("player")) return;

    const StrData = projectile.getDynamicProperty('ph_wild:projectile_data');

    if (StrData) {
        const itemSavedData = JSON.parse(StrData);

        source.dimension.playSound(itemSavedData.hit_sound, projectile.location, { volume: 0.5, pitch: 0.8 });
    
        itemSavedData.effects.forEach((effect) => {
            entity_hit.addEffect(effect.type, effect.duration, {
                amplifier: effect.amplifier,
                showParticles: effect.particles,
            });
        });
    };
    projectile.remove();
  }
});