import { system, world, EquipmentSlot, EntityEquippableComponent, ItemStack } from "@minecraft/server";
import { afterEvents } from "./eternal/constants";
import { disallowedBlocks_pile_of_pebbles } from "./globalVariables.js";

/////////////////////////////////////////////////////

world.afterEvents.playerSpawn.subscribe((e) => {
  if (!e.initialSpawn) return;
  if (!e.player.hasTag("ecbl_bc:has_guidebook")) {
    const guidebook = new ItemStack("ecbl_bc:guidebook");
    e.player.dimension.spawnItem(guidebook, e.player.location);
    world.sendMessage("§c[!] §rThe §gBiomeCraft Add-On§r has been added.");
    world.sendMessage("You have been given a Guidebook.");
    e.player.addTag("ecbl_bc:has_guidebook");
  }
});

const axeIds = [
  "minecraft:wooden_axe",
  "minecraft:stone_axe",
  "minecraft:iron_axe",
  "minecraft:diamond_axe",
  "minecraft:golden_axe",
  "minecraft:netherite_axe",
];

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (axeIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:baobab_log")) {
      const blockPosition = block.location;

      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_baobab_log`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:baobab_wood")) {
      const blockPosition = block.location;
      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_baobab_wood`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:kapok_log")) {
      const blockPosition = block.location;

      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_kapok_log`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:kapok_wood")) {
      const blockPosition = block.location;
      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_kapok_wood`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:mossy_kapok_log")) {
      const blockPosition = block.location;
      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_kapok_log`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:redwood_wood")) {
      const blockPosition = block.location;
      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_redwood_wood`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:mossy_redwood_log")) {
      const blockPosition = block.location;
      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_redwood_log`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:redwood_log")) {
      const blockPosition = block.location;

      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:stripped_redwood_log`);
        player.playSound("use.wood", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
  }
});

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  // Define os blocos permitidos para interação
  const allowedBlocks = [
    "ecbl_bc:redwood_log",
    "ecbl_bc:mossy_redwood_log",
    // Adicione outros blocos permitidos aqui
  ];

  // Define os blocos não permitidos
  const disallowedBlocks = [
    "minecraft:grass_block",
    "minecraft:dirt",
    "ecbl_bc:dry_grass_block",
    // Adicione outros blocos não permitidos aqui
  ];

  // Verifica se o item usado é um item glowing_mushroom
  if (itemUsed.typeId === "ecbl_bc:glowing_mushroom") {
    const blockPosition = block.location;

    // Verifica se o bloco alvo é um dos blocos permitidos
    if (allowedBlocks.some((allowedBlock) => block.permutation.matches(allowedBlock))) {
      // Interação com o lado norte
      player.runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z - 1} ecbl_bc:glowing_mushroom`).then((result) => {
        if (result.successCount > 0) {
          player.runCommand(
            `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z - 1} ecbl_bc:glowing_mushroom.fan_side["minecraft:cardinal_direction"="north"]`
          );
        }
      });

      // Interação com o lado sul
      player.runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z + 1} ecbl_bc:glowing_mushroom`).then((result) => {
        if (result.successCount > 0) {
          player.runCommand(
            `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z + 1} ecbl_bc:glowing_mushroom.fan_side["minecraft:cardinal_direction"="south"]`
          );
        }
      });

      // Interação com o lado oeste
      player.runCommandAsync(`testforblock ${blockPosition.x - 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:glowing_mushroom`).then((result) => {
        if (result.successCount > 0) {
          player.runCommand(
            `setblock ${blockPosition.x - 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:glowing_mushroom.fan_side["minecraft:cardinal_direction"="west"]`
          );
        }
      });

      // Interação com o lado leste
      player.runCommandAsync(`testforblock ${blockPosition.x + 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:glowing_mushroom`).then((result) => {
        if (result.successCount > 0) {
          player.runCommand(
            `setblock ${blockPosition.x + 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:glowing_mushroom.fan_side["minecraft:cardinal_direction"="east"]`
          );
        }
      });

      // Interação com o topo
      player.runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:glowing_mushroom`).then((result) => {
        if (result.successCount > 0) {
          player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:glowing_mushroom.fan_top`);
        }
      });
    } else if (disallowedBlocks.some((disallowedBlock) => block.permutation.matches(disallowedBlock))) {
      // Quebra o cogumelo nas laterais se o bloco não for permitido e aplica destroy
      const directions = [
        { x: 1, y: 0, z: 0 }, // Leste
        { x: -1, y: 0, z: 0 }, // Oeste
        { x: 0, y: 0, z: 1 }, // Sul
        { x: 0, y: 0, z: -1 }, // Norte
      ];

      directions.forEach((offset) => {
        const targetPosition = { x: blockPosition.x + offset.x, y: blockPosition.y + offset.y, z: blockPosition.z + offset.z };
        player.runCommandAsync(`testforblock ${targetPosition.x} ${targetPosition.y} ${targetPosition.z} ecbl_bc:glowing_mushroom`).then((result) => {
          if (result.successCount > 0) {
            player.runCommand(`setblock ${targetPosition.x} ${targetPosition.y} ${targetPosition.z} air destroy`);
          }
        });
      });
    }
  }
});

const allowedBlocksLogs = [
  "ecbl_bc:hollow_birch_log_normal",
  "ecbl_bc:hollow_birch_log_mossy",
  "ecbl_bc:hollow_birch_log_branches",
  "ecbl_bc:hollow_birch_log_red_mushrooms",
  "ecbl_bc:hollow_birch_log_brown_mushrooms",
  "ecbl_bc:mossy_redwood_log",
  "ecbl_bc:redwood_log",
  "ecbl_bc:baobab_log",
  "ecbl_bc:deadwood_log",
  "ecbl_bc:kapok_log",
  "ecbl_bc:mossy_kapok_log",
  "minecraft:oak_log",
  "minecraft:spruce_log",
  "minecraft:birch_log",
  "minecraft:jungle_log",
  "minecraft:acacia_log",
  "minecraft:dark_oak_log",
  "minecraft:cherry_log",
  "minecraft:pale_oak_log",
  "minecraft:mangrove_log",
];

const playerCooldownMushroom = {};

world.beforeEvents.playerInteractWithBlock.subscribe(async (ev) => {
  const { player, block, itemStack, blockFace } = ev;
  const blockPosition = block ? block.location : null;
  const playerId = player.id;

  // Obter o tempo atual em milissegundos
  const currentTime = Date.now();

  // Verificar se block e itemStack estão definidos e se allowedBlocksLogs inclui o tipo de bloco
  if (block && itemStack && allowedBlocksLogs.includes(block.typeId)) {
    if (itemStack.typeId === "minecraft:brown_mushroom") {
      // Verificar se o jogador está no cooldown específico para cogumelos
      if (!playerCooldownMushroom[playerId] || currentTime - playerCooldownMushroom[playerId] > 700) {
        // 700 ms = 0.7 segundos
        // Atualizar o tempo do último comando executado pelo jogador
        playerCooldownMushroom[playerId] = currentTime;

        switch (blockFace) {
          case "North":
            await player.runCommandAsync(
              `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z - 1} ecbl_bc:brown_mushroom.fan_side["minecraft:cardinal_direction"="north"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:brown_mushroom 0 1`);
            }
            break;
          case "South":
            await player.runCommandAsync(
              `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z + 1} ecbl_bc:brown_mushroom.fan_side["minecraft:cardinal_direction"="south"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:brown_mushroom 0 1`);
            }
            break;
          case "East":
            await player.runCommandAsync(
              `setblock ${blockPosition.x + 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:brown_mushroom.fan_side["minecraft:cardinal_direction"="east"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:brown_mushroom 0 1`);
            }
            break;
          case "West":
            await player.runCommandAsync(
              `setblock ${blockPosition.x - 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:brown_mushroom.fan_side["minecraft:cardinal_direction"="west"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:brown_mushroom 0 1`);
            }
            break;
          case "Up":
            await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:brown_mushroom.fan_top`);
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:brown_mushroom 0 1`);
            }
            break;
        }
      }
    }
  }
});

