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

world.beforeEvents.playerInteractWithBlock.subscribe(function (eventData) {
  if (eventData.player.isSneaking) return;
  if (eventData.block.typeId !== "minecraft:iron_door" && eventData.block.typeId !== "minecraft:iron_trapdoor") return;
    if (eventData.itemStack?.typeId !== "minecraft:redstone_torch") return;
    system.run(function () {
      eventData.player.playSound(`open.${eventData.block.typeId.split(":")[1]}`, { location: eventData.block.location });
      eventData.block.setPermutation(eventData.block.permutation.withState("open_bit", !eventData.block.permutation.getState("open_bit")));
      if (eventData.block.permutation.getState("upper_block_bit")) {
        const block = eventData.block.below(1);
        if (block === undefined) return;
        block.setPermutation(block.permutation.withState("open_bit", !block.permutation.getState("open_bit")));
      }
    });
});
