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

system.runInterval(() => {
  world.afterEvents.weatherChange.subscribe((data) => {
    let weather = data.newWeather; // Get the weather type from the event data
    let oldWeather = data.oldWeather; // Get the weather type before the current one from the event data

    // Send specific messages based on the weather type
    if (weather === "Rain") {
      system.run(() => {
        let players = world.getAllPlayers();

        players.forEach((player) => {
          player.runCommand(`event entity @e[type=ecbl_bc:tumbleweed] eternal:rain_event`);
        });
      });
    } else if (weather === "Thunder") {
      system.run(() => {
        let players = world.getAllPlayers();

        players.forEach((player) => {
          player.runCommand(`event entity @e[type=ecbl_bc:tumbleweed] eternal:rain_event`);
        });
      });
    } else if (weather === "Clear") {
      system.run(() => {
        let players = world.getAllPlayers();

        players.forEach((player) => {
          player.runCommand(`event entity @e[type=ecbl_bc:tumbleweed] eternal:no_rain_event`);
        });
      });
    } else if (weather === "Snow") {
      system.run(() => {
        let players = world.getAllPlayers();

        players.forEach((player) => {
          player.runCommand(`event entity @e[type=ecbl_bc:tumbleweed] eternal:rain_event`);
        });
      });
    }
  });
}, 10); // A cada segundo (20 ticks)


world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension } = event;

  // Definindo um objeto onde a chave é o bloco e o valor é true/false
  const plants = {
    "ecbl_bc:heliconia_blooms": true,
    "ecbl_bc:goldenrod_flower": true,
    "ecbl_bc:prairie_tall_grass": false,
    "ecbl_bc:dry_tall_grass": false,
  };

  // Verifica se o tipo do bloco está no objeto 'plants'
  if (!(block.typeId in plants)) return;

  const dropItem = plants[block.typeId]; // Obtém o valor (true ou false)

  const belowBlock = dimension.getBlock({
    x: block.location.x,
    y: block.location.y - 1,
    z: block.location.z
  });

  if (!belowBlock) return;

  const belowPerm = belowBlock.permutation;
  const belowTypeId = belowBlock.typeId;

  const upperBit = belowPerm.getState("ecbl_bc:upper_block_bit");

  // Se o bloco de baixo for igual e o upperBit for verdadeiro
  if (belowTypeId === block.typeId && upperBit === true) {
    if (dropItem) {
      // Droppa o item correspondente se 'dropItem' for true
      const item = new ItemStack(block.typeId, 1);
      dimension.spawnItem(item, {
        x: block.location.x,
        y: block.location.y + 1,
        z: block.location.z
      });
    }

    // Quebra o bloco
    block.setType("minecraft:air");
  }
});






// Função auxiliar para simular atraso
// Esta função retorna uma Promise que é resolvida após o tempo especificado em milissegundos.
function delay(ms) {
  return new Promise((resolve) => system.runTimeout(resolve, ms));
}

// Objetos para armazenar os contadores de hits individualmente para cada barco e garantir que o reset execute apenas uma vez por barco
let hitCounts = {};
let resetExecuted = {};