const playerCooldownRedMushroom = {};

world.beforeEvents.playerInteractWithBlock.subscribe(async (ev) => {
  const { player, block, itemStack, blockFace } = ev;
  const blockPosition = block ? block.location : null;
  const playerId = player.id;

  // Obter o tempo atual em milissegundos
  const currentTime = Date.now();

  // Verificar se block e itemStack estão definidos e se allowedBlocksLogs inclui o tipo de bloco
  if (block && itemStack && allowedBlocksLogs.includes(block.typeId)) {
    if (itemStack.typeId === "minecraft:red_mushroom") {
      // Verificar se o jogador está no cooldown específico para cogumelos vermelhos
      if (!playerCooldownRedMushroom[playerId] || currentTime - playerCooldownRedMushroom[playerId] > 700) {
        // 700 ms = 0.7 segundos
        // Atualizar o tempo do último comando executado pelo jogador
        playerCooldownRedMushroom[playerId] = currentTime;

        switch (blockFace) {
          case "North":
            await player.runCommandAsync(
              `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z - 1} ecbl_bc:red_mushroom.fan_side["minecraft:cardinal_direction"="north"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:red_mushroom 0 1`);
            }
            break;
          case "South":
            await player.runCommandAsync(
              `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z + 1} ecbl_bc:red_mushroom.fan_side["minecraft:cardinal_direction"="south"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:red_mushroom 0 1`);
            }
            break;
          case "East":
            await player.runCommandAsync(
              `setblock ${blockPosition.x + 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:red_mushroom.fan_side["minecraft:cardinal_direction"="east"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:red_mushroom 0 1`);
            }
            break;
          case "West":
            await player.runCommandAsync(
              `setblock ${blockPosition.x - 1} ${blockPosition.y} ${blockPosition.z} ecbl_bc:red_mushroom.fan_side["minecraft:cardinal_direction"="west"]`
            );
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:red_mushroom 0 1`);
            }
            break;
          case "Up":
            await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:red_mushroom.fan_top`);
            await player.runCommandAsync(`playsound dig.grass @s ~~~ 0.1`);
            if (player.getGameMode() !== "creative") {
              player.runCommandAsync(`clear @s minecraft:red_mushroom 0 1`);
            }
            break;
        }
      }
    }
  }
});

const hoeIds = [
  "minecraft:wooden_hoe",
  "minecraft:stone_hoe",
  "minecraft:iron_hoe",
  "minecraft:diamond_hoe",
  "minecraft:golden_hoe",
  "minecraft:netherite_hoe",
];

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (hoeIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:dry_grass_block")) {
      const blockPosition = block.location;

      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} minecraft:farmland`);
        player.playSound("use.dirt_with_roots", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:dry_grass_block")) {
      const blockPosition = block.location;
      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} minecraft:farmland`);
        player.playSound("use.dirt_with_roots", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
    if (block.permutation.matches("ecbl_bc:prairie_grass_block")) {
      const blockPosition = block.location;
      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} minecraft:farmland`);
        player.playSound("use.dirt_with_roots", { pitch: 1, location: blockPosition, volume: 1 });
      });
    }
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  const currentTime = Date.now();
  let lastInteractionTime = 0;
  let player = data.player;
  let placing = data.itemStack;
  let block = data.block;

  if (block.typeId == "ecbl_bc:prickly_pear_cactus_crop") {
    const blockPosition = block.location;
    const randomChance = Math.random();

    // Verifica se passou tempo suficiente desde a última interação
    if (currentTime - lastInteractionTime > 100) {
      // 1000 ms = 1 segundo
      lastInteractionTime = currentTime;

      system.runTimeout(() => {
        const testForCommand = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:prickly_pear_cactus_crop["ecbl_bc:growth"=3]`;

        player.runCommandAsync(testForCommand).then((result) => {
          if (result.successCount > 0) {
            // Usando testfor para verificar se o jogador está segurando "stick" na mão principal
            const testForStickCommand = `/testfor @s[hasitem={item=stick,location=slot.weapon.mainhand}]`;
            player.runCommandAsync(testForStickCommand).then((stickResult) => {
              if (stickResult.successCount > 0) {
                // Se o jogador estiver segurando stick
                player.runCommand(`structure load "ecbl_bc/cactus_fruit" ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
                player.runCommand(`playsound block.sweet_berry_bush.hurt @s`);
                player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:prickly_pear_cactus_crop["ecbl_bc:growth"=2]`);
              }
            });
          }
        }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
      });
    }
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  const currentTime = Date.now();
  let lastInteractionTime = 0;
  let player = data.player;
  let placing = data.itemStack;
  let block = data.block;

  if (block.typeId == "ecbl_bc:prickly_pear_cactus_crop") {
    const blockPosition = block.location;
    const randomChance = Math.random();

    // Verifica se passou tempo suficiente desde a última interação
    if (currentTime - lastInteractionTime > 100) {
      // 1000 ms = 1 segundo
      lastInteractionTime = currentTime;

      system.runTimeout(() => {
        const testForCommand = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:prickly_pear_cactus_crop["ecbl_bc:growth"=3]`;

        player.runCommandAsync(testForCommand).then((result) => {
          if (result.successCount > 0) {
            // Usando testfor para verificar se o jogador está segurando "stick" na mão principal
            const testForStickCommand = `/testfor @s[hasitem={item=stick,location=slot.weapon.mainhand}]`;
            player.runCommandAsync(testForStickCommand).then((stickResult) => {
              if (stickResult.successCount == 0) {
                // Se o jogador estiver segurando stick

                const testForStickCommand = `/testfor @s[hasitem={item=bone_meal,location=slot.weapon.mainhand}]`;
                player.runCommandAsync(testForStickCommand).then((stickResult) => {
                  if (stickResult.successCount == 0) {
                    player.runCommand(`structure load "ecbl_bc/cactus_fruit" ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
                    player.runCommand(`playsound block.sweet_berry_bush.hurt @s`);
                    player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:prickly_pear_cactus_crop["ecbl_bc:growth"=2]`);
                    player.runCommand(`damage @s 2`);
                  }
                });
              }
            }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
          }
        });
      });
    }
  }
});

// Objeto para rastrear o cooldown de cada jogador
const playerCooldowns = {};

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let block = data.block;
  const playerId = player.id;
  const currentTime = Date.now();

  // Verificar se o bloco é do tipo correto
  if (block.typeId === "ecbl_bc:pile_of_pebbles") {
    const blockPosition = block.location;

    // Verificar o cooldown do jogador
    if (!playerCooldowns[playerId] || currentTime - playerCooldowns[playerId] > 700) {
      // 3000 ms = 3 segundos de cooldown
      // Atualizar o último tempo de interação do jogador
      playerCooldowns[playerId] = currentTime;

      system.run(() => {
        const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:pile_of_pebbles,location=slot.weapon.mainhand}]`;

        player.runCommandAsync(testForStickCommand).then((stickResultWest) => {
          if (stickResultWest.successCount > 0) {
            const blockPermutation = block.permutation;
            const quantityState = blockPermutation.getState("ecbl_bc:quantity");

            if (quantityState !== undefined && quantityState < 3) {
              player.runCommand(`playsound dig.stone @s`);
              const newQuantity = quantityState + 1;
              block.setPermutation(blockPermutation.withState("ecbl_bc:quantity", newQuantity));

              if (player.getGameMode() !== "creative") {
                player.runCommand(`clear @s ecbl_bc:pile_of_pebbles 0 1`);
              }
            }
          }
        });
      });
    }
  }
});

