import { world } from "@minecraft/server";
export async function replaceBedrock() {
  for (const player of world.getPlayers()) {
    const mainHand = player.getComponent("minecraft:equippable")?.getEquipment("Mainhand");
    const block = player.getBlockFromViewDirection({ maxDistance: 5 })?.block;

    if (!block) continue;

    const { x, y, z } = block.location;
    const setBlockCommand = `setblock ${x} ${y} ${z}`;

    if (mainHand?.typeId === '4ks_wp:dragon_pickaxe' && block.permutation.matches('minecraft:bedrock')) {
      player.runCommand(`${setBlockCommand} 4ks_wp:fake_bedrock`);
    } else if (block.permutation.matches('4ks_wp:fake_bedrock') && mainHand?.typeId !== '4ks_wp:dragon_pickaxe') {
      player.runCommand(`${setBlockCommand} bedrock`);
    }
  }
}

export async function checkBlock() {
  for (const player of world.getPlayers()) {
    player.runCommand("/execute as @s unless entity @e[type=4ks_wp:item_checker] run summon 4ks_wp:item_checker");
    const rayblock = player.getBlockFromViewDirection({ maxDistance: 6 });
    if (!rayblock) {
      player.removeTag("4kswpint");
      continue;
    }

    const block = rayblock.block;
    const blockID = block.typeId.replace("minecraft:", "");
    if (isInteractableBlock(blockID)) {
      player.addTag("4kswpint");
      player.removeTag("4kswphalberd");
      player.runCommand("/event entity @e[type=4ks_wp:invisible_hitter, c=1,r=3] 4ks_wp:despawn");
    } else {
      player.removeTag("4kswpint");
    }
  }
}

function isInteractableBlock(blockID) {
  return blockID.includes("door") ||
    blockID.includes("chest") ||
    blockID.includes("craft") ||
    blockID.includes("table") ||
    blockID.includes("stand") ||
    blockID.includes("button") ||
    blockID.includes("lever") ||
    blockID.includes("stonecutter");
} 