// Evento que é acionado quando uma entidade é atingida por outra entidade
world.afterEvents.entityHitEntity.subscribe(async (data) => {
  const { damagingEntity, hitEntity } = data;

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

  // Verifica se a entidade atingida é do tipo "ecbl_bc:baobab_boat"
  if (hitEntity.typeId == "ecbl_bc:baobab_boat") {
    const boatId = hitEntity.id; // Identificador único para cada barco

    // Inicializa o contador e a variável de reset para o barco se ainda não existirem
    if (!hitCounts[boatId]) {
      hitCounts[boatId] = 0;
      resetExecuted[boatId] = false;
    }

    // Incrementa o contador de hits para o barco atingido
    hitCounts[boatId]++;

    // Executa o comando desejado nos primeiros 4 hits
    if (hitCounts[boatId] <= 4) {
      hitEntity.runCommand(`playanimation @s animation.ecbl_bc.boat_geometry.destroy`);
    }

    // Executa o comando desejado no quinto hit
    if (hitCounts[boatId] == 5) {
      hitEntity.runCommand(`structure load "ecbl_bc/baobab_boat" ~~1~`);
      delay(1).then(() => {
        hitEntity.runCommand(`tp @s ~~-70~`);
      });

      delay(10).then(() => {
        hitEntity.runCommand(`kill @s`);
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Quebra o script
        return;
      });
    }

    // Executa o reset apenas uma vez por barco após 100 milissegundos
    if (!resetExecuted[boatId]) {
      resetExecuted[boatId] = true; // Marca que o reset foi executado
      delay(100).then(() => {
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Garante que o reset seja executado apenas uma vez para o barco
        resetExecuted[boatId] = true;

        // Quebra o script
        return;
      });
    }
  }
  if (hitEntity.typeId == "ecbl_bc:baobab_boat_chest") {
    const boatId = hitEntity.id; // Identificador único para cada barco

    // Inicializa o contador e a variável de reset para o barco se ainda não existirem
    if (!hitCounts[boatId]) {
      hitCounts[boatId] = 0;
      resetExecuted[boatId] = false;
    }

    // Incrementa o contador de hits para o barco atingido
    hitCounts[boatId]++;

    // Executa o comando desejado nos primeiros 4 hits
    if (hitCounts[boatId] <= 4) {
      hitEntity.runCommand(`playanimation @s animation.ecbl_bc.boat_geometry.destroy`);
    }

    // Executa o comando desejado no quinto hit
    if (hitCounts[boatId] == 5) {
      hitEntity.runCommand(`structure load "ecbl_bc/baobab_boat_c" ~~1~`);
      delay(1).then(() => {
        hitEntity.runCommand(`tp @s ~~-70~`);
      });

      delay(10).then(() => {
        hitEntity.runCommand(`kill @s`);
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Quebra o script
        return;
      });
    }

    // Executa o reset apenas uma vez por barco após 100 milissegundos
    if (!resetExecuted[boatId]) {
      resetExecuted[boatId] = true; // Marca que o reset foi executado
      delay(100).then(() => {
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Garante que o reset seja executado apenas uma vez para o barco
        resetExecuted[boatId] = true;

        // Quebra o script
        return;
      });
    }
  }
  if (hitEntity.typeId == "ecbl_bc:redwood_boat") {
    const boatId = hitEntity.id; // Identificador único para cada barco

    // Inicializa o contador e a variável de reset para o barco se ainda não existirem
    if (!hitCounts[boatId]) {
      hitCounts[boatId] = 0;
      resetExecuted[boatId] = false;
    }

    // Incrementa o contador de hits para o barco atingido
    hitCounts[boatId]++;

    // Executa o comando desejado nos primeiros 4 hits
    if (hitCounts[boatId] <= 4) {
      hitEntity.runCommand(`playanimation @s animation.ecbl_bc.boat_geometry.destroy`);
    }

    // Executa o comando desejado no quinto hit
    if (hitCounts[boatId] == 5) {
      hitEntity.runCommand(`structure load "ecbl_bc/redwood_boat" ~~1~`);
      delay(1).then(() => {
        hitEntity.runCommand(`tp @s ~~-70~`);
      });

      delay(10).then(() => {
        hitEntity.runCommand(`kill @s`);
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Quebra o script
        return;
      });
    }

    // Executa o reset apenas uma vez por barco após 100 milissegundos
    if (!resetExecuted[boatId]) {
      resetExecuted[boatId] = true; // Marca que o reset foi executado
      delay(100).then(() => {
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Garante que o reset seja executado apenas uma vez para o barco
        resetExecuted[boatId] = true;

        // Quebra o script
        return;
      });
    }
  }
  if (hitEntity.typeId == "ecbl_bc:redwood_boat_chest") {
    const boatId = hitEntity.id; // Identificador único para cada barco

    // Inicializa o contador e a variável de reset para o barco se ainda não existirem
    if (!hitCounts[boatId]) {
      hitCounts[boatId] = 0;
      resetExecuted[boatId] = false;
    }

    // Incrementa o contador de hits para o barco atingido
    hitCounts[boatId]++;

    // Executa o comando desejado nos primeiros 4 hits
    if (hitCounts[boatId] <= 4) {
      hitEntity.runCommand(`playanimation @s animation.ecbl_bc.boat_geometry.destroy`);
    }

    // Executa o comando desejado no quinto hit
    if (hitCounts[boatId] == 5) {
      hitEntity.runCommand(`structure load "ecbl_bc/redwood_boat_c" ~~1~`);
      delay(1).then(() => {
        hitEntity.runCommand(`tp @s ~~-70~`);
      });

      delay(10).then(() => {
        hitEntity.runCommand(`kill @s`);
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Quebra o script
        return;
      });
    }

    // Executa o reset apenas uma vez por barco após 100 milissegundos
    if (!resetExecuted[boatId]) {
      resetExecuted[boatId] = true; // Marca que o reset foi executado
      delay(100).then(() => {
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Garante que o reset seja executado apenas uma vez para o barco
        resetExecuted[boatId] = true;

        // Quebra o script
        return;
      });
    }
  }
  if (hitEntity.typeId == "ecbl_bc:kapok_boat") {
    const boatId = hitEntity.id; // Identificador único para cada barco

    // Inicializa o contador e a variável de reset para o barco se ainda não existirem
    if (!hitCounts[boatId]) {
      hitCounts[boatId] = 0;
      resetExecuted[boatId] = false;
    }

    // Incrementa o contador de hits para o barco atingido
    hitCounts[boatId]++;

    // Executa o comando desejado nos primeiros 4 hits
    if (hitCounts[boatId] <= 4) {
      hitEntity.runCommand(`playanimation @s animation.ecbl_bc.boat_geometry.destroy`);
    }

    // Executa o comando desejado no quinto hit
    if (hitCounts[boatId] == 5) {
      hitEntity.runCommand(`structure load "ecbl_bc/kapok_boat" ~~1~`);
      delay(1).then(() => {
        hitEntity.runCommand(`tp @s ~~-70~`);
      });

      delay(10).then(() => {
        hitEntity.runCommand(`kill @s`);
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Quebra o script
        return;
      });
    }

    // Executa o reset apenas uma vez por barco após 100 milissegundos
    if (!resetExecuted[boatId]) {
      resetExecuted[boatId] = true; // Marca que o reset foi executado
      delay(100).then(() => {
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Garante que o reset seja executado apenas uma vez para o barco
        resetExecuted[boatId] = true;

        // Quebra o script
        return;
      });
    }
  }
  if (hitEntity.typeId == "ecbl_bc:kapok_boat_chest") {
    const boatId = hitEntity.id; // Identificador único para cada barco

    // Inicializa o contador e a variável de reset para o barco se ainda não existirem
    if (!hitCounts[boatId]) {
      hitCounts[boatId] = 0;
      resetExecuted[boatId] = false;
    }

    // Incrementa o contador de hits para o barco atingido
    hitCounts[boatId]++;

    // Executa o comando desejado nos primeiros 4 hits
    if (hitCounts[boatId] <= 4) {
      hitEntity.runCommand(`playanimation @s animation.ecbl_bc.boat_geometry.destroy`);
    }

    // Executa o comando desejado no quinto hit
    if (hitCounts[boatId] == 5) {
      hitEntity.runCommand(`structure load "ecbl_bc/kapok_boat_c" ~~1~`);
      delay(1).then(() => {
        hitEntity.runCommand(`tp @s ~~-70~`);
      });

      delay(10).then(() => {
        hitEntity.runCommand(`kill @s`);
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Quebra o script
        return;
      });
    }

    // Executa o reset apenas uma vez por barco após 100 milissegundos
    if (!resetExecuted[boatId]) {
      resetExecuted[boatId] = true; // Marca que o reset foi executado
      delay(100).then(() => {
        // Reinicia o contador de hits para o barco atingido
        hitCounts[boatId] = 0;

        // Garante que o reset seja executado apenas uma vez para o barco
        resetExecuted[boatId] = true;

        // Quebra o script
        return;
      });
    }
  }
});