const playerCooldownDuckweed = {};

world.beforeEvents.playerInteractWithBlock.subscribe(async (ev) => {
  const { player, block, itemStack, blockFace } = ev;
  const blockPosition = block ? block.location : null;
  const playerId = player.id;

  // Obter o tempo atual em milissegundos
  const currentTime = Date.now();

  // Verificar se block e itemStack estão definidos
  if (block && itemStack) {
    // Verificar se o jogador está no cooldown específico para duckweed
    if (!playerCooldownDuckweed[playerId] || currentTime - playerCooldownDuckweed[playerId] > 700) {
      // 700 ms = 0.7 segundos
      // Atualizar o tempo do último comando executado pelo jogador
      playerCooldownDuckweed[playerId] = currentTime;

      // Verificar se o bloco é água e se o item usado é duckweed
      if (block.permutation.matches("minecraft:water") && itemStack.typeId === "ecbl_bc:duckweed" && blockFace === "Up") {
        // Definir o bloco de Duckweed
        await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:duckweed keep`);
        await player.runCommandAsync(
          `/fill ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} water replace ecbl_bc:duckweed`
        );
        await player.runCommandAsync(
          `/fill ${blockPosition.x + 1} ${blockPosition.y} ${blockPosition.z + 1} ${blockPosition.x - 1} ${blockPosition.y} ${blockPosition.z - 1
          } water replace flowing_water`
        );
        if (player.getGameMode() !== "creative") {
          await player.runCommandAsync(`clear @s ecbl_bc:duckweed 0 1`);
        }
      }
    }
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let placing = data.itemStack;
  let block = data.block;

  if (block.typeId == "ecbl_bc:clover") {
    const blockPosition = block.location;

    system.run(() => {
      const testForCommand = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="east"]`;

      player.runCommandAsync(testForCommand).then((result) => {
        if (result.successCount > 0) {
          // Usando testfor para verificar se o jogador está segurando "stick" na mão principal
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResult) => {
            if (stickResult.successCount == 1) {
              // Se o jogador estiver segurando stick
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);

              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1]`);
            }
          }); // Adiciona um atraso de 1 segundo (20 ticks)
        }
      });
    });
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let placing = data.itemStack;
  let block = data.block;

  if (block.typeId == "ecbl_bc:clover") {
    const blockPosition = block.location;

    system.run(() => {
      const testForCommand = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="north"]`;

      player.runCommandAsync(testForCommand).then((result) => {
        if (result.successCount > 0) {
          // Usando testfor para verificar se o jogador está segurando "stick" na mão principal
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResult) => {
            if (stickResult.successCount == 1) {
              // Se o jogador estiver segurando stick
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);

              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1]`);
            }
          }); // Adiciona um atraso de 1 segundo (20 ticks)
        }
      });
    });
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let placing = data.itemStack;
  let block = data.block;

  if (block.typeId == "ecbl_bc:clover") {
    const blockPosition = block.location;

    system.run(() => {
      const testForCommand = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="south"]`;

      player.runCommandAsync(testForCommand).then((result) => {
        if (result.successCount > 0) {
          // Usando testfor para verificar se o jogador está segurando "stick" na mão principal
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResult) => {
            if (stickResult.successCount == 1) {
              // Se o jogador estiver segurando stick
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);

              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1]`);
            }
          }); // Adiciona um atraso de 1 segundo (20 ticks)
        }
      });
    });
  }
});

//clover//

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let block = data.block;

  if (block.typeId == "ecbl_bc:clover") {
    const blockPosition = block.location;

    system.run(() => {
      // --- Verificação para a direção "west" ---
      const testForCommandWest = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="west"]`;

      player.runCommandAsync(testForCommandWest).then((resultWest) => {
        if (resultWest.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultWest) => {
            if (stickResultWest.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="west"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "east" ---
      const testForCommandEast = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="east"]`;

      player.runCommandAsync(testForCommandEast).then((resultEast) => {
        if (resultEast.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultEast) => {
            if (stickResultEast.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="east"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "north" ---
      const testForCommandNorth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="north"]`;

      player.runCommandAsync(testForCommandNorth).then((resultNorth) => {
        if (resultNorth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultNorth) => {
            if (stickResultNorth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="north"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "south" ---
      const testForCommandSouth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="south"]`;

      player.runCommandAsync(testForCommandSouth).then((resultSouth) => {
        if (resultSouth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultSouth) => {
            if (stickResultSouth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="south"]`
              );
            }
          });
        }
      });
    });
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let block = data.block;

  if (block.typeId == "ecbl_bc:clover") {
    const blockPosition = block.location;

    system.run(() => {
      // --- Verificação para a direção "west" ---
      const testForCommandWest = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="west"]`;

      player.runCommandAsync(testForCommandWest).then((resultWest) => {
        if (resultWest.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultWest) => {
            if (stickResultWest.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="west"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "east" ---
      const testForCommandEast = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="east"]`;

      player.runCommandAsync(testForCommandEast).then((resultEast) => {
        if (resultEast.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultEast) => {
            if (stickResultEast.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="east"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "north" ---
      const testForCommandNorth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="north"]`;

      player.runCommandAsync(testForCommandNorth).then((resultNorth) => {
        if (resultNorth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultNorth) => {
            if (stickResultNorth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="north"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "south" ---
      const testForCommandSouth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="south"]`;

      player.runCommandAsync(testForCommandSouth).then((resultSouth) => {
        if (resultSouth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultSouth) => {
            if (stickResultSouth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="south"]`
              );
            }
          });
        }
      });
    });
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let block = data.block;

  if (block.typeId == "ecbl_bc:clover") {
    const blockPosition = block.location;

    system.run(() => {
      // --- Verificação para a direção "west" ---
      const testForCommandWest = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="west"]`;

      player.runCommandAsync(testForCommandWest).then((resultWest) => {
        if (resultWest.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultWest) => {
            if (stickResultWest.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="west"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "east" ---
      const testForCommandEast = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="east"]`;

      player.runCommandAsync(testForCommandEast).then((resultEast) => {
        if (resultEast.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultEast) => {
            if (stickResultEast.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="east"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "north" ---
      const testForCommandNorth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="north"]`;

      player.runCommandAsync(testForCommandNorth).then((resultNorth) => {
        if (resultNorth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultNorth) => {
            if (stickResultNorth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="north"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "south" ---
      const testForCommandSouth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="south"]`;

      player.runCommandAsync(testForCommandSouth).then((resultSouth) => {
        if (resultSouth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:clover,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultSouth) => {
            if (stickResultSouth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:clover 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:clover["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="south"]`
              );
            }
          });
        }
      });
    });
  }
});

///wood anemones///

//wood_anemones//

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let block = data.block;

  if (block.typeId == "ecbl_bc:wood_anemones") {
    const blockPosition = block.location;

    system.run(() => {
      // --- Verificação para a direção "west" ---
      const testForCommandWest = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="west"]`;

      player.runCommandAsync(testForCommandWest).then((resultWest) => {
        if (resultWest.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultWest) => {
            if (stickResultWest.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="west"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "east" ---
      const testForCommandEast = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="east"]`;

      player.runCommandAsync(testForCommandEast).then((resultEast) => {
        if (resultEast.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultEast) => {
            if (stickResultEast.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="east"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "north" ---
      const testForCommandNorth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="north"]`;

      player.runCommandAsync(testForCommandNorth).then((resultNorth) => {
        if (resultNorth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultNorth) => {
            if (stickResultNorth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="north"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "south" ---
      const testForCommandSouth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=0,"minecraft:cardinal_direction"="south"]`;

      player.runCommandAsync(testForCommandSouth).then((resultSouth) => {
        if (resultSouth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;
          player.runCommandAsync(testForStickCommand).then((stickResultSouth) => {
            if (stickResultSouth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);
              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="south"]`
              );
            }
          });
        }
      });
    });
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let block = data.block;

  if (block.typeId == "ecbl_bc:wood_anemones") {
    const blockPosition = block.location;

    system.run(() => {
      // --- Verificação para a direção "west" ---
      const testForCommandWest = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="west"]`;

      player.runCommandAsync(testForCommandWest).then((resultWest) => {
        if (resultWest.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultWest) => {
            if (stickResultWest.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="west"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "east" ---
      const testForCommandEast = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="east"]`;

      player.runCommandAsync(testForCommandEast).then((resultEast) => {
        if (resultEast.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultEast) => {
            if (stickResultEast.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="east"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "north" ---
      const testForCommandNorth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="north"]`;

      player.runCommandAsync(testForCommandNorth).then((resultNorth) => {
        if (resultNorth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultNorth) => {
            if (stickResultNorth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="north"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "south" ---
      const testForCommandSouth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=1,"minecraft:cardinal_direction"="south"]`;

      player.runCommandAsync(testForCommandSouth).then((resultSouth) => {
        if (resultSouth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultSouth) => {
            if (stickResultSouth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="south"]`
              );
            }
          });
        }
      });
    });
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  let player = data.player;
  let block = data.block;

  if (block.typeId == "ecbl_bc:wood_anemones") {
    const blockPosition = block.location;

    system.run(() => {
      // --- Verificação para a direção "west" ---
      const testForCommandWest = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="west"]`;

      player.runCommandAsync(testForCommandWest).then((resultWest) => {
        if (resultWest.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultWest) => {
            if (stickResultWest.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="west"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "east" ---
      const testForCommandEast = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="east"]`;

      player.runCommandAsync(testForCommandEast).then((resultEast) => {
        if (resultEast.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultEast) => {
            if (stickResultEast.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="east"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "north" ---
      const testForCommandNorth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="north"]`;

      player.runCommandAsync(testForCommandNorth).then((resultNorth) => {
        if (resultNorth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultNorth) => {
            if (stickResultNorth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="north"]`
              );
            }
          });
        }
      });

      // --- Verificação para a direção "south" ---
      const testForCommandSouth = `testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=2,"minecraft:cardinal_direction"="south"]`;

      player.runCommandAsync(testForCommandSouth).then((resultSouth) => {
        if (resultSouth.successCount > 0) {
          const testForStickCommand = `testfor @s[hasitem={item=ecbl_bc:wood_anemones,location=slot.weapon.mainhand}]`;

          player.runCommandAsync(testForStickCommand).then((stickResultSouth) => {
            if (stickResultSouth.successCount == 1) {
              player.runCommand(`clear @s ecbl_bc:wood_anemones 0 1`);
              player.runCommand(`playsound dig.grass @s`);

              player.runCommand(
                `setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:wood_anemones["ecbl_bc:quantity"=3,"minecraft:cardinal_direction"="south"]`
              );
            }
          });
        }
      });
    });
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  const currentTime = Date.now();
  let lastInteractionTime = 0;
  let player = data.player;
  let placing = data.itemStack;
  let block = data.block;
  if (block.typeId == "ecbl_bc:dead_shrub") {
    const blockPosition = block.location;
    const randomChance = Math.random();

    // Verifica se passou tempo suficiente desde a última interação
    if (currentTime - lastInteractionTime > 100) {
      // 1000 ms = 1 segundo
      lastInteractionTime = currentTime;

      system.runTimeout(() => {
        if (randomChance < 0.3) {
          player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} minecraft:air destroy`);
          player.runCommand(`playsound block.sweet_berry_bush.break @s`);
        } else {
          // Carrega a estrutura um bloco acima
          player.runCommand(`structure load "ecbl_bc/stick_drop" ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
          player.runCommand(`playsound block.sweet_berry_bush.hurt @s`);
        }
      }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
    }
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
  const currentTime = Date.now();
  let lastInteractionTime = 0;
  let player = data.player;
  let placing = data.itemStack;
  let block = data.block;
  if (block.typeId == "ecbl_bc:apple_block") {
    const blockPosition = block.location;

    // Verifica se passou tempo suficiente desde a última interação
    if (currentTime - lastInteractionTime > 100) {
      // 1000 ms = 1 segundo
      lastInteractionTime = currentTime;

      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} minecraft:air`);
        player.runCommand(`structure load "ecbl_bc/apple_block" ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
        player.runCommand(`playsound random.pop @s`);
      });
      // Adiciona um atraso de 1 segundo (20 ticks)
    }
  }
});

const BoneMealIds = ["minecraft:bone_meal"];

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (BoneMealIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:baobab_sapling")) {
      const randomChance = Math.random();
      const blockPosition = block.location;
      system.runTimeout(() => {
        if (randomChance < 0.3) {
          player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
          player.runCommand(`playsound item.bone_meal.use @a`);

          const randomChoice = Math.floor(Math.random() * 7);

          // Executa um dos comandos de setblock aleatoriamente
          system.run(() => {
            switch (randomChoice) {
              case 0:
                player.runCommand(`structure load "ecbl_bc/baobab_tree_1" ${blockPosition.x - 4} ${blockPosition.y} ${blockPosition.z - 4}`);

                break;
              case 1:
                player.runCommand(`structure load "ecbl_bc/baobab_tree_2" ${blockPosition.x - 7} ${blockPosition.y} ${blockPosition.z - 6}`);

                break;
              case 2:
                player.runCommand(`structure load "ecbl_bc/baobab_tree_3" ${blockPosition.x - 5} ${blockPosition.y} ${blockPosition.z - 6}`);

                break;
              case 3:
                player.runCommand(`structure load "ecbl_bc/baobab_tree_4" ${blockPosition.x - 7} ${blockPosition.y} ${blockPosition.z - 6}`);

                break;
              case 4:
                player.runCommand(`structure load "ecbl_bc/baobab_tree_5" ${blockPosition.x - 3} ${blockPosition.y} ${blockPosition.z - 4}`);

                break;
              case 5:
                player.runCommand(`structure load "ecbl_bc/baobab_tree_6" ${blockPosition.x - 7} ${blockPosition.y} ${blockPosition.z - 6}`);

                break;
              case 6:
                player.runCommand(`structure load "ecbl_bc/baobab_tree_7" ${blockPosition.x - 7} ${blockPosition.y} ${blockPosition.z - 6}`);

                break;
            }
          }); // Adiciona um atraso de 1 segundo (20 ticks)
        } else {
          // Carrega a estrutura um bloco acima
          player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
          player.runCommand(`playsound item.bone_meal.use @a`);
        }
      }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
    }
  }
});

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (BoneMealIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:redwood_sapling")) {
      const randomChance = Math.random();
      const blockPosition = block.location;
      system.runTimeout(() => {
        if (randomChance < 0.3) {
          player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
          player.runCommand(`playsound item.bone_meal.use @a`);

          const randomChoice = Math.floor(Math.random() * 5);

          // Executa um dos comandos de setblock aleatoriamente
          system.run(() => {
            switch (randomChoice) {
              case 0:
                player.runCommand(`structure load "ecbl_bc/redwood_t_1" ${blockPosition.x - 4} ${blockPosition.y} ${blockPosition.z - 4}`);
                break;
              case 1:
                player.runCommand(`structure load "ecbl_bc/redwood_t_2" ${blockPosition.x - 5} ${blockPosition.y} ${blockPosition.z - 5}`);

                break;
              case 2:
                player.runCommand(`structure load "ecbl_bc/redwood_t_3" ${blockPosition.x - 5} ${blockPosition.y} ${blockPosition.z - 6}`);

                break;
              case 3:
                player.runCommand(`structure load "ecbl_bc/redwood_t_4" ${blockPosition.x - 7} ${blockPosition.y} ${blockPosition.z - 6}`);
                break;
              case 4:
                player.runCommand(`structure load "ecbl_bc/redwood_t_5" ${blockPosition.x - 3} ${blockPosition.y} ${blockPosition.z - 4}`);
                break;
            }
          }); // Adiciona um atraso de 1 segundo (20 ticks)
        } else {
          // Carrega a estrutura um bloco acima
          player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
          player.runCommand(`playsound item.bone_meal.use @a`);
        }
      }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
    }
  }
});

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (BoneMealIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:kapok_sapling")) {
      const randomChance = Math.random();
      const blockPosition = block.location;
      system.runTimeout(() => {
        if (randomChance < 0.3) {
          player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
          player.runCommand(`playsound item.bone_meal.use @a`);

          const randomChoice = Math.floor(Math.random() * 3);

          // Executa um dos comandos de setblock aleatoriamente
          system.run(() => {
            switch (randomChoice) {
              case 0:
                player.runCommand(`structure load "ecbl_bc/jungle_t_1" ${blockPosition.x - 6} ${blockPosition.y} ${blockPosition.z - 4}`);
                break;
              case 1:
                player.runCommand(`structure load "ecbl_bc/jungle_t_2" ${blockPosition.x - 7} ${blockPosition.y} ${blockPosition.z - 6}`);
                break;
              case 2:
                player.runCommand(`structure load "ecbl_bc/jungle_t_3" ${blockPosition.x - 8} ${blockPosition.y} ${blockPosition.z - 8}`);

                break;
            }
          }); // Adiciona um atraso de 1 segundo (20 ticks)
        } else {
          // Carrega a estrutura um bloco acima
          player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
          player.runCommand(`playsound item.bone_meal.use @a`);
        }
      }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
    }
  }
});

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (BoneMealIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:climbing_vines")) {
      const randomChance = Math.random();
      const blockPosition = block.location;
      system.runTimeout(() => {
        player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y - 1} ${blockPosition.z}`);
        player.runCommand(`playsound item.bone_meal.use @a`);
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y - 1} ${blockPosition.z} ecbl_bc:climbing_vines keep`);
      }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
    }
  }
});

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (BoneMealIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:glowing_mushroom")) {
      const randomChance = Math.random();
      const blockPosition = block.location;
      system.runTimeout(() => {
        player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
        player.runCommand(`playsound item.bone_meal.use @a`);
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:bounce_mushroom`);
      }, 1); // Adiciona um atraso de 1 segundo (20 ticks)
    }
  }
});

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (BoneMealIds.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:corn_block")) {
      const randomChance = Math.random();
      const blockPosition = block.location;
      system.runTimeout(() => {
        const testForCommand = `testforblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=0,"ecbl_bc:growth_up_or_down"=false]`;
        const testForCommand2 = `testforblock ${block.location.x} ${block.location.y + 1} ${block.location.z
          } ecbl_bc:corn_block["ecbl_bc:growth_corn"=0,"ecbl_bc:growth_up_or_down"=true]`;

        world.getAllPlayers().forEach((player) => {
          player.runCommandAsync(testForCommand).then((result) => {
            if (result.successCount > 0) {
              world.getAllPlayers().forEach((player) => {
                player.runCommandAsync(testForCommand2).then((result) => {
                  if (result.successCount > 0) {
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
                    player.runCommand(`playsound item.bone_meal.use @a`);
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=false]`
                    );
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
                      } ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=true]`
                    );
                  }
                });
              });
            }
          });
        });
        const testForCommand3 = `testforblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=false]`;
        const testForCommand4 = `testforblock ${block.location.x} ${block.location.y + 1} ${block.location.z
          } ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=true]`;

        world.getAllPlayers().forEach((player) => {
          player.runCommandAsync(testForCommand3).then((result) => {
            if (result.successCount > 0) {
              world.getAllPlayers().forEach((player) => {
                player.runCommandAsync(testForCommand4).then((result) => {
                  if (result.successCount > 0) {
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
                    player.runCommand(`playsound item.bone_meal.use @a`);
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=false]`
                    );
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
                      } ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=true]`
                    );
                  }
                });
              });
            }
          });
        });
        const testForCommand5 = `testforblock ${block.location.x} ${block.location.y - 1} ${block.location.z
          } ecbl_bc:corn_block["ecbl_bc:growth_corn"=0,"ecbl_bc:growth_up_or_down"=false]`;
        const testForCommand6 = `testforblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=0,"ecbl_bc:growth_up_or_down"=true]`;

        world.getAllPlayers().forEach((player) => {
          player.runCommandAsync(testForCommand5).then((result) => {
            if (result.successCount > 0) {
              world.getAllPlayers().forEach((player) => {
                player.runCommandAsync(testForCommand6).then((result) => {
                  if (result.successCount > 0) {
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
                    player.runCommand(`playsound item.bone_meal.use @a`);
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y - 1} ${block.location.z
                      } ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=false]`
                    );
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=true]`
                    );
                  }
                });
              });
            }
          });
        });
        const testForCommand7 = `testforblock ${block.location.x} ${block.location.y - 1} ${block.location.z
          } ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=false]`;
        const testForCommand8 = `testforblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=1,"ecbl_bc:growth_up_or_down"=true]`;

        world.getAllPlayers().forEach((player) => {
          player.runCommandAsync(testForCommand7).then((result) => {
            if (result.successCount > 0) {
              world.getAllPlayers().forEach((player) => {
                player.runCommandAsync(testForCommand8).then((result) => {
                  if (result.successCount > 0) {
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z}`);
                    player.runCommand(`particle minecraft:crop_growth_emitter ${blockPosition.x} ${blockPosition.y} ${blockPosition.z}`);
                    player.runCommand(`playsound item.bone_meal.use @a`);
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y - 1} ${block.location.z
                      } ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=false]`
                    );
                    player.runCommandAsync(
                      `setblock ${block.location.x} ${block.location.y} ${block.location.z} ecbl_bc:corn_block["ecbl_bc:growth_corn"=2,"ecbl_bc:growth_up_or_down"=true]`
                    );
                  }
                });
              });
            }
          });
        });
        const testForCommand9 = `testforblock ${block.location.x} ${block.location.y - 1} ${block.location.z
          } ecbl_bc:heliconia_blooms["ecbl_bc:upper_block_bit"=true]`;

        world.getAllPlayers().forEach((player) => {
          player.runCommandAsync(testForCommand9).then((result) => {
            if (result.successCount > 0) {
              player.runCommandAsync(`setblock ${block.location.x} ${block.location.y} ${block.location.z} air`);
              player.runCommandAsync(`setblock ${block.location.x} ${block.location.y + 1} ${block.location.z} air`);
              player.runCommandAsync(`setblock ${block.location.x} ${block.location.y + 1} ${block.location.z} air`);
              player.runCommandAsync(`setblock ${block.location.x} ${block.location.y + 1} ${block.location.z} air`);
              player.runCommandAsync(`give @s ecbl_bc:heliconia_blooms`);
            }
          });
        });
      });
    }
  }
});

const playerCooldownLilypad = {};

world.beforeEvents.playerInteractWithBlock.subscribe(async (ev) => {
  const { player, block, itemStack, blockFace } = ev;
  const blockPosition = block ? block.location : null;
  const playerId = player.id;

  // Obter o tempo atual em milissegundos
  const currentTime = Date.now();

  // Verificar se block e itemStack estão definidos
  if (block && itemStack) {
    // Verificar se o jogador está no cooldown específico para lilypad big
    if (!playerCooldownLilypad[playerId] || currentTime - playerCooldownLilypad[playerId] > 700) {
      // 700 ms = 0.7 segundos
      // Atualizar o tempo do último comando executado pelo jogador
      playerCooldownLilypad[playerId] = currentTime;

      // Verificar se o bloco é água e se o item usado é lilypad big
      if (block.permutation.matches("minecraft:water") && itemStack.typeId === "ecbl_bc:lilypad_big" && blockFace === "Up") {
        // Definir o bloco de Lilypad Big
        await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:lilypad_big keep`);
        if (player.getGameMode() !== "creative") {
          await player.runCommandAsync(`clear @s ecbl_bc:lilypad_big 0 1`);
        }
      }
    }
  }
});

