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

const COOLDOWN_TICKS = 15;
const SLAPFISH_COOLDOWN = 100;
const TOILET_WAND_COOLDOWN = 80;
const KEYBOARD_SWORD_COOLDOWN = 60;
const BONE_SHAME_COOLDOWN = 200;
const SLEEPINATOR_COOLDOWN = 120;
const THINK_WAND_COOLDOWN = 40;
const DOOR_OF_DOOM_COOLDOWN = 150;
const WRONG_ANSWER_STICK_COOLDOWN = 60;
const ECHO_MICROPHONE_COOLDOWN = 80;
const SOAP_COOLDOWN = 100;
const JUICE_BLASTER_COOLDOWN = 120;
const SLOWNESS_STICK_COOLDOWN = 100;
const LAG_BOX_COOLDOWN = 150;
const WINDY_FART_GUN_COOLDOWN = 80;

const activeCooldowns = new Map();
const cooldownMap = new Map();
const slapfishCooldown = new Map();
const toiletWandCooldown = new Map();
const keyboardCooldown = new Map();
const boneCooldown = new Map();
const sleepCooldown = new Map();
const thinkWandCooldown = new Map();
const doorOfDoomCooldown = new Map();
const wrongAnswerStickCooldown = new Map();
const echoMicrophoneCooldown = new Map();
const soapCooldown = new Map();
const juiceBlasterCooldown = new Map();
const slownessStickCooldown = new Map();
const lagBoxCooldown = new Map();
const windyFartGunCooldown = new Map();

function applyEffectToTarget(player, target, effect) {
  const { x, y, z } = target.location;

  if (target.typeId === "minecraft:player") {
    return player.runCommandAsync(
      `execute positioned ${x.toFixed(2)} ${y.toFixed(2)} ${z.toFixed(2)} run effect @a[r=1,c=1] ${effect}`
    );
  } else {
    const type = target.typeId ?? "minecraft:armor_stand";
    return player.runCommandAsync(
      `execute positioned ${x.toFixed(2)} ${y.toFixed(2)} ${z.toFixed(2)} run effect @e[type=${type},type=!minecraft:item,type=!minecraft:xp_orb,r=1,c=1] ${effect}`
    );
  }
}

function applyAreaEffect(player, centerX, centerY, centerZ, radius, effect, excludePlayerName = null) {
  const promises = [];

  if (excludePlayerName) {
    promises.push(player.runCommandAsync(
      `execute positioned ${centerX.toFixed(2)} ${centerY.toFixed(2)} ${centerZ.toFixed(2)} run effect @a[r=${radius},name=!"${excludePlayerName}"] ${effect}`
    ).catch(() => { }));
  } else {
    promises.push(player.runCommandAsync(
      `execute positioned ${centerX.toFixed(2)} ${centerY.toFixed(2)} ${centerZ.toFixed(2)} run effect @a[r=${radius}] ${effect}`
    ).catch(() => { }));
  }

  promises.push(player.runCommandAsync(
    `execute positioned ${centerX.toFixed(2)} ${centerY.toFixed(2)} ${centerZ.toFixed(2)} run effect @e[type=!minecraft:player,type=!minecraft:item,type=!minecraft:xp_orb,r=${radius}] ${effect}`
  ).catch(() => { }));

  return Promise.all(promises);
}

world.afterEvents.playerSpawn.subscribe((event) => {
  const player = event.player;

  system.runTimeout(() => {
    if (!player.hasTag("mw_guidebook_given")) {
      player.runCommandAsync("give @s carperc_mw:guidebook_item 1");
      player.addTag("mw_guidebook_given");
    }
  }, 20);
});

function isValidTarget(entity, playerId) {
  if (!entity || !entity.isValid()) return false;
  if (entity.id === playerId) return false;

  const invalidTypes = [
    "minecraft:item",
    "minecraft:xp_orb",
    "minecraft:experience_orb",
    "minecraft:arrow",
    "minecraft:trident",
    "minecraft:boat",
    "minecraft:minecart",
    "minecraft:painting",
    "minecraft:item_frame",
  ];

  if (invalidTypes.includes(entity.typeId)) return false;
  if (!entity.typeId) return false;
  if (entity.typeId.startsWith("carperc_mw:") && entity.typeId.includes("projectile")) return false;

  return true;
}

async function isPositionSafe(dimension, x, y, z) {
  try {

    const feetBlock = dimension.getBlock({
      x: Math.floor(x),
      y: Math.floor(y),
      z: Math.floor(z)
    });


    const headBlock = dimension.getBlock({
      x: Math.floor(x),
      y: Math.floor(y + 1),
      z: Math.floor(z)
    });


    return feetBlock?.typeId === "minecraft:air" && headBlock?.typeId === "minecraft:air";
  } catch (e) {

    return false;
  }
}

function startTextCooldownBar(player, weaponName, maxTicks) {
  const playerId = player.id;


  if (activeCooldowns.has(playerId)) {
    const existingInterval = activeCooldowns.get(playerId);
    system.clearRun(existingInterval.intervalId);
  }

  let tick = 0;
  const interval = system.runInterval(() => {
    tick += 5;
    const remainingTicks = maxTicks - tick;
    const remainingSeconds = Math.ceil(remainingTicks / 20);

    if (remainingTicks <= 0) {
      system.clearRun(interval);
      activeCooldowns.delete(playerId);


      player.runCommandAsync(
        `titleraw @s actionbar {"rawtext":[{"text":""}]}`
      );
      return;
    }

    player.runCommandAsync(
      `titleraw @s actionbar {"rawtext":[{"text":"§7${weaponName} Cooldown: §f${remainingSeconds}s"}]}`
    );
  }, 5);
  activeCooldowns.set(playerId, {
    intervalId: interval,
    weaponName: weaponName,
    maxTicks: maxTicks
  });
}

function getEntityInView(player, maxDistance = 4, fovDegrees = 40) {
  const view = player.getViewDirection();
  const pos = player.location;
  const entities = player.dimension.getEntities({
    location: pos,
    maxDistance,
    excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
  });
  let bestMatch = null;
  let bestAngle = fovDegrees;
  for (const entity of entities) {
    if (!isValidTarget(entity, player.id)) continue;
    const dx = entity.location.x - pos.x;
    const dy = entity.location.y - pos.y;
    const dz = entity.location.z - pos.z;
    const len = Math.sqrt(dx * dx + dy * dy + dz * dz);
    const dot = (dx * view.x + dy * view.y + dz * view.z) / len;
    const angleDeg = Math.acos(dot) * (180 / Math.PI);
    if (angleDeg < bestAngle) {
      bestAngle = angleDeg;
      bestMatch = entity;
    }
  }
  return bestMatch;
}