world.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("ecbl_bc:magenta_particle", new Tick_magenta_orchid());
  event.blockComponentRegistry.registerCustomComponent("ecbl_bc:glowing_mushroom_particles", new Tick_glowing_mushroom_particle());
});

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
  blockComponentRegistry.registerCustomComponent("ecbl_bc:growth_vine", TickGrowthVine);
});

const TickGrowthVine = {
  onRandomTick({ block, dimension }) {
    const growthChance = 1 / 3;
    if (Math.random() > growthChance) return;
    if (block.below()?.typeId == "minecraft:air") {
      dimension.runCommand(`setblock ${block.location.x} ${block.location.y - 1} ${block.location.z} ecbl_bc:climbing_vines`);
    }
  },
};

class Tick_magenta_orchid {
  onTick(data) {
    let BlockX = data.block.x;
    let BlockY = data.block.y;
    let BlockZ = data.block.z;

    data.block.dimension.runCommand(`particle plank_waao:orchid_blooms_magenta ${BlockX} ${BlockY} ${BlockZ}`);
  }
}

class Tick_glowing_mushroom_particle {
  onTick(data) {
    let BlockX = data.block.x;
    let BlockY = data.block.y;
    let BlockZ = data.block.z;

    data.block.dimension.runCommand(`particle ecbl_bc:mushroom_spores ${BlockX} ${BlockY} ${BlockZ}`);
  }
}