world.beforeEvents.playerInteractWithBlock.subscribe(async (ev) => {
  const { player, block, itemStack, blockFace } = ev;
  const blockPosition = block ? block.location : null;
  const playerId = player.id;

  // Verificar se block e itemStack estão definidos
  if (block && itemStack) {
    // Verificar se o bloco é água e se o item usado é lilypad giant
    if (block.permutation.matches("minecraft:water") && itemStack.typeId === "ecbl_bc:lilypad_giant" && blockFace === "Up") {
      // Definir o bloco de Lilypad Giant

      // Coordenadas relativas para verificação de blocos
      const positions = [
        { x: 1, y: 0, z: 1, blockType: "ecbl_bc:lilypad_fake_box_SE" },
        { x: -1, y: 0, z: 1, blockType: "ecbl_bc:lilypad_fake_box_SW" },
        { x: -1, y: 0, z: -1, blockType: "ecbl_bc:lilypad_fake_box_NW" },
        { x: 1, y: 0, z: -1, blockType: "ecbl_bc:lilypad_fake_box_NE" },
        { x: 1, y: 0, z: 0, blockType: "ecbl_bc:lilypad_fake_box_E" },
        { x: -1, y: 0, z: 0, blockType: "ecbl_bc:lilypad_fake_box_W" },
        { x: 0, y: 0, z: 1, blockType: "ecbl_bc:lilypad_fake_box_S" },
        { x: 0, y: 0, z: -1, blockType: "ecbl_bc:lilypad_fake_box_N" },
        { x: 0, y: 0, z: 0, blockType: "ecbl_bc:lilypad_giant" },
      ];

      // Verificação de todos os blocos ao redor
      for (const pos of positions) {
        const testForCommand = `testforblock ${blockPosition.x + pos.x} ${blockPosition.y + 1} ${blockPosition.z + pos.z} air`;
        const result = await player.runCommandAsync(testForCommand).catch(() => ({ successCount: 0 }));

        if (result.successCount === 0) {
          return; // Cancelar a colocação se qualquer bloco ao redor não for ar
        }
      }

      // Colocar blocos ao redor e o bloco lilypad_giant_block
      for (const pos of positions) {
        player.runCommandAsync(`setblock ${blockPosition.x + pos.x} ${blockPosition.y + 1} ${blockPosition.z + pos.z} ${pos.blockType}`);
      }

      // Limpar o item lilypad_giant do inventário se o jogador não estiver no modo criativo
      if (player.getGameMode() !== "creative") {
        await player.runCommandAsync(`clear @s ecbl_bc:lilypad_giant 0 1`);
      }
    }
  }
});