world.beforeEvents.itemUse.subscribe(async (event) => {
  const player = event.source;
  const item = event.itemStack;
  if (!player || !item) return;

  const target = getEntityInView(player);
  if (!target) return;

  const currentTick = system.currentTick;
  const { x, y, z } = target.location;
  const type = target.typeId ?? "minecraft:armor_stand";

  if (item.typeId === "carperc_mw:bonk_hammer") {
    const lastUsed = cooldownMap.get(player.id) ?? 0;
    if (currentTick - lastUsed < COOLDOWN_TICKS) return;
    cooldownMap.set(player.id, currentTick);
    startTextCooldownBar(player, "BONK", COOLDOWN_TICKS);


    const targetX = x;
    const targetY = y;
    const targetZ = z;
    const targetBlockX = Math.floor(targetX);
    const targetBlockY = Math.floor(targetY);
    const targetBlockZ = Math.floor(targetZ);


    player.runCommandAsync(
      `summon carperc_mw:bonk ${targetX.toFixed(2)} ${(targetY + 2.5).toFixed(2)} ${targetZ.toFixed(2)}`
    ).then(() => {

      let bonkTrackCounter = 0;
      const bonkTrackInterval = system.runInterval(() => {

        if (!target?.isValid() || target.isDead || bonkTrackCounter >= 60) {
          system.clearRun(bonkTrackInterval);
          return;
        }


        const bonkEntities = player.dimension.getEntities({
          type: "carperc_mw:bonk"
        });


        const nearbyBonk = bonkEntities.find(entity => {
          if (!entity?.isValid()) return false;
          const distance = Math.sqrt(
            Math.pow(entity.location.x - target.location.x, 2) +
            Math.pow(entity.location.z - target.location.z, 2)
          );
          return distance < 6;
        });

        if (nearbyBonk?.isValid()) {

          nearbyBonk.runCommandAsync(
            `teleport @s ${target.location.x.toFixed(2)} ${(target.location.y + 2.5).toFixed(2)} ${target.location.z.toFixed(2)}`
          );


          if (bonkTrackCounter % 10 === 0) {
            nearbyBonk.teleport(nearbyBonk.location, {
              facingLocation: player.location,
            });
          }
        }

        bonkTrackCounter++;
      }, 1);
    }).catch(err => console.error("Failed to spawn BONK:", err));


    player.runCommandAsync(
      `particle minecraft:large_explosion ${targetX.toFixed(2)} ${targetY.toFixed(2)} ${targetZ.toFixed(2)}`
    );


    player.runCommandAsync(
      `fill ${targetBlockX - 1} ${targetBlockY - 1} ${targetBlockZ - 1} ${targetBlockX + 1} ${targetBlockY - 1} ${targetBlockZ + 1} air destroy`
    ).then(() => {

      for (let dx = -1; dx <= 1; dx++) {
        for (let dz = -1; dz <= 1; dz++) {
          player.runCommandAsync(
            `particle minecraft:critical_hit_emitter ${targetBlockX + dx + 0.5} ${targetBlockY - 0.5} ${targetBlockZ + dz + 0.5}`
          );
        }
      }
    }).catch(err => { });


    system.runTimeout(() => {
      if (!target?.isValid() || target.isDead) return;
      player.runCommandAsync(
        `fill ${targetBlockX - 1} ${targetBlockY - 2} ${targetBlockZ - 1} ${targetBlockX + 1} ${targetBlockY - 2} ${targetBlockZ + 1} air destroy`
      ).then(() => {

        for (let dx = -1; dx <= 1; dx++) {
          for (let dz = -1; dz <= 1; dz++) {
            player.runCommandAsync(
              `particle minecraft:smoke_particle ${targetBlockX + dx + 0.5} ${targetBlockY - 1.5} ${targetBlockZ + dz + 0.5}`
            );
          }
        }
      }).catch(err => { });
    }, 10);


    system.runTimeout(() => {
      if (!target?.isValid() || target.isDead) return;
      player.runCommandAsync(
        `setblock ${targetBlockX} ${targetBlockY - 3} ${targetBlockZ} air destroy`
      ).then(() => {
        player.runCommandAsync(
          `particle minecraft:large_explosion ${targetBlockX + 0.5} ${targetBlockY - 2.5} ${targetBlockZ + 0.5}`
        );
      }).catch(err => { });
    }, 20);


    const explosionPositions = [
      { x: targetX + 1, z: targetZ },
      { x: targetX - 1, z: targetZ },
      { x: targetX, z: targetZ + 1 },
      { x: targetX, z: targetZ - 1 },
      { x: targetX + 0.7, z: targetZ + 0.7 },
      { x: targetX - 0.7, z: targetZ - 0.7 },
      { x: targetX + 0.7, z: targetZ - 0.7 },
      { x: targetX - 0.7, z: targetZ + 0.7 },
    ];

    explosionPositions.forEach((pos, index) => {
      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        player.runCommandAsync(
          `particle minecraft:critical_hit_emitter ${pos.x.toFixed(2)} ${(targetY - 0.5).toFixed(2)} ${pos.z.toFixed(2)}`
        );
        if (index % 2 === 0) {
          player.runCommandAsync(
            `particle minecraft:smoke_particle ${pos.x.toFixed(2)} ${targetY.toFixed(2)} ${pos.z.toFixed(2)}`
          );
        }
      }, index * 2);
    });


    system.runTimeout(() => {
      if (!target?.isValid() || target.isDead) return;


      target.runCommandAsync(
        `tp @s ${targetX.toFixed(2)} ${(targetY - 0.8).toFixed(2)} ${targetZ.toFixed(2)}`
      ).catch(e => console.error("Failed to teleport target down:", e));

      player.runCommandAsync(
        `particle minecraft:smoke_particle ${targetX.toFixed(2)} ${targetY.toFixed(2)} ${targetZ.toFixed(2)}`
      );

      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;


        target.runCommandAsync(
          `tp @s ${targetX.toFixed(2)} ${(targetY - 1.5).toFixed(2)} ${targetZ.toFixed(2)}`
        ).catch(e => console.error("Failed to teleport target deeper:", e));

        player.runCommandAsync(
          `particle minecraft:critical_hit_emitter ${targetX.toFixed(2)} ${(targetY - 1.5).toFixed(2)} ${targetZ.toFixed(2)}`
        );
        player.runCommandAsync(
          `particle minecraft:villager_angry ${targetX.toFixed(2)} ${(targetY - 1).toFixed(2)} ${targetZ.toFixed(2)}`
        );


        for (let i = 0; i < 4; i++) {
          const angle = (i / 4) * Math.PI * 2;
          const offsetX = Math.cos(angle) * 0.8;
          const offsetZ = Math.sin(angle) * 0.8;
          player.runCommandAsync(
            `particle minecraft:smoke_particle ${(targetX + offsetX).toFixed(2)} ${(targetY - 1).toFixed(2)} ${(targetZ + offsetZ).toFixed(2)}`
          );
        }

        system.runTimeout(() => {
          if (!target?.isValid() || target.isDead) return;


          target.runCommandAsync(
            `tp @s ${targetX.toFixed(2)} ${(targetY - 2.0).toFixed(2)} ${targetZ.toFixed(2)}`
          ).catch(e => console.error("Failed to teleport target to deepest:", e));

          player.runCommandAsync(
            `particle minecraft:large_explosion ${targetX.toFixed(2)} ${(targetY - 2).toFixed(2)} ${targetZ.toFixed(2)}`
          );


          for (let j = 0; j < 8; j++) {
            const angle = (j / 8) * Math.PI * 2;
            const radius = 1.5;
            const smokeX = targetX + Math.cos(angle) * radius;
            const smokeZ = targetZ + Math.sin(angle) * radius;
            player.runCommandAsync(
              `particle minecraft:smoke_particle ${smokeX.toFixed(2)} ${(targetY - 1.5).toFixed(2)} ${smokeZ.toFixed(2)}`
            );
          }

          player.runCommandAsync(
            `playsound dig.stone @a ${targetX.toFixed(2)} ${(targetY - 2).toFixed(2)} ${targetZ.toFixed(2)} 1.0 0.5`
          );
        }, 5);
      }, 5);
    }, 10);


    player.runCommandAsync("playsound carperc_mw.bonk_loud @s ~ ~ ~ 1.5 0.8");


    player.runCommandAsync("camerashake add @s 0.3 0.5 positional");

    player.runCommandAsync(
      `tellraw @s {"rawtext":[{"text":"§e§lBONK! §7Target hammered into the ground!"}]}`
    );
  }

  if (item.typeId === "carperc_mw:slapfish") {
    const lastUsed = slapfishCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < SLAPFISH_COOLDOWN) return;

    slapfishCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Slapfish", SLAPFISH_COOLDOWN);

    const dx = target.location.x - player.location.x;
    const dz = target.location.z - player.location.z;
    const len = Math.sqrt(dx * dx + dz * dz) || 1;

    const knockbackX = dx / len;
    const knockbackZ = dz / len;


    const blockBeneath = player.dimension.getBlock({
      x: Math.floor(target.location.x),
      y: Math.floor(target.location.y),
      z: Math.floor(target.location.z),
    });

    if (blockBeneath?.typeId?.includes("water")) {
      await target.runCommandAsync(
        `tp @s ${target.location.x} ${target.location.y + 1} ${target.location.z}`
      );
    }

    const { x, y, z } = target.location;

    player.runCommandAsync(
      `summon carperc_mw:splash ${x.toFixed(2)} ${(y + 0).toFixed(2)} ${z.toFixed(2)}`
    );

    const maxDistance = Math.floor(10 + Math.random() * 6);
    for (let i = maxDistance; i > 0; i--) {
      const testX = target.location.x + knockbackX * i;
      const testY = target.location.y;
      const testZ = target.location.z + knockbackZ * i;

      try {
        const result = await player.runCommandAsync(
          `testforblock ${Math.floor(testX)} ${Math.floor(testY)} ${Math.floor(testZ)} air`
        );
        if (result.successCount > 0) {
          await target.runCommandAsync(
            `tp @s ${testX.toFixed(2)} ${testY.toFixed(2)} ${testZ.toFixed(2)}`
          );
          break;
        }
      } catch (e) {

      }
    }

    player.runCommandAsync("playsound carperc_mw.slapfish_splash @s");
    player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§b§lFISH SLAP! §7Target slapped away!"}]}`);

  }

  if (item.typeId === "carperc_mw:toilet_paper_wand") {
    const lastUsed = toiletWandCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < TOILET_WAND_COOLDOWN) return;
    toiletWandCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "TP Wand", TOILET_WAND_COOLDOWN);

    const { x, y, z } = target.location;
    const type = target.typeId ?? "minecraft:armor_stand";

    try {

      const effects = [
        "weakness 8 1 true",
        "slowness 8 255 true",
        "blindness 8 0 true",
        "resistance 8 255 true"
      ];
      for (const eff of effects) {
        await applyEffectToTarget(player, target, eff);
      }

      player.runCommandAsync("playsound carperc_mw.toiletpaper_unroll @s");
      player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§f§lWRAPPED! §7Target mummified in toilet paper!"}]}`
      );




      await player.runCommandAsync(`summon carperc_mw:toilet_paper ${x.toFixed(2)} ${(y + 0.3).toFixed(2)} ${z.toFixed(2)}`);


      system.runTimeout(async () => {
        if (target?.isValid()) {
          await player.runCommandAsync(`summon carperc_mw:toilet_paper ${target.location.x.toFixed(2)} ${(target.location.y + 0.4).toFixed(2)} ${target.location.z.toFixed(2)}`);
          player.runCommandAsync("playsound block.wool.step @a ~ ~ ~ 0.8 1.2");


          player.runCommandAsync(
            `particle minecraft:villager_happy ${target.location.x.toFixed(2)} ${(target.location.y + 1).toFixed(2)} ${target.location.z.toFixed(2)}`
          );
        }
      }, 20);


      system.runTimeout(async () => {
        if (target?.isValid()) {
          await player.runCommandAsync(`summon carperc_mw:toilet_paper ${target.location.x.toFixed(2)} ${(target.location.y + 0.5).toFixed(2)} ${target.location.z.toFixed(2)}`);
          player.runCommandAsync("playsound mob.sheep.idle @a ~ ~ ~ 0.6 1.5");


          player.runCommandAsync(
            `particle minecraft:villager_happy ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
          );
          player.runCommandAsync(
            `particle minecraft:smoke_particle ${target.location.x.toFixed(2)} ${(target.location.y + 0.8).toFixed(2)} ${target.location.z.toFixed(2)}`
          );


          applyEffectToTarget(player, target, "blindness 3 255 true");
        }
      }, 40);


      let followTicks = 0;
      const followInterval = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || followTicks >= 120) {
          system.clearRun(followInterval);
          return;
        }


        const toiletPapers = player.dimension.getEntities({
          type: "carperc_mw:toilet_paper"
        });

        const nearbyPapers = toiletPapers.filter(paper => {
          if (!paper?.isValid()) return false;
          const distance = Math.sqrt(
            Math.pow(paper.location.x - target.location.x, 2) +
            Math.pow(paper.location.z - target.location.z, 2)
          );
          return distance < 6;
        });


        nearbyPapers.forEach((paper, index) => {
          if (paper?.isValid()) {
            const wrapHeight = 0.3 + (index * 0.1);
            const wrapOffset = {
              x: (Math.random() - 0.5) * 0.3,
              z: (Math.random() - 0.5) * 0.3
            };


            const rotationAngle = (followTicks * 2 + index * 120) % 360;

            paper.teleport(
              {
                x: target.location.x + wrapOffset.x,
                y: target.location.y + wrapHeight,
                z: target.location.z + wrapOffset.z
              },
              {
                rotation: { x: 0, y: rotationAngle }
              }
            );
          }
        });


        target.runCommandAsync(
          `tp @s ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
        );


        if (followTicks % 15 === 0) {

          player.runCommandAsync(
            `particle minecraft:villager_happy ${target.location.x.toFixed(2)} ${(target.location.y + 1.2).toFixed(2)} ${target.location.z.toFixed(2)}`
          );
        }


        if (followTicks % 8 === 0) {

          const smokePositions = [
            { x: 0.5, z: 0 }, { x: -0.5, z: 0 },
            { x: 0, z: 0.5 }, { x: 0, z: -0.5 }
          ];

          smokePositions.forEach(pos => {
            player.runCommandAsync(
              `particle minecraft:smoke_particle ${(target.location.x + pos.x).toFixed(2)} ${target.location.y.toFixed(2)} ${(target.location.z + pos.z).toFixed(2)}`
            );
          });
        }


        if (followTicks % 25 === 0) {
          player.runCommandAsync("playsound mob.sheep.idle @a ~ ~ ~ 0.4 0.8");
          player.runCommandAsync("playsound block.wool.step @a ~ ~ ~ 0.3 1.0");
        }


        if (followTicks % 20 === 0) {
          applyEffectToTarget(player, target, "slowness 2 255 true");
          applyEffectToTarget(player, target, "weakness 2 1 true");
        }

        followTicks++;
      }, 1);


      system.runTimeout(async () => {
        if (!target?.isValid()) return;


        await player.runCommandAsync(
          `particle minecraft:large_explosion ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
        );


        for (let i = 0; i < 6; i++) {
          const angle = (i / 6) * Math.PI * 2;
          const dustX = target.location.x + Math.cos(angle) * 1.5;
          const dustZ = target.location.z + Math.sin(angle) * 1.5;

          system.runTimeout(() => {
            if (!target?.isValid() || target.isDead) return;
            player.runCommandAsync(
              `particle minecraft:villager_happy ${dustX.toFixed(2)} ${(target.location.y + 1).toFixed(2)} ${dustZ.toFixed(2)}`
            );
          }, i * 2);
        }

        await player.runCommandAsync("playsound random.pop @a ~ ~ ~ 1.0 0.8");
        await player.runCommandAsync("playsound block.wool.break @a ~ ~ ~ 1.2 0.5");

        await player.runCommandAsync(
          `tellraw @s {"rawtext":[{"text":"§f§lMUMMY WRAPPED! §7Target completely restrained!"}]}`
        );

      }, 100);

    } catch (err) {
      console.error("Toilet Paper Wand effect failed:", err);
    }
  }


  if (item.typeId === "carperc_mw:keyboard_sword") {
    const lastUsed = keyboardCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < KEYBOARD_SWORD_COOLDOWN) return;
    keyboardCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Keyboard", KEYBOARD_SWORD_COOLDOWN);

    await applyEffectToTarget(player, target, "nausea 4 0 true");
    await applyEffectToTarget(player, target, "weakness 4 1 true");
    await applyEffectToTarget(player, target, "slowness 4 1 true");

    [
      "carperc_mw.keyboard_mash",
    ].forEach((sound) => player.runCommandAsync(`playsound ${sound} @s`));

    player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"§c§lKEY SMASH! §7Target is typing in circles!"}]}`);
    player.runCommandAsync(`summon carperc_mw:letters ${x} ${y + 0.3} ${z}`);

    const baseX = target.location.x;
    const baseZ = target.location.z;
    const originalY = target.location.y;
    let tick = 0;

    const circle = system.runInterval(() => {
      if (!target?.isValid()) {
        system.clearRun(circle);
        return;
      }

      const angle = (tick / 30) * Math.PI * 2;
      const radius = 1;
      const offsetX = Math.cos(angle) * radius;
      const offsetZ = Math.sin(angle) * radius;
      const floatY = originalY + 6;

      target.runCommandAsync(
        `tp @s ${(baseX + offsetX).toFixed(2)} ${floatY.toFixed(2)} ${(baseZ + offsetZ).toFixed(2)}`
      );


      const letters = player.dimension.getEntities({
        type: "carperc_mw:letters"
      })[0];
      if (letters?.isValid()) {
        letters.runCommandAsync(
          `teleport @s ${(baseX + offsetX).toFixed(2)} ${(floatY + 0.3).toFixed(2)} ${(baseZ + offsetZ).toFixed(2)}`
        );
      }


      target.runCommandAsync(
        `execute at @s run particle minecraft:endrod ~ ~1 ~`
      );


      if (++tick >= 60) {
        target.runCommandAsync(
          `tp @s ${baseX.toFixed(2)} ${originalY.toFixed(2)} ${baseZ.toFixed(2)}`
        );
        player.runCommandAsync(
          `playsound carperc_mw.keyboard_mash @a ${baseX.toFixed(2)} ${originalY.toFixed(2)} ${baseZ.toFixed(2)} 1 1`
        );
        system.clearRun(circle);
      }
    }, 1);
  }


  if (item.typeId === "carperc_mw:sleepinator_3000") {
    const lastUsed = sleepCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < SLEEPINATOR_COOLDOWN) return;
    sleepCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Sleepinator", SLEEPINATOR_COOLDOWN);


    await applyEffectToTarget(player, target, "blindness 5 1 true");
    await applyEffectToTarget(player, target, "slowness 5 6 true");

    // NOVO:
    await applyAreaEffect(player, x, y, z, 8, "darkness 6 0 true");


    player.runCommandAsync("playsound carperc_mw.snore_cartoon @s");


    player.runCommandAsync(
      `summon carperc_mw:sleep ${target.location.x.toFixed(2)} ${(target.location.y + 2).toFixed(2)} ${target.location.z.toFixed(2)}`
    );



    const starPositions = [
      { x: 0.8, y: 3.8, z: 0.8 },
      { x: -0.8, y: 3.6, z: 0.8 },
      { x: 0.8, y: 3.4, z: -0.8 },
      { x: -0.8, y: 3.7, z: -0.8 },
      { x: 1.2, y: 3.5, z: 0 },
      { x: -1.2, y: 3.3, z: 0 },
      { x: 0, y: 4.0, z: 0 },
      { x: 1.5, y: 3.2, z: 1.5 },
      { x: -1.5, y: 3.9, z: -1.5 },
    ];

    starPositions.forEach((pos, index) => {
      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;

        player.runCommandAsync(
          `particle minecraft:endrod ${(target.location.x + pos.x).toFixed(2)} ${(target.location.y + pos.y).toFixed(2)} ${(target.location.z + pos.z).toFixed(2)}`
        );
      }, index * 3);
    });


    let starFallCounter = 0;
    const starFallInterval = system.runInterval(() => {
      if (!target?.isValid() || target.isDead || starFallCounter >= 30) {
        system.clearRun(starFallInterval);
        return;
      }


      const offsetX = (Math.random() - 0.5) * 6;
      const offsetZ = (Math.random() - 0.5) * 6;
      const startY = target.location.y + 4 + Math.random() * 2;


      for (let i = 0; i <= 4; i++) {
        system.runTimeout(() => {
          if (!target?.isValid() || target.isDead) return;
          player.runCommandAsync(
            `particle minecraft:endrod ${(target.location.x + offsetX).toFixed(2)} ${(startY - i * 0.4).toFixed(2)} ${(target.location.z + offsetZ).toFixed(2)}`
          );
        }, i * 2);
      }

      starFallCounter++;
    }, 5);


    player.runCommandAsync(
      `execute at @e[type=${type},x=${x},y=${y},z=${z},r=1,c=1] run effect @e[r=8] darkness 6 0 true`
    );


    let snoreCounter = 0;
    const snoreInterval = system.runInterval(() => {
      if (!target?.isValid() || target.isDead || snoreCounter >= 6) {
        system.clearRun(snoreInterval);
        return;
      }


      if (snoreCounter % 2 === 0) {
        player.runCommandAsync(`playsound carperc_mw.snore_cartoon @a ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)} 0.5 0.7`);
      }


      player.runCommandAsync(
        `particle minecraft:heart_particle ${target.location.x.toFixed(2)} ${(target.location.y + 1.5).toFixed(2)} ${target.location.z.toFixed(2)}`
      );

      snoreCounter++;
    }, 20);


    let ticks = 0;
    const follow = system.runInterval(() => {
      const sleep = player.dimension.getEntities({
        type: "carperc_mw:sleep"
      });


      const nearbySleep = sleep.find(entity => {
        if (!entity?.isValid()) return false;
        const distance = Math.sqrt(
          Math.pow(entity.location.x - target.location.x, 2) +
          Math.pow(entity.location.z - target.location.z, 2)
        );
        return distance < 5;
      });

      if (!target?.isValid() || target.isDead || !nearbySleep?.isValid()) {
        system.clearRun(follow);
        return;
      }


      nearbySleep.runCommandAsync(
        `teleport @s ${target.location.x.toFixed(2)} ${(target.location.y + 2).toFixed(2)} ${target.location.z.toFixed(2)}`
      );

      applyEffectToTarget(player, target, "blindness 1 1 true");
      applyEffectToTarget(player, target, "slowness 1 255 true");

      if (ticks % 15 === 0) {
        const angle = (ticks / 15) * Math.PI * 0.5;
        const radius = 1.5;
        const particleX = target.location.x + Math.cos(angle) * radius;
        const particleZ = target.location.z + Math.sin(angle) * radius;

        player.runCommandAsync(
          `particle minecraft:villager_happy ${particleX.toFixed(2)} ${(target.location.y + 1).toFixed(2)} ${particleZ.toFixed(2)}`
        );
      }

      if (++ticks >= 120) {
        system.clearRun(follow);
      }
    }, 1);


    player.runCommandAsync(
      `tellraw @s {"rawtext":[{"text":"§9§lNIGHT TIME! §7Target sent to dreamland!"}]}`
    );
  }

  if (item.typeId === "carperc_mw:bone_of_shame") {
    const lastUsed = boneCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < BONE_SHAME_COOLDOWN) return;
    boneCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Bone of Shame", BONE_SHAME_COOLDOWN);

    try {
      await player.runCommandAsync(
        `summon carperc_mw:caught_in_the_act ${target.location.x.toFixed(2)} ${(target.location.y + 1.8).toFixed(2)} ${target.location.z.toFixed(2)}`
      );

      
      await applyEffectToTarget(player, target, "levitation 1 0 true");

      await player.runCommandAsync("playsound carperc_mw.violin_sad @s");

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§c§lCAUGHT IN THE ACT!"}]}`
      );

      let tickCounter = 0;
      const totalTicks = 120;

      const mainInterval = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || tickCounter >= totalTicks) {
          system.clearRun(mainInterval);
          return;
        }

        if (tickCounter % 10 === 0) {
          const bounceNumber = Math.floor(tickCounter / 10);
          const isSmallBounce = bounceNumber % 2 === 0;
          const levitationLevel = isSmallBounce ? 0 : 1;

          
          applyEffectToTarget(player, target, `levitation 1 ${levitationLevel} true`);

          const particles = [
            "minecraft:heart_particle",
            "minecraft:villager_angry",
            "minecraft:critical_hit_emitter",
            "minecraft:enchantment_table_particle"
          ];

          const randomParticle = particles[Math.floor(Math.random() * particles.length)];
          player.runCommandAsync(
            `execute at @e[x=${target.location.x},y=${target.location.y},z=${target.location.z},r=2,c=1] run particle ${randomParticle} ~ ~1 ~`
          );

          if (bounceNumber % 3 === 0) {
            const sounds = [
              "mob.villager.haggle",
              "mob.chicken.plop",
              "random.pop",
              "mob.villager.idle"
            ];
            const randomSound = sounds[Math.floor(Math.random() * sounds.length)];
            player.runCommandAsync(`playsound ${randomSound} @a ~ ~ ~ 0.5 1.5`);
          }
        }

        if (tickCounter % 3 === 0 && tickCounter <= 60) {
          const caughtEntities = player.dimension.getEntities({
            type: "carperc_mw:caught_in_the_act"
          });

          const nearbyEntities = caughtEntities.filter(entity => {
            if (!entity?.isValid()) return false;
            const distance = Math.sqrt(
              Math.pow(entity.location.x - target.location.x, 2) +
              Math.pow(entity.location.z - target.location.z, 2)
            );
            return distance < 6;
          });

          if (nearbyEntities.length > 1) {
            for (let i = 1; i < nearbyEntities.length; i++) {
              nearbyEntities[i].triggerEvent("carperc_mw:despawn_event");
            }
          }

          if (nearbyEntities.length > 0 && nearbyEntities[0].isValid()) {
            nearbyEntities[0].runCommandAsync(
              `teleport @s ${target.location.x.toFixed(2)} ${(target.location.y + 1.5).toFixed(2)} ${target.location.z.toFixed(2)}`
            );
          }
        }

        tickCounter++;
      }, 1);

    } catch (err) {
      console.error("Bone of Shame effect failed:", err);
    }
  }


  if (item.typeId === "carperc_mw:door_of_doom") {
    const lastUsed = doorOfDoomCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < DOOR_OF_DOOM_COOLDOWN) return;
    doorOfDoomCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Door of Doom", DOOR_OF_DOOM_COOLDOWN);

    try {
      const targetPos = target.location;
      const { x: targetX, y: targetY, z: targetZ } = targetPos;
      const type = target.typeId ?? "minecraft:armor_stand";


      let circleTickCounter = 0;
      const circleParticles = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || circleTickCounter >= 40) {
          system.clearRun(circleParticles);
          return;
        }


        const angle = (circleTickCounter / 10) * Math.PI * 2;
        const radius = 2.5;
        const offsetX = Math.cos(angle) * radius;
        const offsetZ = Math.sin(angle) * radius;


        player.runCommandAsync(
          `particle minecraft:critical_hit_emitter ${(targetX + offsetX).toFixed(2)} ${(targetY + 1.5).toFixed(2)} ${(targetZ + offsetZ).toFixed(2)}`
        );


        if (circleTickCounter % 5 === 0) {
          player.runCommandAsync(
            `particle minecraft:endrod ${targetX.toFixed(2)} ${(targetY + 2).toFixed(2)} ${targetZ.toFixed(2)}`
          );
        }


        if (circleTickCounter % 8 === 0) {
          player.runCommandAsync(
            `particle minecraft:heart_particle ${(targetX + offsetX * 0.5).toFixed(2)} ${(targetY + 1).toFixed(2)} ${(targetZ + offsetZ * 0.5).toFixed(2)}`
          );
        }

        circleTickCounter++;
      }, 1);


      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§4§lSLAM & BAM!"}]}`
      );


      system.runTimeout(async () => {
        try {

          await player.runCommandAsync(
            `summon carperc_mw:doors ${targetX.toFixed(2)} ${targetY.toFixed(2)} ${targetZ.toFixed(2)}`
          );


          await player.runCommandAsync(
            `playsound carperc_mw.door_slam_heavy @a ${targetX.toFixed(2)} ${targetY.toFixed(2)} ${targetZ.toFixed(2)} 1.5 1.0`
          );
          await player.runCommandAsync(
            `playsound random.break @a ${targetX.toFixed(2)} ${targetY.toFixed(2)} ${targetZ.toFixed(2)} 1.0 1.2`
          );


          await player.runCommandAsync(
            `particle minecraft:large_explosion ${targetX.toFixed(2)} ${targetY.toFixed(2)} ${targetZ.toFixed(2)}`
          );

        } catch (e) {
          console.error("Failed to spawn doors:", e);
        }
      }, 20);


      system.runTimeout(async () => {
        try {

          await player.runCommandAsync(
            `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=1,c=1] darkness 5 0 true`
          );
          await player.runCommandAsync(
            `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=1,c=1] slowness 4 4 true`
          );


          await player.runCommandAsync(
            `execute at @s run effect @e[type=!player,x=${targetX},y=${targetY},z=${targetZ},r=5] slowness 8 2 true`
          );
          await player.runCommandAsync(
            `execute at @s run effect @e[type=!player,x=${targetX},y=${targetY},z=${targetZ},r=5] weakness 6 1 true`
          );


          await player.runCommandAsync(`particle minecraft:critical_hit_emitter ${targetX.toFixed(2)} ${(targetY + 1).toFixed(2)} ${targetZ.toFixed(2)}`);
          await player.runCommandAsync(`particle minecraft:villager_angry ${targetX.toFixed(2)} ${(targetY + 0.5).toFixed(2)} ${targetZ.toFixed(2)}`);

          await player.runCommandAsync(
            `tellraw @s {"rawtext":[{"text":"§7Target is caged and nearby enemies weakened!"}]}`
          );

        } catch (e) {
          console.error("Door of Doom final effect failed:", e);
        }
      }, 40);


      const originalTargetPos = { x: targetX, y: targetY, z: targetZ };
      let trapTickCounter = 0;
      const trapSystem = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || trapTickCounter >= 120) {
          system.clearRun(trapSystem);
          return;
        }


        const nearbyDoors = player.dimension.getEntities({
          type: "carperc_mw:doors",
          location: originalTargetPos,
          maxDistance: 3
        });


        if (nearbyDoors.length === 0 && trapTickCounter > 40) {
          system.clearRun(trapSystem);
          return;
        }


        target.runCommandAsync(
          `tp @s ${originalTargetPos.x.toFixed(2)} ${originalTargetPos.y.toFixed(2)} ${originalTargetPos.z.toFixed(2)}`
        );


        if (trapTickCounter % 10 === 0) {
          player.runCommandAsync(
            `particle minecraft:villager_angry ${originalTargetPos.x.toFixed(2)} ${(originalTargetPos.y + 1).toFixed(2)} ${originalTargetPos.z.toFixed(2)}`
          );
        }


        if (trapTickCounter % 20 === 0) {
          player.runCommandAsync(
            `execute at @s run effect @e[type=${type},x=${originalTargetPos.x},y=${originalTargetPos.y},z=${originalTargetPos.z},r=1,c=1] slowness 2 255 true`
          );


          player.runCommandAsync(
            `tp @e[type=${type},x=${originalTargetPos.x},y=${originalTargetPos.y},z=${originalTargetPos.z},r=3,c=1] ${originalTargetPos.x.toFixed(2)} ${originalTargetPos.y.toFixed(2)} ${originalTargetPos.z.toFixed(2)}`
          );
        }

        trapTickCounter++;
      }, 1);


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        const remainingDoors = player.dimension.getEntities({
          type: "carperc_mw:doors",
          location: targetPos,
          maxDistance: 3
        });

        remainingDoors.forEach(door => {
          try {
            door.triggerEvent("carperc_mw:despawn_event");
          } catch (e) {
            if (door?.isValid()) {
              door.remove();
            }
          }
        });
      }, 80);

    } catch (err) {
      console.error("Door of Doom effect failed:", err);
    }
  }


  if (item.typeId === "carperc_mw:wrong_answer_stick") {
    const lastUsed = wrongAnswerStickCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < WRONG_ANSWER_STICK_COOLDOWN) return;
    wrongAnswerStickCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Wrong Answer", WRONG_ANSWER_STICK_COOLDOWN);

    try {
      const targetPos = target.location;
      const { x: targetX, y: targetY, z: targetZ } = targetPos;
      const type = target.typeId ?? "minecraft:armor_stand";


      await player.runCommandAsync(`particle minecraft:critical_hit_emitter ${targetX.toFixed(2)} ${(targetY + 1).toFixed(2)} ${targetZ.toFixed(2)}`);
      await player.runCommandAsync(`particle minecraft:critical_hit_emitter ${targetX.toFixed(2)} ${(targetY + 0.5).toFixed(2)} ${targetZ.toFixed(2)}`);



      await player.runCommandAsync("playsound note.pling @a ~ ~ ~ 0.8 0.5");
      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        player.runCommandAsync("playsound note.pling @a ~ ~ ~ 0.8 1.0");
      }, 5);
      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        player.runCommandAsync("playsound note.pling @a ~ ~ ~ 0.8 2.0");
      }, 10);

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§c§lBZZT! §7Wrong answer marked!"}]}`
      );


      await player.runCommandAsync(
        `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=1,c=1] nausea 2 0 true`
      );


      await player.runCommandAsync(
        `summon carperc_mw:x ${targetX.toFixed(2)} ${(targetY + 1.0).toFixed(2)} ${targetZ.toFixed(2)}`
      );


      await player.runCommandAsync(
        `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=1,c=1] weakness 5 0 true`
      );


      await player.runCommandAsync(`particle minecraft:villager_angry ${targetX.toFixed(2)} ${(targetY + 2).toFixed(2)} ${targetZ.toFixed(2)}`);


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;

        let followTickCounter = 0;
        const followSystem = system.runInterval(() => {
          if (!target?.isValid() || target.isDead || followTickCounter >= 80) {
            system.clearRun(followSystem);
            return;
          }


          const xEntities = player.dimension.getEntities({
            type: "carperc_mw:x"
          });

          const nearbyX = xEntities.find(entity => {
            if (!entity?.isValid()) return false;

            const distance = Math.sqrt(
              Math.pow(entity.location.x - target.location.x, 2) +
              Math.pow(entity.location.z - target.location.z, 2)
            );

            return distance < 6;
          });

          if (!nearbyX?.isValid()) {
            system.clearRun(followSystem);
            return;
          }


          nearbyX.runCommandAsync(
            `teleport @s ${target.location.x.toFixed(2)} ${(target.location.y + 1.0).toFixed(2)} ${target.location.z.toFixed(2)}`
          );


          if (followTickCounter % 15 === 0) {
            player.runCommandAsync(
              `particle minecraft:villager_angry ${target.location.x.toFixed(2)} ${(target.location.y + 1.5).toFixed(2)} ${target.location.z.toFixed(2)}`
            );
          }


          followTickCounter++;
        }, 1);


        system.runTimeout(async () => {
          await player.runCommandAsync(`playsound carperc_mw.buzzer_wrong @a ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)} 1.0 0.8`);


          try {
            await player.runCommandAsync(
              `summon carperc_mw:x ${target.location.x.toFixed(2)} ${(target.location.y + 1.0).toFixed(2)} ${target.location.z.toFixed(2)}`
            );


            let secondXFollowCounter = 0;
            const secondXFollowInterval = system.runInterval(() => {
              if (!target?.isValid() || target.isDead || secondXFollowCounter >= 60) {
                system.clearRun(secondXFollowInterval);
                return;
              }


              const xEntities = player.dimension.getEntities({
                type: "carperc_mw:x"
              });


              const nearbyXs = xEntities.filter(entity => {
                if (!entity?.isValid()) return false;
                const distance = Math.sqrt(
                  Math.pow(entity.location.x - target.location.x, 2) +
                  Math.pow(entity.location.z - target.location.z, 2)
                );
                return distance < 6;
              });


              nearbyXs.forEach((xEntity, index) => {
                if (xEntity?.isValid()) {
                  const yOffset = 1.0 + (index * 0.5);
                  xEntity.runCommandAsync(
                    `teleport @s ${target.location.x.toFixed(2)} ${(target.location.y + yOffset).toFixed(2)} ${target.location.z.toFixed(2)}`
                  );
                }
              });

              secondXFollowCounter++;
            }, 1);




            const explodeX = Math.floor(target.location.x);
            const explodeY = Math.floor(target.location.y);
            const explodeZ = Math.floor(target.location.z);


            await player.runCommandAsync(`particle minecraft:lava_particle ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`);
            await player.runCommandAsync("playsound carperc_mw.buzzer_wrong @a ~ ~ ~ 1.0 1.0");


            system.runTimeout(async () => {

              await player.runCommandAsync(
                `particle minecraft:large_explosion ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
              );


              await player.runCommandAsync("playsound random.explode @a ~ ~ ~ 1.5 1.0");


              await player.runCommandAsync("camerashake add @a[r=10] 0.5 0.8 positional");


              await player.runCommandAsync(
                `fill ${explodeX - 1} ${explodeY - 1} ${explodeZ - 1} ${explodeX + 1} ${explodeY + 1} ${explodeZ + 1} air destroy`
              );


              await player.runCommandAsync(
                `fill ${explodeX - 1} ${explodeY - 2} ${explodeZ - 1} ${explodeX + 1} ${explodeY - 2} ${explodeZ + 1} air destroy`
              );


              for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                const radius = 2;
                const particleX = target.location.x + Math.cos(angle) * radius;
                const particleZ = target.location.z + Math.sin(angle) * radius;

                await player.runCommandAsync(
                  `particle minecraft:critical_hit_emitter ${particleX.toFixed(2)} ${target.location.y.toFixed(2)} ${particleZ.toFixed(2)}`
                );
                await player.runCommandAsync(
                  `particle minecraft:smoke_particle ${particleX.toFixed(2)} ${(target.location.y + 0.5).toFixed(2)} ${particleZ.toFixed(2)}`
                );
              }


              for (let j = 0; j < 5; j++) {
                const lavaX = target.location.x + (Math.random() - 0.5) * 3;
                const lavaZ = target.location.z + (Math.random() - 0.5) * 3;
                await player.runCommandAsync(
                  `particle minecraft:lava_particle ${lavaX.toFixed(2)} ${target.location.y.toFixed(2)} ${lavaZ.toFixed(2)}`
                );
              }


              await player.runCommandAsync(
                `execute at @s run damage @e[type=${type},x=${target.location.x},y=${target.location.y},z=${target.location.z},r=1,c=1] 1 entity_explosion`
              );


              const knockbackY = 1.0;
              if (target?.isValid()) {
                await target.runCommandAsync(
                  `tp @s ~ ~${knockbackY} ~`
                );
              }


              await player.runCommandAsync(
                `execute at @s run effect @e[type=${type},x=${target.location.x},y=${target.location.y},z=${target.location.z},r=1,c=1] fire_resistance 3 0 true`
              );


              await player.runCommandAsync(`particle minecraft:villager_angry ${target.location.x.toFixed(2)} ${(target.location.y + 1.0).toFixed(2)} ${target.location.z.toFixed(2)}`);

              await player.runCommandAsync(
                `tellraw @a {"rawtext":[{"text":"§c§lBOOM! §7Double wrong = TNT explosion!"}]}`
              );

            }, 10);

          } catch (e) {
            console.error("Failed to spawn second carperc_mw:x or explode:", e);
          }

        }, 40);

      }, 20);

    } catch (err) {
      console.error("Wrong Answer Stick effect failed:", err);
    }
  }


  if (item.typeId === "carperc_mw:echo_microphone") {
    const lastUsed = echoMicrophoneCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < ECHO_MICROPHONE_COOLDOWN) return;
    echoMicrophoneCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Echo Microphone", ECHO_MICROPHONE_COOLDOWN);

    try {
      const targetPos = target.location;
      const { x: targetX, y: targetY, z: targetZ } = targetPos;
      const type = target.typeId ?? "minecraft:armor_stand";


      await player.runCommandAsync("playsound carperc_mw.echo_shout @a ~ ~ ~ 1.0 1.0");

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§e§lHEY! §7Calling out target..."}]}`
      );


      await player.runCommandAsync(
        `summon carperc_mw:hey ${targetX.toFixed(2)} ${(targetY + 1.8).toFixed(2)} ${targetZ.toFixed(2)}`
      );


      await player.runCommandAsync(
        `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=1,c=1] slowness 8 0 true`
      );
      await player.runCommandAsync(
        `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=1,c=1] weakness 8 0 true`
      );


      await player.runCommandAsync(`particle carperc_mw:note_particle ${targetX.toFixed(2)} ${(targetY + 1).toFixed(2)} ${targetZ.toFixed(2)}`);
      await player.runCommandAsync(`particle minecraft:villager_happy ${targetX.toFixed(2)} ${(targetY + 1.5).toFixed(2)} ${targetZ.toFixed(2)}`);


      let circleTickCounter = 0;
      const noteCircleSystem = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || circleTickCounter >= 160) {
          system.clearRun(noteCircleSystem);
          return;
        }


        const angle = (circleTickCounter / 15) * Math.PI * 2;
        const radius = 2.0;
        const offsetX = Math.cos(angle) * radius;
        const offsetZ = Math.sin(angle) * radius;


        player.runCommandAsync(
          `particle carperc_mw:note_particle ${(target.location.x + offsetX).toFixed(2)} ${(target.location.y + 1.2).toFixed(2)} ${(target.location.z + offsetZ).toFixed(2)}`
        );


        if (circleTickCounter % 5 === 0) {
          const angle2 = angle + Math.PI;
          const offsetX2 = Math.cos(angle2) * radius;
          const offsetZ2 = Math.sin(angle2) * radius;

          player.runCommandAsync(
            `particle minecraft:villager_happy ${(target.location.x + offsetX2).toFixed(2)} ${(target.location.y + 1.2).toFixed(2)} ${(target.location.z + offsetZ2).toFixed(2)}`
          );
        }


        if (circleTickCounter % 8 === 0) {
          player.runCommandAsync(
            `particle minecraft:endrod ${target.location.x.toFixed(2)} ${(target.location.y + 1.8).toFixed(2)} ${target.location.z.toFixed(2)}`
          );
        }

        circleTickCounter++;
      }, 1);


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        let heyFollowCounter = 0;
        const heyFollowSystem = system.runInterval(() => {
          if (!target?.isValid() || target.isDead || heyFollowCounter >= 25) {
            system.clearRun(heyFollowSystem);
            return;
          }


          const heyEntities = player.dimension.getEntities({
            type: "carperc_mw:hey"
          });

          const nearbyHey = heyEntities.find(entity => {
            if (!entity?.isValid()) return false;

            const distance = Math.sqrt(
              Math.pow(entity.location.x - target.location.x, 2) +
              Math.pow(entity.location.z - target.location.z, 2)
            );

            return distance < 6;
          });

          if (!nearbyHey?.isValid()) {
            system.clearRun(heyFollowSystem);
            return;
          }


          nearbyHey.runCommandAsync(
            `teleport @s ${target.location.x.toFixed(2)} ${(target.location.y + 1.8).toFixed(2)} ${target.location.z.toFixed(2)}`
          );

          heyFollowCounter++;
        }, 1);
      }, 1);


      system.runTimeout(async () => {
        await player.runCommandAsync(`playsound entity.player.levelup @a ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)} 1.0 2.0`);
        await player.runCommandAsync(`particle minecraft:heart_particle ${target.location.x.toFixed(2)} ${(target.location.y + 2).toFixed(2)} ${target.location.z.toFixed(2)}`);
        await player.runCommandAsync(
          `tellraw @a {"rawtext":[{"text":"§e§lHEY! §7${target.nameTag || 'Entity'} is getting attention!"}]}`
        );
      }, 60);

    } catch (err) {
      console.error("Echo Microphone effect failed:", err);
    }
  }

  if (item.typeId === "carperc_mw:slowness_stick") {
    const lastUsed = slownessStickCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < SLOWNESS_STICK_COOLDOWN) return;
    slownessStickCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Slowness Stick", SLOWNESS_STICK_COOLDOWN);

    const target = getEntityInView(player);
    if (!target) return;

    try {
      const { x, y, z } = target.location;
      const type = target.typeId ?? "minecraft:armor_stand";


      await player.runCommandAsync(
        `summon carperc_mw:slowness ${x.toFixed(2)} ${y.toFixed(2)} ${z.toFixed(2)}`
      );


      await player.runCommandAsync("playsound carperc_mw.slime_squishloop @a ~ ~ ~ 0.7 1.0");


      await player.runCommandAsync(
        `particle minecraft:villager_happy ${x.toFixed(2)} ${y.toFixed(2)} ${z.toFixed(2)}`
      );
      await player.runCommandAsync(
        `particle minecraft:heart_particle ${x.toFixed(2)} ${(y + 0.5).toFixed(2)} ${z.toFixed(2)}`
      );

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§a§lSLOWNESS SLIME! §7Target trapped in goo!"}]}`
      );


      await applyEffectToTarget(player, target, "slowness 12 4 true");


      const centerBlockX = Math.floor(x);
      const centerBlockY = Math.floor(y) - 1;
      const centerBlockZ = Math.floor(z);


      const originalBlocks = [];


      const slimeCommands = [];
      for (let offsetX = -2; offsetX <= 2; offsetX++) {
        for (let offsetZ = -2; offsetZ <= 2; offsetZ++) {
          const blockX = centerBlockX + offsetX;
          const blockZ = centerBlockZ + offsetZ;

          try {

            const originalBlock = player.dimension.getBlock({
              x: blockX,
              y: centerBlockY,
              z: blockZ
            });

            if (originalBlock) {
              originalBlocks.push({
                x: blockX,
                y: centerBlockY,
                z: blockZ,
                typeId: originalBlock.typeId
              });
            }


            slimeCommands.push(`setblock ${blockX} ${centerBlockY} ${blockZ} slime`);

          } catch (e) {

          }
        }
      }


      const slimePromises = slimeCommands.map(cmd =>
        player.runCommandAsync(cmd).catch(() => { })
      );
      await Promise.all(slimePromises);


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        for (let offsetX = -1; offsetX <= 2; offsetX++) {
          for (let offsetZ = -1; offsetZ <= 2; offsetZ++) {
            const blockX = centerBlockX + offsetX;
            const blockZ = centerBlockZ + offsetZ;

            player.runCommandAsync(
              `particle minecraft:villager_happy ${blockX + 0.5} ${centerBlockY + 1} ${centerBlockZ + 0.5}`
            );
          }
        }
      }, 2);


      await applyAreaEffect(player, x, y, z, 10, "slowness 8 2 true", player.name);


      for (let i = 0; i < 8; i++) {
        const angle = (i / 8) * Math.PI * 2;
        const radius = 5;
        const aoeX = x + Math.cos(angle) * radius;
        const aoeZ = z + Math.sin(angle) * radius;

        system.runTimeout(() => {
          if (!target?.isValid() || target.isDead) return;
          player.runCommandAsync(
            `particle minecraft:villager_happy ${aoeX.toFixed(2)} ${y.toFixed(2)} ${aoeZ.toFixed(2)}`
          );
        }, i * 2);
      }


      let followTicks = 0;
      const maxFollowTicks = 120;

      const followInterval = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || followTicks >= maxFollowTicks) {
          system.clearRun(followInterval);
          return;
        }


        const slownessEntities = player.dimension.getEntities({
          type: "carperc_mw:slowness"
        });

        const nearbySlowness = slownessEntities.find(entity => {
          if (!entity?.isValid()) return false;
          const distance = Math.sqrt(
            Math.pow(entity.location.x - target.location.x, 2) +
            Math.pow(entity.location.z - target.location.z, 2)
          );
          return distance < 6;
        });

        if (!nearbySlowness?.isValid()) {
          system.clearRun(followInterval);
          return;
        }


        nearbySlowness.runCommandAsync(
          `teleport @s ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
        );


        const angle = (followTicks / 10) * Math.PI * 2;
        const radius = 1.8;
        const trailX = target.location.x + Math.cos(angle) * radius;
        const trailZ = target.location.z + Math.sin(angle) * radius;


        player.runCommandAsync(
          `particle minecraft:villager_happy ${trailX.toFixed(2)} ${target.location.y.toFixed(2)} ${trailZ.toFixed(2)}`
        );


        const oppositeX = target.location.x - Math.cos(angle) * radius;
        const oppositeZ = target.location.z - Math.sin(angle) * radius;
        player.runCommandAsync(
          `particle minecraft:heart_particle ${oppositeX.toFixed(2)} ${(target.location.y + 0.3).toFixed(2)} ${oppositeZ.toFixed(2)}`
        );


        if (followTicks % 20 === 0) {
          player.runCommandAsync(
            `playsound mob.slime.squish @a ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)} 0.5 ${0.8 + Math.random() * 0.4}`
          );
        }


        if (followTicks % 40 === 0) {
          applyEffectToTarget(player, target, "slowness 3 3 true");
        }

        followTicks++;
      }, 1);


      system.runTimeout(async () => {
        for (const blockInfo of originalBlocks) {
          try {

            const restoreType = blockInfo.typeId === "minecraft:slime" ? "air" : blockInfo.typeId;
            await player.runCommandAsync(
              `setblock ${blockInfo.x} ${blockInfo.y} ${blockInfo.z} ${restoreType}`
            );


            if (Math.random() < 0.3) {
              await player.runCommandAsync(
                `particle minecraft:smoke_particle ${blockInfo.x + 0.5} ${blockInfo.y + 1} ${blockInfo.z + 0.5}`
              );
            }
          } catch (e) {

          }
        }


        await player.runCommandAsync(
          `playsound mob.slime.death @a ${x.toFixed(2)} ${y.toFixed(2)} ${z.toFixed(2)} 0.5 1.2`
        );

        await player.runCommandAsync(
          `tellraw @s {"rawtext":[{"text":"§7Slime cleanup complete!"}]}`
        );

      }, 200);


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;

        player.runCommandAsync(
          `particle minecraft:large_explosion ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
        );


        for (let j = 0; j < 12; j++) {
          const burstAngle = (j / 12) * Math.PI * 2;
          const burstRadius = 2.5;
          const burstX = target.location.x + Math.cos(burstAngle) * burstRadius;
          const burstZ = target.location.z + Math.sin(burstAngle) * burstRadius;

          system.runTimeout(() => {
            if (!target?.isValid() || target.isDead) return;
            player.runCommandAsync(
              `particle minecraft:villager_happy ${burstX.toFixed(2)} ${(target.location.y + 0.8).toFixed(2)} ${burstZ.toFixed(2)}`
            );
          }, j);
        }

        player.runCommandAsync("playsound mob.slime.big @a ~ ~ ~ 1.2 0.6");

      }, 100);

    } catch (err) {
      console.error("Slowness Stick effect failed:", err);
    }
  }

  if (item.typeId === "carperc_mw:lag_box") {
    const lastUsed = lagBoxCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < LAG_BOX_COOLDOWN) return;
    lagBoxCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Blink Box", LAG_BOX_COOLDOWN);

    const target = getEntityInView(player);
    if (!target) return;

    try {
      const { x, y, z } = target.location;
      const type = target.typeId ?? "minecraft:armor_stand";


      const originalX = x;
      const originalY = y;
      const originalZ = z;
      const prisonRadius = 2;


      await player.runCommandAsync("playsound carperc_mw.lag_glitch @a ~ ~ ~ 1.0 1.0");


      await player.runCommandAsync(
        `particle minecraft:critical_hit_emitter ${x.toFixed(2)} ${y.toFixed(2)} ${z.toFixed(2)}`
      );
      await player.runCommandAsync(
        `particle minecraft:endrod ${x.toFixed(2)} ${(y + 1).toFixed(2)} ${z.toFixed(2)}`
      );

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§b§lBLINK BURST! §7Target safely blinks a short distance."}]}`
      );


      await applyEffectToTarget(player, target, "slowness 1 255 true");


      const createLagBoxVisual = () => {

        for (let offsetX = -2; offsetX <= 2; offsetX++) {
          for (let offsetZ = -2; offsetZ <= 2; offsetZ++) {

            if (Math.abs(offsetX) === 2 || Math.abs(offsetZ) === 2) {

              player.runCommandAsync(
                `particle minecraft:endrod ${(originalX + offsetX).toFixed(2)} ${originalY.toFixed(2)} ${(originalZ + offsetZ).toFixed(2)}`
              );

              player.runCommandAsync(
                `particle minecraft:endrod ${(originalX + offsetX).toFixed(2)} ${(originalY + 2).toFixed(2)} ${(originalZ + offsetZ).toFixed(2)}`
              );
            }
          }
        }


        for (let offsetY = 0; offsetY <= 2; offsetY++) {
          const corners = [
            { x: originalX - 2, z: originalZ - 2 },
            { x: originalX + 2, z: originalZ - 2 },
            { x: originalX - 2, z: originalZ + 2 },
            { x: originalX + 2, z: originalZ + 2 },
          ];

          corners.forEach(corner => {
            player.runCommandAsync(
              `particle minecraft:critical_hit_emitter ${corner.x.toFixed(2)} ${(originalY + offsetY).toFixed(2)} ${corner.z.toFixed(2)}`
            );
          });
        }
      };


      createLagBoxVisual();


      let teleportCount = 0;
      const maxTeleports = 12;

      system.runTimeout(() => {
        const rapidTeleportInterval = system.runInterval(async () => {
          if (!target?.isValid() || target.isDead || teleportCount >= maxTeleports) {
            system.clearRun(rapidTeleportInterval);
            return;
          }


          const randomOffsetX = (Math.random() - 0.5) * prisonRadius * 2;
          const randomOffsetY = Math.random() * 3;
          const randomOffsetZ = (Math.random() - 0.5) * prisonRadius * 2;

          const newX = originalX + randomOffsetX;
          const newY = originalY + randomOffsetY;
          const newZ = originalZ + randomOffsetZ;


          const isSafe = await isPositionSafe(player.dimension, newX, newY, newZ);

          if (isSafe) {

            target.runCommandAsync(
              `tp @s ${newX.toFixed(2)} ${newY.toFixed(2)} ${newZ.toFixed(2)}`
            ).catch(() => { });
          }


          player.runCommandAsync(
            `particle minecraft:critical_hit_emitter ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
          );


          applyEffectToTarget(player, target, "slowness 1 255 true");


          if (teleportCount % 3 === 0) {
            createLagBoxVisual();
          }

          teleportCount++;
        }, 5);


        system.runTimeout(async () => {
          if (!target?.isValid()) return;


          await applyEffectToTarget(player, target, "clear");


          await player.runCommandAsync(
            `particle minecraft:large_explosion ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)}`
          );


          await player.runCommandAsync("playsound random.explode @a ~ ~ ~ 1.5 0.8");


          await player.runCommandAsync("camerashake add @a[r=8] 0.4 0.6 positional");


          await applyEffectToTarget(player, target, "nausea 5 1 true");
          await applyEffectToTarget(player, target, "weakness 4 1 true");


          for (let i = 0; i < 8; i++) {
            const angle = (i / 8) * Math.PI * 2;
            const explosionRadius = 2.5;
            const explX = target.location.x + Math.cos(angle) * explosionRadius;
            const explZ = target.location.z + Math.sin(angle) * explosionRadius;

            system.runTimeout(() => {
              if (!target?.isValid() || target.isDead) return;
              player.runCommandAsync(
                `particle minecraft:critical_hit_emitter ${explX.toFixed(2)} ${target.location.y.toFixed(2)} ${explZ.toFixed(2)}`
              );
              player.runCommandAsync(
                `particle minecraft:smoke_particle ${explX.toFixed(2)} ${(target.location.y + 1).toFixed(2)} ${explZ.toFixed(2)}`
              );
            }, i);
          }


          await player.runCommandAsync(
            `tellraw @s {"rawtext":[{"text":"§a§lBLINK COMPLETE! §7Everything returns to normal."}]}`
          );

        }, maxTeleports * 5 + 10);

      }, 20);


      let ambientTick = 0;
      const ambientInterval = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || ambientTick >= 80) {
          system.clearRun(ambientInterval);
          return;
        }


        if (ambientTick % 8 === 0) {
          const ambientX = originalX + (Math.random() - 0.5) * 6;
          const ambientZ = originalZ + (Math.random() - 0.5) * 6;

          player.runCommandAsync(
            `particle minecraft:villager_angry ${ambientX.toFixed(2)} ${(originalY + 1).toFixed(2)} ${ambientZ.toFixed(2)}`
          );
        }

        ambientTick++;
      }, 1);

    } catch (err) {
      console.error("Lag Box effect failed:", err);
    }
  }

  if (item.typeId === "carperc_mw:windy_fart_gun") {
    const lastUsed = windyFartGunCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < WINDY_FART_GUN_COOLDOWN) return;
    windyFartGunCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Fart Gun", WINDY_FART_GUN_COOLDOWN);

    const target = getEntityInView(player);
    if (!target) return;

    try {
      const { x, y, z } = target.location;
      const type = target.typeId ?? "minecraft:armor_stand";


      const playerPos = player.location;
      const viewDirection = player.getViewDirection();


      const fartSpawnX = playerPos.x + viewDirection.x * 1.2;
      const fartSpawnY = playerPos.y + 1.2;
      const fartSpawnZ = playerPos.z + viewDirection.z * 1.2;


      await player.runCommandAsync(
        `particle carperc_mw:fart ${fartSpawnX.toFixed(2)} ${fartSpawnY.toFixed(2)} ${fartSpawnZ.toFixed(2)}`
      );


      for (let i = 0; i < 3; i++) {
        const offsetX = (Math.random() - 0.5) * 0.5;
        const offsetY = (Math.random() - 0.5) * 0.3;
        const offsetZ = (Math.random() - 0.5) * 0.5;

        system.runTimeout(() => {
          if (!target?.isValid() || target.isDead) return;
          player.runCommandAsync(
            `particle carperc_mw:fart ${(fartSpawnX + offsetX).toFixed(2)} ${(fartSpawnY + offsetY).toFixed(2)} ${(fartSpawnZ + offsetZ).toFixed(2)}`
          );
        }, i * 2);
      }


      await player.runCommandAsync("playsound carperc_mw.fart_gust @a ~ ~ ~ 1.0 1.0");


      await player.runCommandAsync(
        `particle minecraft:villager_angry ${fartSpawnX.toFixed(2)} ${fartSpawnY.toFixed(2)} ${fartSpawnZ.toFixed(2)}`
      );
      await player.runCommandAsync(
        `particle minecraft:smoke_particle ${fartSpawnX.toFixed(2)} ${(fartSpawnY + 0.3).toFixed(2)} ${fartSpawnZ.toFixed(2)}`
      );

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§a§lWINDY BLAST! §7Toxic gas deployed!"}]}`
      );


      await applyEffectToTarget(player, target, "poison 5 1 true");


      const dx = target.location.x - player.location.x;
      const dz = target.location.z - player.location.z;
      const len = Math.sqrt(dx * dx + dz * dz) || 1;


      const knockbackX = (dx / len) * 3.5;
      const knockbackZ = (dz / len) * 3.5;
      const knockbackY = 0.8;


      const maxKnockbackDistance = Math.floor(4);


      for (let distance = maxKnockbackDistance; distance > 0; distance--) {
        const testX = target.location.x + (knockbackX * distance / maxKnockbackDistance);
        const testY = target.location.y + knockbackY;
        const testZ = target.location.z + (knockbackZ * distance / maxKnockbackDistance);


        const isSafe = await isPositionSafe(player.dimension, testX, testY, testZ);

        if (isSafe) {

          await target.runCommandAsync(
            `tp @s ${testX.toFixed(2)} ${testY.toFixed(2)} ${testZ.toFixed(2)}`
          );
          break;
        }
      }


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        if (!target?.isValid()) return;


        const cloudPositions = [
          { x: 0, y: 0.5, z: 0 },
          { x: 1, y: 0.3, z: 0 },
          { x: -1, y: 0.3, z: 0 },
          { x: 0, y: 0.3, z: 1 },
          { x: 0, y: 0.3, z: -1 },
          { x: 0.7, y: 0.7, z: 0.7 },
          { x: -0.7, y: 0.7, z: -0.7 },
        ];

        cloudPositions.forEach((pos, index) => {
          system.runTimeout(() => {
            if (!target?.isValid() || target.isDead) return;
            player.runCommandAsync(
              `particle minecraft:villager_angry ${(target.location.x + pos.x).toFixed(2)} ${(target.location.y + pos.y).toFixed(2)} ${(target.location.z + pos.z).toFixed(2)}`
            );
            player.runCommandAsync(
              `particle minecraft:smoke_particle ${(target.location.x + pos.x).toFixed(2)} ${(target.location.y + pos.y).toFixed(2)} ${(target.location.z + pos.z).toFixed(2)}`
            );
          }, index * 3);
        });


        player.runCommandAsync(
          `playsound mob.ghast.fireball @a ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)} 0.8 0.4`
        );

      }, 8);


      let travelTicks = 0;
      const maxTravelTicks = 20;

      const fartProjectileInterval = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || travelTicks >= maxTravelTicks) {
          system.clearRun(fartProjectileInterval);
          return;
        }


        const progress = travelTicks / maxTravelTicks;
        const currentX = fartSpawnX + (target.location.x - fartSpawnX) * progress;
        const currentY = fartSpawnY + (target.location.y - fartSpawnY) * progress;
        const currentZ = fartSpawnZ + (target.location.z - fartSpawnZ) * progress;


        player.runCommandAsync(
          `particle carperc_mw:fart ${currentX.toFixed(2)} ${currentY.toFixed(2)} ${currentZ.toFixed(2)}`
        );


        if (travelTicks % 3 === 0) {
          player.runCommandAsync(
            `particle minecraft:smoke_particle ${currentX.toFixed(2)} ${currentY.toFixed(2)} ${currentZ.toFixed(2)}`
          );
        }

        travelTicks++;
      }, 1);


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        if (!target?.isValid()) return;


        for (let i = 0; i < 4; i++) {
          const cloudOffsetX = (Math.random() - 0.5) * 1.5;
          const cloudOffsetY = Math.random() * 0.8;
          const cloudOffsetZ = (Math.random() - 0.5) * 1.5;

          system.runTimeout(() => {
            if (!target?.isValid() || target.isDead) return;
            player.runCommandAsync(
              `particle carperc_mw:fart ${(target.location.x + cloudOffsetX).toFixed(2)} ${(target.location.y + cloudOffsetY).toFixed(2)} ${(target.location.z + cloudOffsetZ).toFixed(2)}`
            );
          }, i * 5);
        }


        player.runCommandAsync(
          `playsound mob.ghast.fireball @a ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)} 0.8 0.4`
        );

      }, maxTravelTicks + 5);


      let poisonTicks = 0;
      const maxPoisonTicks = 100;

      const poisonCloudInterval = system.runInterval(() => {
        if (!target?.isValid() || target.isDead || poisonTicks >= maxPoisonTicks) {
          system.clearRun(poisonCloudInterval);
          return;
        }


        if (poisonTicks % 20 === 0) {
          applyEffectToTarget(player, target, "poison 2 1 true");
        }


        if (poisonTicks % 8 === 0) {
          const angle = (poisonTicks / 8) * Math.PI * 0.5;
          const radius = 1.2;
          const stinkX = target.location.x + Math.cos(angle) * radius;
          const stinkZ = target.location.z + Math.sin(angle) * radius;

          player.runCommandAsync(
            `particle minecraft:villager_angry ${stinkX.toFixed(2)} ${(target.location.y + 0.5).toFixed(2)} ${stinkZ.toFixed(2)}`
          );
        }


        if (poisonTicks % 30 === 0) {
          player.runCommandAsync(
            `playsound random.fizz @a ${target.location.x.toFixed(2)} ${target.location.y.toFixed(2)} ${target.location.z.toFixed(2)} 0.4 0.8`
          );
        }

        poisonTicks++;
      }, 1);


      system.runTimeout(() => {
        if (!target?.isValid() || target.isDead) return;
        if (target?.isValid()) {

          for (let i = 0; i < 5; i++) {
            const disperseAngle = (i / 5) * Math.PI * 2;
            const disperseRadius = 2;
            const disperseX = target.location.x + Math.cos(disperseAngle) * disperseRadius;
            const disperseZ = target.location.z + Math.sin(disperseAngle) * disperseRadius;

            system.runTimeout(() => {
              if (!target?.isValid() || target.isDead) return;
              player.runCommandAsync(
                `particle minecraft:smoke_particle ${disperseX.toFixed(2)} ${(target.location.y + 0.8).toFixed(2)} ${disperseZ.toFixed(2)}`
              );
            }, i * 4);
          }

          player.runCommandAsync(
            `tellraw @s {"rawtext":[{"text":"§7Toxic cloud dispersed!"}]}`
          );
        }
      }, maxPoisonTicks + 10);

    } catch (err) {
      console.error("Windy Fart Gun effect failed:", err);
    }
  }

});