world.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("ecbl_bc:pink_particle", new Tick_pink_orchid());
});

class Tick_pink_orchid {
  onTick(data) {
    let BlockX = data.block.x;
    let BlockY = data.block.y;
    let BlockZ = data.block.z;

    data.block.dimension.runCommand(`particle plank_waao:orchid_blooms_pink ${BlockX} ${BlockY} ${BlockZ}`);
  }
}

world.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("ecbl_bc:purple_particle", new Tick_purple_orchid());
});

class Tick_purple_orchid {
  onTick(data) {
    let BlockX = data.block.x;
    let BlockY = data.block.y;
    let BlockZ = data.block.z;

    data.block.dimension.runCommand(`particle plank_waao:orchid_blooms_purple ${BlockX} ${BlockY} ${BlockZ}`);
  }
}


world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:prairie_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "north") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:prairie_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="north"]`
    );
  }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:prairie_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "east") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:prairie_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="east"]`
    );
  }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:prairie_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "west") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:prairie_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="west"]`
    );
  }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:prairie_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "south") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:prairie_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="south"]`
    );
  }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:dry_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "north") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:dry_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="north"]`
    );
  }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:dry_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "east") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:dry_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="east"]`
    );
  }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:dry_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "west") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:dry_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="west"]`
    );
  }
});

world.afterEvents.playerPlaceBlock.subscribe((event) => {
  const { block, dimension, player } = event;

  if (block.typeId === "ecbl_bc:dry_tall_grass" && block.permutation.getState("minecraft:cardinal_direction") == "south") {
    player.runCommand(
      `setblock ${block.location.x} ${block.location.y + 1} ${block.location.z
      } ecbl_bc:dry_tall_grass["ecbl_bc:upper_block_bit"=true,"minecraft:cardinal_direction"="south"]`
    );
  }
});

world.afterEvents.playerBreakBlock.subscribe((event) => {
  const { dimension, block, player, brokenBlockPermutation } = event;
  if (player.getGameMode() !== "creative") {
    if (brokenBlockPermutation.type.id === "ecbl_bc:pile_of_pebbles") {
      const quantityState = brokenBlockPermutation.getState("ecbl_bc:quantity");

      if (quantityState === 0) {
        const itemsDrop = [...block.dimension.getEntities({
          type: "minecraft:item",
          location: block.location,
          maxDistance: 2
        })].filter(item => item.getComponent("item").itemStack.typeId == "ecbl_bc:pile_of_pebbles");

        if (itemsDrop.length > 0) {
          itemsDrop[0].remove();
        }

        delay(1).then(() => {
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
        });
      }
    }
  }
});

world.afterEvents.playerBreakBlock.subscribe((event) => {
  const { dimension, block, player, brokenBlockPermutation } = event;
  if (player.getGameMode() !== "creative") {
    if (brokenBlockPermutation.type.id === "ecbl_bc:pile_of_pebbles") {
      const quantityState = brokenBlockPermutation.getState("ecbl_bc:quantity");

      if (quantityState === 1) {
        const itemsDrop = [...block.dimension.getEntities({
          type: "minecraft:item",
          location: block.location,
          maxDistance: 2
        })].filter(item => item.getComponent("item").itemStack.typeId == "ecbl_bc:pile_of_pebbles");

        if (itemsDrop.length > 0) {
          itemsDrop[0].remove();
        }

        delay(1).then(() => {
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
        });
      }
    }
  }
});

world.afterEvents.playerBreakBlock.subscribe((event) => {
  const { dimension, block, player, brokenBlockPermutation } = event;
  if (player.getGameMode() !== "creative") {
    if (brokenBlockPermutation.type.id === "ecbl_bc:pile_of_pebbles") {
      const quantityState = brokenBlockPermutation.getState("ecbl_bc:quantity");

      if (quantityState === 2) {
        const itemsDrop = [...block.dimension.getEntities({
          type: "minecraft:item",
          location: block.location,
          maxDistance: 2
        })].filter(item => item.getComponent("item").itemStack.typeId == "ecbl_bc:pile_of_pebbles");

        if (itemsDrop.length > 0) {
          itemsDrop[0].remove();
        }

        delay(1).then(() => {
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
        });
      }
    }
  }
});

world.afterEvents.playerBreakBlock.subscribe((event) => {
  const { dimension, block, player, brokenBlockPermutation } = event;
  if (player.getGameMode() !== "creative") {
    if (brokenBlockPermutation.type.id === "ecbl_bc:pile_of_pebbles") {
      const quantityState = brokenBlockPermutation.getState("ecbl_bc:quantity");

      if (quantityState === 3) {
        const itemsDrop = [...block.dimension.getEntities({
          type: "minecraft:item",
          location: block.location,
          maxDistance: 2
        })].filter(item => item.getComponent("item").itemStack.typeId == "ecbl_bc:pile_of_pebbles");

        if (itemsDrop.length > 0) {
          itemsDrop[0].remove();
        }

        delay(1).then(() => {
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
          dimension.runCommandAsync(`structure load "ecbl_bc/pile_of_pebbles" ${block.location.x} ${block.location.y} ${block.location.z}`);
        });
      }
    }
  }
});

world.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("ecbl_bc:lilypad", new Lilypad());
});

class Lilypad {
  async onTick(data) {
    let BlockX = data.block.x;
    let BlockY = data.block.y;
    let BlockZ = data.block.z;

    await data.block.dimension.runCommandAsync(`setblock ${BlockX + 1} ${BlockY} ${BlockZ + 1} ecbl_bc:lilypad_fake_box_SE`);
    await data.block.dimension.runCommandAsync(`setblock ${BlockX - 1} ${BlockY} ${BlockZ + 1} ecbl_bc:lilypad_fake_box_SW`);
    await data.block.dimension.runCommandAsync(`setblock ${BlockX - 1} ${BlockY} ${BlockZ - 1} ecbl_bc:lilypad_fake_box_NW`);
    await data.block.dimension.runCommandAsync(`setblock ${BlockX + 1} ${BlockY} ${BlockZ - 1} ecbl_bc:lilypad_fake_box_NE`);
    //
    await data.block.dimension.runCommandAsync(`setblock ${BlockX + 1} ${BlockY} ${BlockZ} ecbl_bc:lilypad_fake_box_E`);
    await data.block.dimension.runCommandAsync(`setblock ${BlockX - 1} ${BlockY} ${BlockZ} ecbl_bc:lilypad_fake_box_W`);
    await data.block.dimension.runCommandAsync(`setblock ${BlockX} ${BlockY} ${BlockZ + 1} ecbl_bc:lilypad_fake_box_S`);
    await data.block.dimension.runCommandAsync(`setblock ${BlockX} ${BlockY} ${BlockZ - 1} ecbl_bc:lilypad_fake_box_N`);
  }

  async onPlayerDestroy(event) {
    const { block } = event;
    const BlockX = block.x;
    const BlockY = block.y;
    const BlockZ = block.z;
    const dimension = block.dimension;

    const positions = [
      { x: 1, y: 0, z: 1 },
      { x: -1, y: 0, z: 1 },
      { x: -1, y: 0, z: -1 },
      { x: 1, y: 0, z: -1 },
      { x: 1, y: 0, z: 0 },
      { x: -1, y: 0, z: 0 },
      { x: 0, y: 0, z: 1 },
      { x: 0, y: 0, z: -1 },
      { x: 0, y: 0, z: 0 }, // Central block
    ];

    // Destruir todos os blocos associados
    for (const pos of positions) {
      await dimension.runCommandAsync(`setblock ${BlockX + pos.x} ${BlockY} ${BlockZ + pos.z} air`);
    }
  }
}

// Evento para detectar a quebra de blocos
world.afterEvents.playerBreakBlock.subscribe(async (event) => {
  const { dimension, block, player } = event;
  const blockPosition = block.location;
  const blockType = event.brokenBlockPermutation.type.id;

  // Executar comandos de fill para destruir blocos associados
  if (blockType.startsWith("ecbl_bc:lilypad_fake_box_") || blockType === "ecbl_bc:lilypad_giant") {
    if (blockType === "ecbl_bc:lilypad_fake_box_se") {
      dimension.runCommandAsync(
        `fill ${block.location.x} ${block.location.y} ${block.location.z} ${block.location.x - 2} ${block.location.y} ${block.location.z - 2} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_fake_box_sw") {
      dimension.runCommandAsync(
        `fill ${block.location.x + 2} ${block.location.y} ${block.location.z} ${block.location.x} ${block.location.y} ${block.location.z - 2} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_fake_box_nw") {
      dimension.runCommandAsync(
        `fill ${block.location.x} ${block.location.y} ${block.location.z} ${block.location.x + 2} ${block.location.y} ${block.location.z + 2} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_fake_box_ne") {
      dimension.runCommandAsync(
        `fill ${block.location.x} ${block.location.y} ${block.location.z} ${block.location.x - 2} ${block.location.y} ${block.location.z + 2} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_fake_box_e") {
      dimension.runCommandAsync(
        `fill ${block.location.x} ${block.location.y} ${block.location.z - 1} ${block.location.x - 2} ${block.location.y} ${block.location.z + 1} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_fake_box_w") {
      dimension.runCommandAsync(
        `fill ${block.location.x + 2} ${block.location.y} ${block.location.z - 1} ${block.location.x} ${block.location.y} ${block.location.z + 1} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_fake_box_s") {
      dimension.runCommandAsync(
        `fill ${block.location.x - 1} ${block.location.y} ${block.location.z} ${block.location.x + 1} ${block.location.y} ${block.location.z - 2} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_fake_box_n") {
      dimension.runCommandAsync(
        `fill ${block.location.x + 1} ${block.location.y} ${block.location.z + 2} ${block.location.x - 1} ${block.location.y} ${block.location.z} air`
      );
    } else if (blockType === "ecbl_bc:lilypad_giant") {
      dimension.runCommandAsync(
        `fill ${block.location.x - 1} ${block.location.y} ${block.location.z - 1} ${block.location.x + 1} ${block.location.y} ${block.location.z + 1} air`
      );
    }

    // Carregar estrutura se o jogador não estiver no modo criativo
    if (player.getGameMode() !== "creative") {
      dimension.runCommand(`structure load "ecbl_bc/lilypad_giant" ${block.location.x} ${block.location.y} ${block.location.z}`);
    }
  }
});