world.afterEvents.playerBreakBlock.subscribe((event) => {
  const { dimension, block, player } = event;
  if (player.getGameMode() !== "creative") {
    const blockPosition = block.location;
    if (event.brokenBlockPermutation.type.id == "ecbl_bc:lilypad_big") {
      dimension.runCommand(`structure load "ecbl_bc/lilypad_big" ${block.location.x} ${block.location.y} ${block.location.z}`);
    }
  }
});

const playerCooldownLilypadVanilla = {};

world.beforeEvents.playerInteractWithBlock.subscribe(async (ev) => {
  const { player, block, itemStack, blockFace } = ev;
  const blockPosition = block ? block.location : null;
  const playerId = player.id;

  // Obter o tempo atual em milissegundos
  const currentTime = Date.now();

  // Verificar se block e itemStack estão definidos
  if (block && itemStack) {
    // Verificar se o jogador está no cooldown específico para lilypad vanilla
    if (!playerCooldownLilypadVanilla[playerId] || currentTime - playerCooldownLilypadVanilla[playerId] > 700) {
      // 700 ms = 0.7 segundos
      // Atualizar o tempo do último comando executado pelo jogador
      playerCooldownLilypadVanilla[playerId] = currentTime;

      // Verificar se o bloco é água e se o item usado é lilypad vanilla
      if (block.permutation.matches("minecraft:water") && itemStack.typeId === "ecbl_bc:lilypad_vanilla" && blockFace === "Up") {
        // Gerar um número aleatório entre 0 e 2
        const randomChoice = Math.floor(Math.random() * 3);

        // Definir o bloco de Lilypad Vanilla aleatoriamente
        switch (randomChoice) {
          case 0:
            await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:lilypad_vanilla_1 keep`);
            break;
          case 1:
            await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:lilypad_vanilla_2 keep`);
            break;
          case 2:
            await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:lilypad_vanilla_3 keep`);
            break;
        }

        if (player.getGameMode() !== "creative") {
          await player.runCommandAsync(`clear @s ecbl_bc:lilypad_vanilla 0 1`);
        }
      }
    }
  }
});

world.afterEvents.playerBreakBlock.subscribe((event) => {
  const { dimension, block, player } = event;
  const blockPosition = block.location;
  if (player.getGameMode() !== "creative") {
    if (event.brokenBlockPermutation.type.id == "ecbl_bc:lilypad_vanilla_flower") {
      dimension.runCommand(`structure load "ecbl_bc/lilypad_vanilla" ${block.location.x} ${block.location.y} ${block.location.z}`);
    }
    if (event.brokenBlockPermutation.type.id == "ecbl_bc:lilypad_vanilla_1") {
      dimension.runCommand(`structure load "ecbl_bc/lilypad_vanilla" ${block.location.x} ${block.location.y} ${block.location.z}`);
    }
    if (event.brokenBlockPermutation.type.id == "ecbl_bc:lilypad_vanilla_2") {
      dimension.runCommand(`structure load "ecbl_bc/lilypad_vanilla" ${block.location.x} ${block.location.y} ${block.location.z}`);
    }
    if (event.brokenBlockPermutation.type.id == "ecbl_bc:lilypad_vanilla_3") {
      dimension.runCommand(`structure load "ecbl_bc/lilypad_vanilla" ${block.location.x} ${block.location.y} ${block.location.z}`);
    }
  }
});

// Identificadores dos blocos que ativam o evento
const Block_ID = [
  "ecbl_bc:kapok_log", // Substitua por outros identificadores de blocos, se necessário
];

// Evento de colocação de bloco por um jogador
world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension } = event;

  // Verifica se o bloco colocado está na lista de identificadores
  if (Block_ID.includes(block.typeId)) {
    const blockPosition = block.location;
    const randomChoice = Math.random();

    // Testa o bloco na posição norte com a face norte
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="north"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:kapok_log no lado norte
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="north"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_kapok_log no lado norte
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_kapok_log["minecraft:block_face"="north"]`);
          }
        }
      });

    // Testa o bloco na posição sul com a face sul
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="south"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:kapok_log no lado sul
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="south"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_kapok_log no lado sul
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_kapok_log["minecraft:block_face"="south"]`);
          }
        }
      });

    // Testa o bloco na posição leste com a face leste
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="east"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:kapok_log no lado leste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="east"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_kapok_log no lado leste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_kapok_log["minecraft:block_face"="east"]`);
          }
        }
      });

    // Testa o bloco na posição oeste com a face oeste
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="west"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:kapok_log no lado oeste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="west"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_kapok_log no lado oeste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_kapok_log["minecraft:block_face"="west"]`);
          }
        }
      });

    // Testa o bloco na posição de cima com a face de cima
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="up"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:kapok_log com a face de cima
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="up"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_kapok_log com a face de cima
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_kapok_log["minecraft:block_face"="up"]`);
          }
        }
      });

    // Testa o bloco na posição de baixo com a face de baixo
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="down"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:kapok_log com a face de baixo
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:kapok_log["minecraft:block_face"="down"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_kapok_log com a face de baixo
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_kapok_log["minecraft:block_face"="down"]`);
          }
        }
      });
  }
});

// Identificadores dos blocos que ativam o evento
const Block_ID2 = [
  "ecbl_bc:redwood_log", // Substitua por outros identificadores de blocos, se necessário
];

// Evento de colocação de bloco por um jogador
world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension } = event;

  // Verifica se o bloco colocado está na lista de identificadores
  if (Block_ID2.includes(block.typeId)) {
    const blockPosition = block.location;
    const randomChoice = Math.random();

    // Testa o bloco na posição norte com a face norte
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="north"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:redwood_log no lado norte
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="north"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_redwood_log no lado norte
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_redwood_log["minecraft:block_face"="north"]`);
          }
        }
      });

    // Testa o bloco na posição sul com a face sul
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="south"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:redwood_log no lado sul
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="south"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_redwood_log no lado sul
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_redwood_log["minecraft:block_face"="south"]`);
          }
        }
      });

    // Testa o bloco na posição leste com a face leste
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="east"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:redwood_log no lado leste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="east"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_redwood_log no lado leste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_redwood_log["minecraft:block_face"="east"]`);
          }
        }
      });

    // Testa o bloco na posição oeste com a face oeste
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="west"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:redwood_log no lado oeste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="west"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_redwood_log no lado oeste
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_redwood_log["minecraft:block_face"="west"]`);
          }
        }
      });

    // Testa o bloco na posição de cima com a face de cima
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="up"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:redwood_log com a face de cima
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="up"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_redwood_log com a face de cima
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_redwood_log["minecraft:block_face"="up"]`);
          }
        }
      });

    // Testa o bloco na posição de baixo com a face de baixo
    dimension
      .runCommandAsync(`testforblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="down"]`)
      .then((result) => {
        if (result.successCount > 0) {
          if (randomChoice < 0.6) {
            // 60% de chance de ser substituído por ecbl_bc:redwood_log com a face de baixo
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:redwood_log["minecraft:block_face"="down"]`);
          } else {
            // 40% de chance de ser substituído por ecbl_bc:mossy_redwood_log com a face de baixo
            dimension.runCommand(`setblock ${blockPosition.x} ${blockPosition.y} ${blockPosition.z} ecbl_bc:mossy_redwood_log["minecraft:block_face"="down"]`);
          }
        }
      });
  }
});

// Função auxiliar para simular atraso
function delay(ms) {
  return new Promise((resolve) => system.runTimeout(resolve, ms));
}

world.afterEvents.entityHitEntity.subscribe((data) => {
  const { damagingEntity, hitEntity } = data;

  // Verifica se quem causou o dano é um jogador
  if (damagingEntity.typeId != "minecraft:player") return;

  if (hitEntity.typeId == "ecbl_bc:tumbleweed") {
    // Executa o comando desejado
    hitEntity.runCommand(`structure load "ecbl_bc/stick_drop" ~~1~`);
    delay(1).then(() => {
      hitEntity.runCommand(`tp @s ~~-70~`);
      damagingEntity.runCommand(`playsound block.sweet_berry_bush.break @s`);
    });

    delay(10).then(() => {
      hitEntity.runCommand(`kill @s`);
    });
  }
});

const CornSeedID = ["ecbl_bc:corn_seeds"];

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (CornSeedID.includes(itemUsed.typeId)) {
    if (block.permutation.matches("ecbl_bc:prairie_grass_block")) {
      const blockPosition = block.location;

      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:corn_block["ecbl_bc:growth_up_or_down"=false]`);
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y + 2} ${blockPosition.z} ecbl_bc:corn_block["ecbl_bc:growth_up_or_down"=true]`);
        player.runCommand(`playsound dig.grass @s ~~~ 0.1`);
      });
    }
  }
});

world.beforeEvents.itemUseOn.subscribe((evd) => {
  const { source: player, block, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (CornSeedID.includes(itemUsed.typeId)) {
    if (block.permutation.matches("minecraft:farmland")) {
      const blockPosition = block.location;

      system.run(() => {
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:corn_block["ecbl_bc:growth_up_or_down"=false]`);
        player.runCommand(`setblock ${blockPosition.x} ${blockPosition.y + 2} ${blockPosition.z} ecbl_bc:corn_block["ecbl_bc:growth_up_or_down"=true]`);
        player.runCommand(`playsound dig.grass @s ~~~ 0.1`);
      });
    }
  }
});