world.afterEvents.itemUse.subscribe(async (event) => {
  const player = event.source;
  const item = event.itemStack;
  if (!player || !item) return;

  const currentTick = system.currentTick;


  if (item.typeId === "carperc_mw:think_hard_wand") {
    const lastUsed = thinkWandCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < THINK_WAND_COOLDOWN) return;
    thinkWandCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Think Wand", THINK_WAND_COOLDOWN);


    const playerPos = player.location;
    const viewDirection = player.getViewDirection();


    const playerRotation = player.getRotation();
    const yawRad = (playerRotation.y * Math.PI) / 180;


    const rightArmOffset = {
      x: Math.cos(yawRad + Math.PI / 2) * 0.3,
      y: 1.2,
      z: Math.sin(yawRad + Math.PI / 2) * 0.3
    };


    const wandTipOffset = {
      x: viewDirection.x * 1.5,
      y: viewDirection.y * 1.5,
      z: viewDirection.z * 1.5
    };

    const spawnPos = {
      x: playerPos.x + rightArmOffset.x + wandTipOffset.x,
      y: playerPos.y + rightArmOffset.y + wandTipOffset.y,
      z: playerPos.z + rightArmOffset.z + wandTipOffset.z
    };

    try {

      await player.runCommandAsync(
        `summon carperc_mw:think_hard_wand_projectile ${spawnPos.x.toFixed(2)} ${spawnPos.y.toFixed(2)} ${spawnPos.z.toFixed(2)}`
      );


      const projectiles = player.dimension.getEntities({
        type: "carperc_mw:think_hard_wand_projectile",
        location: spawnPos,
        maxDistance: 3
      });

      if (projectiles.length > 0) {
        const projectile = projectiles[0];
        const speed = 0.8;
        let distance = 0;
        const maxDistance = 20;
        let hitSomething = false;


        const moveInterval = system.runInterval(() => {
          if (!projectile?.isValid() || hitSomething) {
            system.clearRun(moveInterval);
            return;
          }


          const newPos = {
            x: projectile.location.x + viewDirection.x * speed,
            y: projectile.location.y + viewDirection.y * speed,
            z: projectile.location.z + viewDirection.z * speed
          };


          try {

            const yaw = Math.atan2(-viewDirection.x, viewDirection.z) * (180 / Math.PI);

            projectile.teleport(newPos, {
              rotation: { x: 0, y: yaw }
            });
          } catch (e) {
            system.clearRun(moveInterval);
            return;
          }

          distance += speed;


          try {
            projectile.runCommandAsync("particle minecraft:enchantment_table_particle ~ ~ ~");
          } catch (e) {

          }


          if (distance >= maxDistance) {
            hitSomething = true;
            try {
              projectile.triggerEvent("carperc_mw:despawn");
            } catch (e) {
              if (projectile?.isValid()) {
                projectile.remove();
              }
            }
            system.clearRun(moveInterval);
            return;
          }


          const nearbyEntities = player.dimension.getEntities({
            location: projectile.location,
            maxDistance: 2.0,
            excludeTypes: ["minecraft:item"]
          });


          const validTargets = nearbyEntities.filter(entity =>
            isValidTarget(entity, player.id) && entity.id !== projectile.id
          );


          if (validTargets.length > 0) {
            hitSomething = true;


            let closestTarget = validTargets[0];
            let closestDistance = Math.sqrt(
              Math.pow(closestTarget.location.x - projectile.location.x, 2) +
              Math.pow(closestTarget.location.y - projectile.location.y, 2) +
              Math.pow(closestTarget.location.z - projectile.location.z, 2)
            );

            for (const entity of validTargets) {
              const dist = Math.sqrt(
                Math.pow(entity.location.x - projectile.location.x, 2) +
                Math.pow(entity.location.y - projectile.location.y, 2) +
                Math.pow(entity.location.z - projectile.location.z, 2)
              );
              if (dist < closestDistance) {
                closestTarget = entity;
                closestDistance = dist;
              }
            }

            const hitEntity = closestTarget;


            try {
              const { x, y, z } = hitEntity.location;
              const type = hitEntity.typeId ?? "minecraft:armor_stand";


              player.runCommandAsync(
                `execute at @s run effect @e[x=${x},y=${y},z=${z},r=3,type=!player] nausea 8 2 true`
              );
              player.runCommandAsync(
                `execute at @s run effect @e[x=${x},y=${y},z=${z},r=3,type=!player] slowness 5 1 true`
              );
              player.runCommandAsync(
                `execute at @s run effect @e[x=${x},y=${y},z=${z},r=3,type=!player] weakness 3 1 true`
              );




              const explodeX = Math.floor(hitEntity.location.x);
              const explodeY = Math.floor(hitEntity.location.y);
              const explodeZ = Math.floor(hitEntity.location.z);


              player.runCommandAsync(
                `particle minecraft:enchantment_table_particle ${hitEntity.location.x.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
              );
              player.runCommandAsync("playsound carperc_mw.brain_thinkloop @a ~ ~ ~ 1.5 1.0");


              system.runTimeout(async () => {

                await player.runCommandAsync(
                  `particle minecraft:large_explosion ${hitEntity.location.x.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                );


                await player.runCommandAsync("playsound random.explode @a ~ ~ ~ 2.0 0.9");


                await player.runCommandAsync("camerashake add @a[r=15] 0.8 1.0 positional");


                await player.runCommandAsync(
                  `fill ${explodeX - 2} ${explodeY - 1} ${explodeZ - 2} ${explodeX + 2} ${explodeY + 1} ${explodeZ + 2} air destroy`
                );


                await player.runCommandAsync(
                  `fill ${explodeX - 1} ${explodeY - 2} ${explodeZ - 1} ${explodeX + 1} ${explodeY - 2} ${explodeZ + 1} air destroy`
                );


                await player.runCommandAsync(
                  `setblock ${explodeX} ${explodeY - 3} ${explodeZ} air destroy`
                );


                for (let i = 0; i < 12; i++) {
                  const angle = (i / 12) * Math.PI * 2;
                  const radius = 3;
                  const particleX = hitEntity.location.x + Math.cos(angle) * radius;
                  const particleZ = hitEntity.location.z + Math.sin(angle) * radius;

                  await player.runCommandAsync(
                    `particle minecraft:critical_hit_emitter ${particleX.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${particleZ.toFixed(2)}`
                  );
                  await player.runCommandAsync(
                    `particle minecraft:smoke_particle ${particleX.toFixed(2)} ${(hitEntity.location.y + 1).toFixed(2)} ${particleZ.toFixed(2)}`
                  );
                }


                for (let j = 0; j < 8; j++) {
                  const magicX = hitEntity.location.x + (Math.random() - 0.5) * 4;
                  const magicZ = hitEntity.location.z + (Math.random() - 0.5) * 4;
                  const magicY = hitEntity.location.y + Math.random() * 2;
                  await player.runCommandAsync(
                    `particle minecraft:enchantment_table_particle ${magicX.toFixed(2)} ${magicY.toFixed(2)} ${magicZ.toFixed(2)}`
                  );
                }


                await player.runCommandAsync(
                  `execute at @s run damage @e[type=${type},x=${hitEntity.location.x},y=${hitEntity.location.y},z=${hitEntity.location.z},r=1,c=1] 1 magic`
                );


                if (hitEntity?.isValid()) {
                  const knockbackX = -viewDirection.x * 2;
                  const knockbackY = 1.2;
                  const knockbackZ = -viewDirection.z * 2;

                  await hitEntity.runCommandAsync(
                    `tp @s ~${knockbackX.toFixed(2)} ~${knockbackY} ~${knockbackZ.toFixed(2)}`
                  );
                }


                await player.runCommandAsync(
                  `tellraw @a {"rawtext":[{"text":"§d§lMIND BLOWN! §75x5 confusion explosion!"}]}`
                );

              }, 5);

              player.runCommandAsync(
                `tellraw @s {"rawtext":[{"text":"§d§lTHINK HARD! §7Direct hit - prepare for explosion!"}]}`
              );

            } catch (e) {
              console.error("Think Hard Wand hit effect failed:", e);
            }


            system.runTimeout(() => {
              try {
                if (projectile?.isValid()) {
                  projectile.triggerEvent("carperc_mw:despawn");
                }
              } catch (e) {
                if (projectile?.isValid()) {
                  projectile.remove();
                }
              }
            }, 2);

            system.clearRun(moveInterval);
            return;
          }


          try {
            const blockAtPos = player.dimension.getBlock({
              x: Math.floor(newPos.x),
              y: Math.floor(newPos.y),
              z: Math.floor(newPos.z)
            });

            if (blockAtPos && blockAtPos.typeId !== "minecraft:air") {
              hitSomething = true;
              try {
                projectile.triggerEvent("carperc_mw:despawn");
              } catch (e) {
                if (projectile?.isValid()) {
                  projectile.remove();
                }
              }
              system.clearRun(moveInterval);
              return;
            }
          } catch (e) {

          }

        }, 1);
      }

      await player.runCommandAsync("playsound random.bow @s ~ ~ ~ 1.0 0.8");

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§d§lTHINK HARD! §7Projectile fired!"}]}`
      );

    } catch (err) {
      console.error("Think Hard Wand failed:", err);
    }
  }


  if (item.typeId === "carperc_mw:soap_of_justice") {
    const lastUsed = soapCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < SOAP_COOLDOWN) return;
    soapCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Soap of Justice", SOAP_COOLDOWN);


    const playerPos = player.location;
    const viewDirection = player.getViewDirection();


    const playerRotation = player.getRotation();
    const yawRad = (playerRotation.y * Math.PI) / 180;


    const spawnOffset = {
      x: viewDirection.x * 1.5,
      y: 1.2,
      z: viewDirection.z * 1.5
    };

    const spawnPos = {
      x: playerPos.x + spawnOffset.x,
      y: playerPos.y + spawnOffset.y,
      z: playerPos.z + spawnOffset.z
    };

    try {

      await player.runCommandAsync(
        `summon carperc_mw:soap_projectile ${spawnPos.x.toFixed(2)} ${spawnPos.y.toFixed(2)} ${spawnPos.z.toFixed(2)}`
      );


      const projectiles = player.dimension.getEntities({
        type: "carperc_mw:soap_projectile",
        location: spawnPos,
        maxDistance: 3
      });

      if (projectiles.length > 0) {
        const projectile = projectiles[0];
        const speed = 0.9;
        let distance = 0;
        const maxDistance = 25;
        let hitSomething = false;


        const moveInterval = system.runInterval(() => {
          if (!projectile?.isValid() || hitSomething) {
            system.clearRun(moveInterval);
            return;
          }


          const newPos = {
            x: projectile.location.x + viewDirection.x * speed,
            y: projectile.location.y + viewDirection.y * speed,
            z: projectile.location.z + viewDirection.z * speed
          };


          try {
            const yaw = Math.atan2(-viewDirection.x, viewDirection.z) * (180 / Math.PI);
            projectile.teleport(newPos, {
              rotation: { x: 0, y: yaw }
            });
          } catch (e) {
            system.clearRun(moveInterval);
            return;
          }

          distance += speed;


          try {
            if (distance % 3 < 1) {
              projectile.runCommandAsync("particle minecraft:villager_happy ~ ~ ~");
            }
          } catch (e) { }


          if (distance >= maxDistance) {
            hitSomething = true;
            try {
              projectile.triggerEvent("carperc_mw:despawn");
            } catch (e) {
              if (projectile?.isValid()) {
                projectile.remove();
              }
            }
            system.clearRun(moveInterval);
            return;
          }


          const nearbyEntities = player.dimension.getEntities({
            location: projectile.location,
            maxDistance: 1.8,
            excludeTypes: ["minecraft:item"]
          });

          const validTargets = nearbyEntities.filter(entity =>
            isValidTarget(entity, player.id) && entity.id !== projectile.id
          );

          if (validTargets.length > 0) {
            hitSomething = true;


            let closestTarget = validTargets[0];
            let closestDistance = Math.sqrt(
              Math.pow(closestTarget.location.x - projectile.location.x, 2) +
              Math.pow(closestTarget.location.y - projectile.location.y, 2) +
              Math.pow(closestTarget.location.z - projectile.location.z, 2)
            );

            for (const entity of validTargets) {
              const dist = Math.sqrt(
                Math.pow(entity.location.x - projectile.location.x, 2) +
                Math.pow(entity.location.y - projectile.location.y, 2) +
                Math.pow(entity.location.z - projectile.location.z, 2)
              );
              if (dist < closestDistance) {
                closestTarget = entity;
                closestDistance = dist;
              }
            }

            const hitEntity = closestTarget;


            try {
              const targetPos = hitEntity.location;
              const targetX = targetPos.x;
              const targetY = targetPos.y;
              const targetZ = targetPos.z;
              const type = hitEntity.typeId ?? "minecraft:armor_stand";

              player.runCommandAsync("playsound carperc_mw.cleanse_shimmer @a ~ ~ ~ 0.7 1.0");


              player.runCommandAsync(
                `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=1,c=1] slowness 1 2 true`
              );

              player.runCommandAsync(
                `tellraw @s {"rawtext":[{"text":"§b§lSOAPED! §7Target is slippery!"}]}`
              );


              let slideCounter = 0;
              const maxSlides = 20;

              const slideInterval = system.runInterval(async () => {
                if (!hitEntity?.isValid() || hitEntity.isDead || slideCounter >= maxSlides) {
                  system.clearRun(slideInterval);
                  return;
                }


                let slideX = 0;
                let slideZ = 0;


                if (slideCounter < 5) {

                  slideX = viewDirection.x * 0.8;
                  slideZ = viewDirection.z * 0.8;
                } else if (slideCounter < 10) {

                  slideX = -viewDirection.x * 0.8;
                  slideZ = -viewDirection.z * 0.8;
                } else if (slideCounter < 13) {

                  slideX = Math.cos(yawRad - Math.PI / 2) * 0.6;
                  slideZ = Math.sin(yawRad - Math.PI / 2) * 0.6;
                } else if (slideCounter < 16) {

                  slideX = Math.cos(yawRad + Math.PI / 2) * 0.6;
                  slideZ = Math.sin(yawRad + Math.PI / 2) * 0.6;
                } else {

                  slideX = (Math.random() - 0.5) * 0.5;
                  slideZ = (Math.random() - 0.5) * 0.5;
                }


                const newX = hitEntity.location.x + slideX;
                const newY = hitEntity.location.y;
                const newZ = hitEntity.location.z + slideZ;


                const isSafe = await isPositionSafe(player.dimension, newX, newY, newZ);

                if (isSafe) {

                  hitEntity.runCommandAsync(
                    `tp @s ${newX.toFixed(2)} ${newY.toFixed(2)} ${newZ.toFixed(2)}`
                  ).catch(() => { });
                } else {

                  const smallSlideX = slideX * 0.3;
                  const smallSlideZ = slideZ * 0.3;
                  const smallNewX = hitEntity.location.x + smallSlideX;
                  const smallNewZ = hitEntity.location.z + smallSlideZ;

                  const isSmallSafe = await isPositionSafe(player.dimension, smallNewX, newY, smallNewZ);

                  if (isSmallSafe) {
                    hitEntity.runCommandAsync(
                      `tp @s ${smallNewX.toFixed(2)} ${newY.toFixed(2)} ${smallNewZ.toFixed(2)}`
                    ).catch(() => { });
                  }

                }


                if (slideCounter % 5 === 0) {
                  player.runCommandAsync(
                    `playsound mob.slime.squish @a ${hitEntity.location.x.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${hitEntity.location.z.toFixed(2)} 0.5 ${1.0 + Math.random() * 0.5}`
                  );
                }

                slideCounter++;
              }, 1);


              system.runTimeout(() => {

                player.runCommandAsync(
                  `execute at @s run effect @e[type=${type},x=${targetX},y=${targetY},z=${targetZ},r=2,c=1] speed 2 1 true`
                );


                for (let i = 0; i < 5; i++) {
                  system.runTimeout(() => {
                    if (hitEntity?.isValid()) {
                      player.runCommandAsync(
                        `particle minecraft:villager_happy ${hitEntity.location.x.toFixed(2)} ${(hitEntity.location.y + 1).toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                      );
                    }
                  }, i * 4);
                }
              }, 10);


              system.runTimeout(() => {
                if (hitEntity?.isValid()) {

                  hitEntity.runCommandAsync(`tp @s ~ ~0.5 ~`).then(() => {
                    system.runTimeout(() => {
                      if (hitEntity?.isValid()) {
                        hitEntity.runCommandAsync(`tp @s ~ ~-0.5 ~`);
                        player.runCommandAsync(
                          `particle minecraft:large_explosion ${hitEntity.location.x.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                        );
                        player.runCommandAsync("playsound mob.slime.big @a ~ ~ ~ 1.0 0.8");


                        player.runCommandAsync(
                          `execute at @s run effect @e[type=${type},x=${hitEntity.location.x},y=${hitEntity.location.y},z=${hitEntity.location.z},r=1,c=1] nausea 5 1 true`
                        );
                      }
                    }, 5);
                  }).catch(() => { });
                }
              }, 25);

            } catch (e) {
              console.error("Soap of Justice hit effect failed:", e);
            }


            system.runTimeout(() => {
              try {
                if (projectile?.isValid()) {
                  projectile.triggerEvent("carperc_mw:despawn");
                }
              } catch (e) {
                if (projectile?.isValid()) {
                  projectile.remove();
                }
              }
            }, 2);

            system.clearRun(moveInterval);
            return;
          }


          try {
            const blockAtPos = player.dimension.getBlock({
              x: Math.floor(newPos.x),
              y: Math.floor(newPos.y),
              z: Math.floor(newPos.z)
            });

            if (blockAtPos && blockAtPos.typeId !== "minecraft:air") {
              hitSomething = true;
              player.runCommandAsync("playsound bucket.empty_water @a ~ ~ ~ 0.5 1.8");

              try {
                projectile.triggerEvent("carperc_mw:despawn");
              } catch (e) {
                if (projectile?.isValid()) {
                  projectile.remove();
                }
              }
              system.clearRun(moveInterval);
              return;
            }
          } catch (e) { }

        }, 1);
      }

      await player.runCommandAsync("playsound random.bow @s ~ ~ ~ 0.8 1.2");
      await player.runCommandAsync("playsound bucket.fill_water @s ~ ~ ~ 0.6 1.5");

      await player.runCommandAsync(
        `tellraw @s {"rawtext":[{"text":"§b§lSOAP LAUNCHED! §7Clean up time!"}]}`
      );

    } catch (err) {
      console.error("Soap of Justice failed:", err);
    }
  }

  if (item.typeId === "carperc_mw:juice_blaster_9000") {
    const lastUsed = juiceBlasterCooldown.get(player.id) ?? 0;
    if (currentTick - lastUsed < JUICE_BLASTER_COOLDOWN) return;
    juiceBlasterCooldown.set(player.id, currentTick);
    startTextCooldownBar(player, "Juice Blaster", JUICE_BLASTER_COOLDOWN);


    const playerPos = player.location;
    const viewDirection = player.getViewDirection();
    const playerRotation = player.getRotation();
    const yawRad = (playerRotation.y * Math.PI) / 180;


    const spawnOffset = {
      x: viewDirection.x * 1.5,
      y: 1.2,
      z: viewDirection.z * 1.5
    };

    const spawnPos = {
      x: playerPos.x + spawnOffset.x,
      y: playerPos.y + spawnOffset.y,
      z: playerPos.z + spawnOffset.z
    };

    try {

      await player.runCommandAsync(
        `summon carperc_mw:juice_projectile ${spawnPos.x.toFixed(2)} ${spawnPos.y.toFixed(2)} ${spawnPos.z.toFixed(2)}`
      );


      const projectiles = player.dimension.getEntities({
        type: "carperc_mw:juice_projectile",
        location: spawnPos,
        maxDistance: 3
      });

      if (projectiles.length > 0) {
        const projectile = projectiles[0];
        const speed = 1.0;
        let distance = 0;
        const maxDistance = 25;
        let hitSomething = false;


        const moveInterval = system.runInterval(() => {
          if (!projectile?.isValid() || hitSomething) {
            system.clearRun(moveInterval);
            return;
          }


          const newPos = {
            x: projectile.location.x + viewDirection.x * speed,
            y: projectile.location.y + viewDirection.y * speed,
            z: projectile.location.z + viewDirection.z * speed
          };

          try {
            const yaw = Math.atan2(-viewDirection.x, viewDirection.z) * (180 / Math.PI);
            projectile.teleport(newPos, {
              rotation: { x: 0, y: yaw }
            });
          } catch (e) {
            system.clearRun(moveInterval);
            return;
          }

          distance += speed;


          try {
            projectile.runCommandAsync("particle minecraft:villager_happy ~ ~ ~");
            if (distance % 2 < 1) {
              projectile.runCommandAsync("particle minecraft:heart_particle ~ ~ ~");
            }
          } catch (e) { }


          if (distance >= maxDistance) {
            hitSomething = true;
            try {
              projectile.triggerEvent("carperc_mw:despawn");
            } catch (e) {
              if (projectile?.isValid()) projectile.remove();
            }
            system.clearRun(moveInterval);
            return;
          }


          const nearbyEntities = player.dimension.getEntities({
            location: projectile.location,
            maxDistance: 2.0,
            excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
          });


          const validTargets = nearbyEntities.filter(entity =>
            isValidTarget(entity, player.id) && entity.id !== projectile.id
          );

          if (validTargets.length > 0) {
            hitSomething = true;


            let closestTarget = validTargets[0];
            let closestDistance = Math.sqrt(
              Math.pow(closestTarget.location.x - projectile.location.x, 2) +
              Math.pow(closestTarget.location.y - projectile.location.y, 2) +
              Math.pow(closestTarget.location.z - projectile.location.z, 2)
            );

            for (const entity of validTargets) {
              const dist = Math.sqrt(
                Math.pow(entity.location.x - projectile.location.x, 2) +
                Math.pow(entity.location.y - projectile.location.y, 2) +
                Math.pow(entity.location.z - projectile.location.z, 2)
              );
              if (dist < closestDistance) {
                closestTarget = entity;
                closestDistance = dist;
              }
            }

            const hitEntity = closestTarget;


            try {
              const targetPos = hitEntity.location;
              const { x: targetX, y: targetY, z: targetZ } = targetPos;
              const type = hitEntity.typeId ?? "minecraft:armor_stand";


              player.runCommandAsync(
                `particle minecraft:heart_particle ${targetX.toFixed(2)} ${targetY.toFixed(2)} ${targetZ.toFixed(2)}`
              );
              player.runCommandAsync(
                `particle minecraft:villager_happy ${targetX.toFixed(2)} ${(targetY + 0.5).toFixed(2)} ${targetZ.toFixed(2)}`
              );

              player.runCommandAsync("playsound carperc_mw.juice_spray @a ~ ~ ~ 0.7 1.0");


              applyEffectToTarget(player, hitEntity, "speed 8 2 true");
              applyEffectToTarget(player, hitEntity, "jump_boost 8 4 true");

              player.runCommandAsync(
                `tellraw @s {"rawtext":[{"text":"§6§lJUICE BLAST! §7Bouncing madness activated!"}]}`
              );


              let bounceCounter = 0;
              const maxBounces = 8;
              const originalY = targetY;

              const bounceInterval = system.runInterval(async () => {
                if (!hitEntity?.isValid() || hitEntity.isDead || bounceCounter >= maxBounces) {
                  system.clearRun(bounceInterval);
                  return;
                }

                const bounceHeight = 2.5;
                const isUp = bounceCounter % 2 === 0;

                if (isUp) {

                  const bounceUpY = originalY + bounceHeight;
                  const isSafeUp = await isPositionSafe(player.dimension, hitEntity.location.x, bounceUpY, hitEntity.location.z);

                  if (isSafeUp) {
                    hitEntity.runCommandAsync(
                      `tp @s ${hitEntity.location.x.toFixed(2)} ${bounceUpY.toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                    ).catch(() => { });
                  }


                  player.runCommandAsync(
                    `particle minecraft:critical_hit_emitter ${hitEntity.location.x.toFixed(2)} ${(hitEntity.location.y + 1).toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                  );
                  player.runCommandAsync(
                    `particle minecraft:endrod ${hitEntity.location.x.toFixed(2)} ${(hitEntity.location.y + 0.5).toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                  );


                  player.runCommandAsync(
                    `playsound mob.slime.big @a ${hitEntity.location.x.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${hitEntity.location.z.toFixed(2)} 0.8 ${1.2 + Math.random() * 0.4}`
                  );

                } else {

                  const isSafeDown = await isPositionSafe(player.dimension, hitEntity.location.x, originalY, hitEntity.location.z);

                  if (isSafeDown) {
                    hitEntity.runCommandAsync(
                      `tp @s ${hitEntity.location.x.toFixed(2)} ${originalY.toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                    ).catch(() => { });
                  }


                  player.runCommandAsync(
                    `particle minecraft:large_explosion ${hitEntity.location.x.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                  );
                  player.runCommandAsync(
                    `particle minecraft:smoke_particle ${hitEntity.location.x.toFixed(2)} ${(hitEntity.location.y + 0.3).toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                  );


                  player.runCommandAsync("camerashake add @a[r=10] 0.3 0.4 positional");


                  if (bounceCounter < maxBounces - 1) {
                    const sideX = (Math.random() - 0.5) * 1.5;
                    const sideZ = (Math.random() - 0.5) * 1.5;


                    system.runTimeout(async () => {
                      if (hitEntity?.isValid()) {
                        const newSideX = hitEntity.location.x + sideX;
                        const newSideZ = hitEntity.location.z + sideZ;
                        const isSafe = await isPositionSafe(player.dimension, newSideX, hitEntity.location.y, newSideZ);

                        if (isSafe) {
                          hitEntity.runCommandAsync(
                            `tp @s ${newSideX.toFixed(2)} ~ ${newSideZ.toFixed(2)}`
                          ).catch(() => { });
                        }
                      }
                    }, 3);
                  }
                }


                const angle = (bounceCounter / 4) * Math.PI * 2;
                const radius = 1.2;
                const particleX = hitEntity.location.x + Math.cos(angle) * radius;
                const particleZ = hitEntity.location.z + Math.sin(angle) * radius;

                player.runCommandAsync(
                  `particle minecraft:villager_happy ${particleX.toFixed(2)} ${hitEntity.location.y.toFixed(2)} ${particleZ.toFixed(2)}`
                );

                bounceCounter++;
              }, 8);


              system.runTimeout(() => {
                if (hitEntity?.isValid()) {

                  applyEffectToTarget(player, hitEntity, "clear");
                  applyEffectToTarget(player, hitEntity, "nausea 4 1 true");
                  applyEffectToTarget(player, hitEntity, "slowness 3 1 true");


                  player.runCommandAsync(
                    `particle minecraft:villager_angry ${hitEntity.location.x.toFixed(2)} ${(hitEntity.location.y + 1).toFixed(2)} ${hitEntity.location.z.toFixed(2)}`
                  );

                  player.runCommandAsync(
                    `tellraw @a {"rawtext":[{"text":"§c§lCRASH! §7Sugar rush is over..."}]}`
                  );
                }
              }, maxBounces * 8 + 10);

            } catch (e) {
              console.error("Juice Blaster bouncing effect failed:", e);
            }


            system.runTimeout(() => {
              try {
                if (projectile?.isValid()) {
                  projectile.triggerEvent("carperc_mw:despawn");
                }
              } catch (e) {
                if (projectile?.isValid()) projectile.remove();
              }
            }, 2);

            system.clearRun(moveInterval);
            return;
          }


          try {
            const blockAtPos = player.dimension.getBlock({
              x: Math.floor(newPos.x),
              y: Math.floor(newPos.y),
              z: Math.floor(newPos.z)
            });

            if (blockAtPos && blockAtPos.typeId !== "minecraft:air") {
              hitSomething = true;
              player.runCommandAsync(
                `particle minecraft:villager_happy ${newPos.x.toFixed(2)} ${newPos.y.toFixed(2)} ${newPos.z.toFixed(2)}`
              );

              try {
                projectile.triggerEvent("carperc_mw:despawn");
              } catch (e) {
                if (projectile?.isValid()) projectile.remove();
              }
              system.clearRun(moveInterval);
              return;
            }
          } catch (e) { }

        }, 1);
      }

      await player.runCommandAsync("playsound random.bow @s ~ ~ ~ 0.8 1.4");

    } catch (err) {
      console.error("Juice Blaster 9000 failed:", err);
    }
  }
});