let shearingCooldown = new Set();
let previousPositions = new Map(); // Map para armazenar as posições anteriores das ovelhas

// Evento para detectar a interação do jogador com a entidade
world.beforeEvents.playerInteractWithEntity.subscribe((evd) => {
  const { source: player, target: entity, itemStack: itemUsed } = evd;

  if (!itemUsed) return;

  if (itemUsed.typeId === "minecraft:shears" && entity.typeId === "ecbl_bc:ram") {
    if (shearingCooldown.has(entity.id)) {
      return;
    }

    // Verifica se a entidade é um bebê
    if (entity.hasComponent("minecraft:is_baby")) {
      return; // Se for bebê, não executa a tosquia
    }

    shearingCooldown.add(entity.id);

    system.run(() => {
      entity.runCommand(`structure load "ecbl_bc/w_white" ~~1~`);
      entity.runCommand(`/event entity @s ecbl_bc:event_shorn_ram`);
      entity.runCommand(`playsound mob.sheep.shear @a[r=10]`);
    });
  }
});

// Função para verificar periodicamente todas as ovelhas
function verifyRams() {
  system.runInterval(() => {
    const allRams = world.getEntities().filter((entity) => entity.typeId === "ecbl_bc:ram");
    const selectedRams = getRandomSubset(allRams, Math.ceil(allRams.length * 0.5));

    selectedRams.forEach((entity) => {
      // Verifica se a entidade é um bebê
      if (entity.hasComponent("minecraft:is_baby")) {
        return; // Se for bebê, não executa a verificação
      }

      const currentPosition = `${entity.location.x},${entity.location.y},${entity.location.z}`;

      if (previousPositions.has(entity.id)) {
        const previousPosition = previousPositions.get(entity.id);

        // Verifica se a posição atual é igual à posição anterior
        if (currentPosition === previousPosition) {
          // Verifica se o bloco abaixo da entidade é um bloco de grama
          entity
            .runCommandAsync(`testforblock ~ ~-1 ~ minecraft:grass_block`)
            .then((result) => {
              if (result.successCount > 0) {
                // Executa a animação após verificar o bloco
                entity.runCommand(`/playanimation @s animation.sheep.grazing`);

                // Executa o evento e substitui o bloco após 2 segundos (40 ticks) da animação
                system.runTimeout(() => {
                  entity.runCommand(`/event entity @s ecbl_bc:event_no_shorn_ram`);
                  entity.runCommand(`/fill ~ ~-1 ~ ~ ~-1 ~ dirt replace grass_block`);
                  entity.runCommand(`/playsound dig.grass @a[r=10]`);
                  shearingCooldown.delete(entity.id);
                }, 40);
              }
            })
            .catch((error) => {
              console.error(`Erro ao executar o comando: ${error}`);
            });
        }
      }

      // Atualiza a posição anterior da entidade
      previousPositions.set(entity.id, currentPosition);
    });
  }, 60); // Verifica a cada 60 ticks
}

// Função para selecionar um subconjunto aleatório de uma lista
function getRandomSubset(arr, size) {
  const shuffled = arr.slice();
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled.slice(0, size);
}

// Inicia a verificação periódica
verifyRams();

world.afterEvents.itemCompleteUse.subscribe((e) => {
  const { itemStack, source: player } = e;
  if (itemStack.typeId === "ecbl_bc:orchid_tea") {
    player.addEffect("regeneration", 300);
  }
});

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


const playerCooldown = {};

function isPlayerInCooldown(playerId, currentTime, cooldownPeriod) {
  return playerCooldown[playerId] && currentTime - playerCooldown[playerId] <= cooldownPeriod;
}

world.beforeEvents.playerInteractWithBlock.subscribe(async (ev) => {
  const { player, block, itemStack, blockFace } = ev;
  const blockPosition = block?.location;
  const playerId = player.id;
  const currentTime = Date.now();
  const cooldownPeriod = 700; // 700 ms = 0.7 segundos

  if (block && itemStack && !disallowedBlocks_pile_of_pebbles.includes(block.typeId) &&
    itemStack.typeId === "ecbl_bc:pile_of_pebbles" && blockFace === "Up") { 

    if (!isPlayerInCooldown(playerId, currentTime, cooldownPeriod)) {
      playerCooldown[playerId] = currentTime;

      try {
        await player.runCommandAsync(`setblock ${blockPosition.x} ${blockPosition.y + 1} ${blockPosition.z} ecbl_bc:pile_of_pebbles keep`);
        player.runCommand(`playsound dig.stone @s`);
        if (player.getGameMode() !== "creative") {
          player.runCommand(`clear @s ecbl_bc:pile_of_pebbles 0 1`);
        }
      } catch (error) {
        console.error("Erro ao executar comando:", error);
      }
    }
  }
});


afterEvents.entityHitEntity.subscribe((e) => {
  const { damagingEntity, hitEntity } = e;
  const item = damagingEntity.getEquipment(EquipmentSlot.Head);

  if (item && item?.typeId === "ecbl_bc:antler_helmet") {
    const viewdirect = damagingEntity.getViewDirection();

    hitEntity.applyKnockback(viewdirect.x, viewdirect.z, 1.5, 0.5);
  }
});

world.afterEvents.entityHitEntity.subscribe((e) => {
  const { damagingEntity, hitEntity } = e;
  const item = damagingEntity.getComponent(EntityEquippableComponent.componentId)?.getEquipment(EquipmentSlot.Mainhand);

  if (item?.typeId === "ecbl_bc:bear_claw") {
    let i = 0;
    const dmg = system.runInterval(() => {
      if (hitEntity && i <= 3) {
        const exist = world.getEntity(hitEntity.id);

        if (exist) {
          hitEntity?.applyDamage(1);
        }

        i = i + 1;
      } else {
        system.clearRun(dmg);
      }
    }, 16);
  }
});
