import { BlockTypes, BlockPermutation, TimeOfDay, system, world, ItemStack, StructureAnimationMode, StructureRotation, StructureSaveMode } from "@minecraft/server";
import { checkBelowEntityDespawn, getStringBefore, checkLocation, getEntityRotation, getLocationbyFacingBlock, stringBetween, getGamemode, getElementPosition, getElementPositionArrayWithObjects } from "./helpers";
import { calculateKnockbackVector } from "../utilities/knockbacks";
import { cameraCutscene } from "../events/camera";
import { ModalFormData, ActionFormData } from "@minecraft/server-ui";

export const fenceMap = new Map([
  ["hb_cb:spike_fence_oak_block", "hb_cb:spike_fence_oak_block"],
  ["hb_cb:spike_fence_inventory", "hb_cb:spike_fence_oak_block"],

  ["hb_cb:spike_fence_acacia", "hb_cb:spike_fence_acacia"],
  ["hb_cb:spike_fence_birch", "hb_cb:spike_fence_birch"],
  ["hb_cb:spike_fence_cherry", "hb_cb:spike_fence_cherry"],
  ["hb_cb:spike_fence_crimson", "hb_cb:spike_fence_crimson"],
  ["hb_cb:spike_fence_dark_oak", "hb_cb:spike_fence_dark_oak"],
  ["hb_cb:spike_fence_jungle", "hb_cb:spike_fence_jungle"],
  ["hb_cb:spike_fence_mangrove", "hb_cb:spike_fence_mangrove"],
  ["hb_cb:spike_fence_pale", "hb_cb:spike_fence_pale"],
  ["hb_cb:spike_fence_spruce", "hb_cb:spike_fence_spruce"],
  ["hb_cb:spike_fence_warped", "hb_cb:spike_fence_warped"],
]);

export const fenceSet = new Set(["hb_cb:spike_fence_oak_block", "hb_cb:spike_fence_acacia_block", "hb_cb:spike_fence_birch_block", "hb_cb:spike_fence_cherry_block", "hb_cb:spike_fence_crimson_block", "hb_cb:spike_fence_dark_oak_block", "hb_cb:spike_fence_jungle_block", "hb_cb:spike_fence_mangrove_block", "hb_cb:spike_fence_pale_block", "hb_cb:spike_fence_spruce_block", "hb_cb:spike_fence_warped_block", "hb_cb:spike_fence_inventory"]);

export const FenceInteractComponent = {
  onPlayerInteract(e) {
    const { block, player, face } = e;

    // Get the equipment component for the player
    const equipment = player.getComponent("equippable");
    // Get the selected item from the player's mainhand
    const selectedItem = equipment.getEquipment("Mainhand");

    if (selectedItem?.typeId === "minecraft:water_bucket") {
      // Check if the current dimension is not the Nether
      if (e.dimension.id !== "minecraft:nether") {
        // If not in creative mode, replace water bucket with empty bucket
        if (player.getGameMode() !== "creative") {
          equipment.setEquipment("Mainhand", new ItemStack("minecraft:bucket", 1));
        }
        // Set block to waterlogged and place corresponding structure
        block.setPermutation(block.permutation.withState("hb_hr:waterlogged", true));
        block.setWaterlogged(true);
      } else {
        try {
          e.dimension.spawnParticle("minecraft:water_evaporation_bucket_emitter", block.center());
        } catch (error) {}
        player.playSound("random.fizz", { pitch: 1.0, volume: 1.0 });
        // If not in creative mode, replace water bucket with empty bucket
        if (player.getGameMode() !== "creative") {
          equipment.setEquipment("Mainhand", new ItemStack("minecraft:bucket", 1));
        }
      }
      return; // Exit the function after handling water bucket
    }

    // Check if the selected item is a empty bucket and handle un-waterlogging
    else if (selectedItem?.typeId === "minecraft:bucket") {
      if (block.permutation.getState("hb_hr:waterlogged")) {
        // If not in creative mode, replace empty bucket with water bucket
        if (player.getGameMode() !== "creative") {
          if (selectedItem.amount === 1) {
            equipment.setEquipment("Mainhand", undefined);
          } else {
            selectedItem.amount -= 1;
            equipment.setEquipment("Mainhand", selectedItem);
          }
          player.runCommandAsync(`gamerule sendcommandfeedback false`);
          player.runCommandAsync(`give @s minecraft:water_bucket 1`);
          player.runCommandAsync(`gamerule sendcommandfeedback true`);
        }

        player.playSound("bucket.fill_water");

        // Save the state of the block
        const currentPermutation = block.permutation;
        const stateObject = currentPermutation.getAllStates();

        // Create a new object to store the states to prevent visual glitches
        const statesToKeep = {};
        for (const [key, value] of Object.entries(stateObject)) {
          if (key !== "hb_hr:waterlogged") {
            statesToKeep[key] = value;
          }
        }

        // Create a new permutation with the saved states
        let newPermutation = currentPermutation.withState("hb_hr:waterlogged", false);
        for (const [key, value] of Object.entries(statesToKeep)) {
          newPermutation = newPermutation.withState(key, value);
        }
        block.setWaterlogged(false);
        // Set the block with the new permutation
        block.setPermutation(newPermutation);

        return; // Exit the function after handling bucket
      }
    }

    // Determine the adjacent block position based on the face
    let adjacentBlockPos;
    switch (face) {
      case "North":
        adjacentBlockPos = { x: block.x, y: block.y, z: block.z - 1 };
        break;
      case "South":
        adjacentBlockPos = { x: block.x, y: block.y, z: block.z + 1 };
        break;
      case "East":
        adjacentBlockPos = { x: block.x + 1, y: block.y, z: block.z };
        break;
      case "West":
        adjacentBlockPos = { x: block.x - 1, y: block.y, z: block.z };
        break;
      case "Up":
        adjacentBlockPos = { x: block.x, y: block.y + 1, z: block.z };
        break;
      case "Down":
        adjacentBlockPos = { x: block.x, y: block.y - 1, z: block.z };
        break;
    }

    const adjacentBlock = e.dimension.getBlock(adjacentBlockPos);

    // Get block states and player direction
    if (!selectedItem) return;
    if (!getBlockStatesAndDirection(player, selectedItem, face)) return;
    const { stateName, stateValue } = getBlockStatesAndDirection(player, selectedItem, face);
    // Check if the selected item is a block
    if (face) {
      // Calculate the position above the current block
      const aboveBlock = adjacentBlock.above();

      if (selectedItem?.typeId.includes("_inventory") || selectedItem?.typeId.includes("_inventory_item")) {
        // If the block is air or a custom fence inventory item...
        if (adjacentBlock.typeId.includes("_inventory") || adjacentBlock.typeId === "minecraft:air" || adjacentBlock.typeId === "minecraft:water") {
          // ...place the corresponding fence block
          const fenceBlockType = fenceMap.get(selectedItem.typeId);
          adjacentBlock.setType(fenceBlockType);

          if (aboveBlock.typeId === "minecraft:air" || aboveBlock.typeId === "minecraft:water") {
            aboveBlock.setPermutation(BlockPermutation.resolve("hb_cb:spike_fence_inventory", { "hb_cb:post": 1 }));
          }

          // Reduce item count if not in creative mode
          if (player.getGameMode() !== "creative") {
            if (selectedItem.amount > 1) {
              selectedItem.amount -= 1;
              equipment.setEquipment("Mainhand", selectedItem);
            } else {
              equipment.setEquipment("Mainhand", undefined); // Clear the slot if only 1 item left
            }
          }
        }
      } else if (adjacentBlock.typeId === "minecraft:air" || adjacentBlock.typeId === "minecraft:water" || adjacentBlock.typeId.includes("_inventory")) {
        // Handle non-fence block placement with state
        let placeItemName = selectedItem.typeId;
        if (selectedItem.typeId.includes("spike_fence")) {
          adjacentBlock.setPermutation(
            BlockPermutation.resolve(selectedItem.typeId.replace("_item", "_block"), {
              "minecraft:block_face": block.permutation.getState("minecraft:block_face"),
            })
          );
          if (adjacentBlock.above().typeId === "minecraft:air") {
            adjacentBlock.above().setPermutation(
              BlockPermutation.resolve("hb_cb:spike_fence_inventory", {
                "minecraft:block_face": block.permutation.getState("minecraft:block_face"),
              })
            );
          }
        } else {
          if (selectedItem.typeId.includes("_item")) {
            return;
          }
          const commandBlock = stateName ? `setblock ${adjacentBlockPos.x} ${adjacentBlockPos.y} ${adjacentBlockPos.z} ${selectedItem.typeId} ["${stateName}"="${stateValue}"]` : `setblock ${adjacentBlockPos.x} ${adjacentBlockPos.y} ${adjacentBlockPos.z} ${selectedItem.typeId}`;
          player.runCommand(commandBlock);
        }

        system.runTimeout(() => {
          try {
            if (player.getGameMode() !== "creative") {
              if (selectedItem.amount === 1) {
                equipment.setEquipment("Mainhand", undefined);
              } else {
                selectedItem.amount -= 1;
                equipment.setEquipment("Mainhand", selectedItem);
              }
            }
          } catch (error) {
            console.warn(`Error: ${error.message}`);
          }
        }, 1);
      }
    }
  },
};

const DestroyComponent = {
  onPlayerDestroy(e) {
    const { block, player } = e;
    const aboveBlock = block.above();
    const blockBelow = block.below();

    // Remove hb_cb:fence_inventory or invisible fence gate on top if present
    if (aboveBlock.typeId.includes("_inventory") || fenceSet.has(aboveBlock.typeId)) {
      aboveBlock.setType("minecraft:air");
    }

    // add hb_cb:fence_inventory if fence present below
    if (fenceSet.has(blockBelow.typeId)) {
      block.setPermutation(BlockPermutation.resolve("hb_cb:spike_fence_inventory", { "hb_cb:post": 1 }));
    }
    const inventory = player.getComponent("inventory");
    const selectedItem = inventory.container.getItem(player.selectedSlotIndex);
    if (selectedItem && (selectedItem.typeId.includes("shovel") || selectedItem.typeId.includes("hoe") || selectedItem.typeId.includes("_axe") || selectedItem.typeId.includes("_pickaxe") || selectedItem.typeId.includes("shears"))) {
      system.runTimeout(() => {
        applyDurabilityDamage(player, selectedItem, inventory, player.selectedSlotIndex);
      }, 1);
    }
  },
};

export const OnTickComponent = {
  onTick(e) {
    if (e.block.typeId.includes("hb_cb:") && e.block.typeId.includes("fence") && e.block.typeId.includes("_inventory")) {
      /*  remove the fake fence collision block if the block below is:
          - any other marketplace-product fence block
          - any vanilla fence block
          - is another fake fence collision block
          - doesnt have fence at all in the block identifier
      */
      if ((!e.block.below().typeId.includes("hb_cb:") && !e.block.below().typeId.includes("minecraft:") && e.block.below().typeId.includes("fence")) || (e.block.below().typeId.includes("minecraft:") && e.block.below().typeId.includes("fence")) || (!e.block.below().typeId.includes("hb_cb:") && !e.block.below().typeId.includes("fence")) || !e.block.below().typeId.includes("fence") || (e.block.below().typeId.includes("hb_cb") && e.block.below().typeId.includes("fence") && e.block.below().typeId.includes("inventory"))) {
        e.block.setType("minecraft:air");
      }
      return;
    }
    // Destructure event data for easier access
    const { block } = e;
    // figure out which face is “front”

    // fence orientation
    const face = block.permutation.getState("minecraft:block_face"); // "north"|"south"|"east"|"west"
    const { x: bx, y: by, z: bz } = block.location;

    // threshold distance in front of the face
    const d = 0.55;
    let nearbyEntities = world.getDimension(block.dimension.id).getEntities({
      location: block.location,
      excludeTypes: ["minecraft:item", "minecraft:falling_block", "minecraft:xp_orb", "minecraft:arrow"],
      minDistance: 0,
      maxDistance: 3,
    });
    if (nearbyEntities.length === 0 || nearbyEntities[0] == undefined) return;
    for (const entity of nearbyEntities) {
      if (!entity.isValid()) continue;
      const { x: px, y: py, z: pz } = entity.location;

      // vertical check: within fence height
      const inY = py >= by && py < by + 1;

      // horizontal/radial check in front slice
      let inFront = false;
      switch (face) {
        case "north":
          // north face is at z = bz, so look just on the negative-Z side
          inFront = pz <= bz && pz >= bz - d && px >= bx && px < bx + 1;
          break;
        case "south":
          // south face at z = bz+1
          inFront = pz >= bz + 1 && pz <= bz + 1 + d && px >= bx && px < bx + 1;
          break;
        case "west":
          // west face at x = bx
          inFront = px <= bx && px >= bx - d && pz >= bz && pz < bz + 1;
          break;
        case "east":
          // east face at x = bx+1
          inFront = px >= bx + 1 && px <= bx + 1 + d && pz >= bz && pz < bz + 1;
          break;
      }

      if (inY && inFront) {
        if (entity) {
          entity.applyDamage(2);
          const kbVector = calculateKnockbackVector(entity.location, block.center(), 1);
          entity.applyKnockback(kbVector.x, kbVector.z, 2, 0);
        }
      }
    }
  },
};

const customComponents = {
  "hb_cb:fence_interact": FenceInteractComponent,
  "hb_cb:on_player_destroy": DestroyComponent,
  "hb_cb:on_tick": OnTickComponent,
};

export class spikeFenceHandler {
  static initialized = false;
  constructor() {
    this.initialize();
  }

  initialize() {
    if (!spikeFenceHandler.initialized) {
      spikeFenceHandler.initialized = true;
      this.processSubscriptions();
    } else {
    }
  }
  processSubscriptions() {
    let curTick = 0;
    const INIT_TIME = 0;

    // Run interval logic every game tick (20 times per second)
    system.runInterval(() => {
      try {
        if (curTick > INIT_TIME) {
          const allPlayers = world.getAllPlayers();
          allPlayers.forEach((player) => {
            if (!player.isValid()) return;
            else {
              changeBlockItemtoEntityItems(player);
            }
          });
        }
        curTick++;
      } catch (e) {
        console.warn(e);
      }
    }, 10);

    // Use this world initialization event to register all custom components
    world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
      for (const [componentName, componentImplementation] of Object.entries(customComponents)) {
        blockComponentRegistry.registerCustomComponent(componentName, componentImplementation);
      }
    });

    world.beforeEvents.playerBreakBlock.subscribe((eventData) => {
      const { block, player, dimension } = eventData;
      if (player.getGameMode() == "creative") return;
      if (!block.typeId.includes("spike_fence")) return;
      let spawnItem = new ItemStack(block.typeId.replace("_block", "_item"));
      if (fenceSet.has(block.typeId)) {
        system.runTimeout(() => {
          player.dimension.spawnItem(spawnItem, block.location);
          if (block.below().typeId.includes("hb_cb:") && block.below().typeId.includes("spike_fence")) {
            block.setPermutation(BlockPermutation.resolve("hb_cb:spike_fence_inventory", { "hb_cb:post": 1 }));
          }
        }, 1);
      }
    });
    world.afterEvents.playerInteractWithEntity.subscribe((event) => {
      const player = event.player;
      const typeId = player.typeId;
      if (typeId !== "minecraft:player") {
        return;
      }
      if (event.target.typeId.includes("hb_cb:spike_fence")) {
        const spikeFence = event.target;
        this.interactAbility(player, spikeFence);
      } else return;
    });
    world.afterEvents.itemUse.subscribe((event) => {
      const player = event.source;
      const typeId = player.typeId;
      if (typeId !== "minecraft:player") {
        return;
      }
      const holdingItem = player.getComponent("equippable").getEquipment("Mainhand");
      if (holdingItem == undefined) {
        return;
      }
      if (holdingItem.typeId.includes("hb_cb:spike_fence")) this.spawnspikeFence(player, holdingItem);
    });
    system.afterEvents.scriptEventReceive.subscribe((event) => {
      if (event.sourceEntity == undefined) return;
      else {
        if (event.sourceEntity.typeId.includes("hb_cb:") && event.sourceEntity.typeId.includes("spike_fence")) {
          let spikeFence = event.sourceEntity;
          switch (event.id) {
            case "hb_cb:despawn_tick_hit_trigger":
              if (spikeFence.getProperty("hb_cb:despawn_tick") < 4) {
                spikeFence.runCommand("/playsound hb_cb:spike_fence_hit @a[r=10] ~~~ 1 1");
                spikeFence.runCommand("/playanimation @s animation.hb_cb.spike_fence.break");
                spikeFence.runCommand("/event entity @s hb_cb:despawn_tick_hit");
              }
              break;
            case "hb_cb:spike_fence_despawn":
              this.despawnspikeFence(spikeFence);
              break;
            default:
              break;
          }
        }
      }
    });
  }
  interactAbility(player, spikeFence) {
    const form = new ModalFormData();
    form.title("hb_cb.spike_fence.ui.title");
    form.dropdown("hb_cb.spike_fence.ui.dropdown.title", [{ translate: "hb_cb.spike_fence.ui.text_0" }, { translate: "hb_cb.spike_fence.ui.text_1" }, { translate: "hb_cb.spike_fence.ui.text_2" }, { translate: "hb_cb.spike_fence.ui.text_3" }, { translate: "hb_cb.spike_fence.ui.text_4" }, { translate: "hb_cb.spike_fence.ui.text_5" }, { translate: "hb_cb.spike_fence.ui.text_6" }, { translate: "hb_cb.spike_fence.ui.text_7" }, { translate: "hb_cb.spike_fence.ui.text_8" }], spikeFence.getProperty("hb_cb:spike_fence_text") ?? 0);
    form.submitButton("Change spikeFence text");
    form.show(player).then((data) => {
      if (data.formValues == undefined) return;
      spikeFence.setProperty("hb_cb:spike_fence_text", data.formValues[0]);
    });
  }

  spawnspikeFence(player, item) {
    const raycastBlock = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: false, maxDistance: 8 });
    if (raycastBlock == undefined) return;
    else {
      let gamemodeCreative = getGamemode(player, 1);
      const location = raycastBlock.block.location;
      const face = raycastBlock.face;

      let yRotation = getEntityRotation(player);
      let orientation;
      switch (yRotation) {
        case 0:
          orientation = "north";
          break;
        case 90:
          orientation = "east";
          break;
        case 180:
          orientation = "south";
          break;
        case 270:
          orientation = "west";
          break;

        default:
          break;
      }

      let placeLoc = getLocationbyFacingBlock(face, location);
      if (checkLocation(placeLoc, player, placeLoc, 0)) return;
      let block = world.getDimension(player.dimension.id).getBlock({ x: placeLoc.x, y: placeLoc.y, z: placeLoc.z });
      block.setPermutation(
        BlockPermutation.resolve(item.typeId.replace("_item", "_block"), {
          "minecraft:block_face": orientation,
        })
      );

      // 3) And only add the post if it isn’t there already:
      if (block.above().typeId === "minecraft:air") {
        block.above().setPermutation(
          BlockPermutation.resolve("hb_cb:spike_fence_inventory", {
            "minecraft:block_face": orientation,
          })
        );
        // block.above().setPermutation(BlockPermutation.resolve("hb_cb:spike_fence_inventory", { "hb_cb:post": 1 }));
      }
      player.runCommand("/playsound dig.wood @a [r=20] ~~~ ");
      if (!gamemodeCreative) {
        player.runCommand("/clear @s " + item.typeId + " 0 1");
      }
    }
  }

  despawnspikeFence(spikeFence) {
    spikeFence.runCommand("/playanimation @s animation.hb_cb.spike_fence.despawn");
    system.waitTicks(1).then(() => {
      if (spikeFence.hasTag("hb_cb:start_block_despawn")) {
        spikeFence.teleport({ x: spikeFence.location.x, y: spikeFence.location.y + 0.5, z: spikeFence.location.z });
      }
      let block = world.getDimension(spikeFence.dimension.id).getBlock({ x: spikeFence.location.x, y: spikeFence.location.y, z: spikeFence.location.z });
      let block2 = world.getDimension(spikeFence.dimension.id).getBlock({ x: spikeFence.location.x, y: spikeFence.location.y + 1, z: spikeFence.location.z });
      block.setType("minecraft:air");
      block2.setType("minecraft:air");
      let spawnedItem = new ItemStack(spikeFence.typeId + "_item");
      world.getDimension(spikeFence.dimension.id).spawnItem(spawnedItem, spikeFence.location);
      spikeFence.remove();
    });
  }
}

export function getBlockStatesAndDirection(player, selectedItem, face) {
  let resolvedBlockId = selectedItem?.typeId;
  if (selectedItem?.typeId.includes("_item") && selectedItem?.typeId.includes("hb_cb:")) {
    resolvedBlockId = selectedItem?.typeId.replace("_item", "_block");
  }
  if (!BlockTypes.get(resolvedBlockId)) {
    return false;
  }
  const blockPermutation = BlockPermutation.resolve(resolvedBlockId);
  if (!blockPermutation) return false;
  const blockStates = blockPermutation.getAllStates();
  let stateName = null;
  let stateValue = null;

  // Prioritize block states in a specific order
  const statePriority = ["minecraft:vertical_half", "minecraft:block_face", "minecraft:cardinal_direction", "pillar_axis", "facing_direction"];
  for (const state of statePriority) {
    if (blockStates[state] !== undefined) {
      stateName = state;
      if (state === "pillar_axis") {
        // Determine pillar_axis based on face
        if (["North", "South"].includes(face)) {
          stateValue = "z";
        } else if (["East", "West"].includes(face)) {
          stateValue = "x";
        } else {
          stateValue = "y";
        }
      } else if (state === "minecraft:cardinal_direction") {
        // Calculate direction based on player's rotation
        const rotation = player.getRotation();
        const rad = (rotation.y * Math.PI) / 180;
        const directionX = -Math.sin(rad);
        const directionZ = Math.cos(rad);

        // Determine cardinal direction based on calculated direction
        if (Math.abs(directionX) > Math.abs(directionZ)) {
          stateValue = directionX > 0 ? "east" : "west";
        } else {
          stateValue = directionZ > 0 ? "south" : "north";
        }
      } else if (state === "facing_direction") {
        // Calculate direction based on player's rotation
        const rotation = player.getRotation();
        const rad = (rotation.y * Math.PI) / 180;
        const directionX = -Math.sin(rad);
        const directionZ = Math.cos(rad);

        // Determine cardinal direction based on calculated direction
        if (Math.abs(directionX) > Math.abs(directionZ)) {
          stateValue = directionX > 0 ? 2 : 3;
        } else {
          stateValue = directionZ > 0 ? 0 : 1;
        }
      } else if (state === "minecraft:block_face") {
        // Determine block_face based on face
        stateValue = face.toLowerCase();
      } else if (state === "minecraft:vertical_half") {
        // Use getBlockFromViewDirection to get the exact hit location on the block face
        const raycastOptions = {
          maxDistance: 5, // Adjust as needed
          includePassableBlocks: false,
        };

        const raycastHit = player.getBlockFromViewDirection(raycastOptions);

        if (raycastHit) {
          const faceLocation = raycastHit.faceLocation;

          if (face === "Up" || face === "Down") {
            stateValue = face === "Up" ? "bottom" : "top";
          } else {
            // For side faces, use the y-coordinate of the faceLocation
            stateValue = faceLocation.y > 0.5 ? "top" : "bottom";
          }
        } else {
          // Fallback to default behavior if raycast fails
          if (face === "Up") {
            stateValue = "bottom";
          } else if (face === "Down") {
            stateValue = "top";
          } else {
            stateValue = "bottom"; // Default to bottom for non-slab blocks
          }
        }
      } else {
        stateValue = blockStates[state];
      }
      break;
    }
  }

  return { stateName, stateValue, resolvedBlockId };
}

export function applyDurabilityDamage(player, item, inventory, slotIndex) {
  const durabilityComponent = item.getComponent("minecraft:durability");
  if (durabilityComponent) {
    const { unbreakingLevel } = getRelevantEnchantments(item);

    if (Math.random() < 1 / (unbreakingLevel + 1)) {
      const newDamage = durabilityComponent.damage + 1;
      if (newDamage >= durabilityComponent.maxDurability) {
        inventory.container.setItem(slotIndex, undefined);
        player.playSound("random.break");
      } else {
        durabilityComponent.damage = newDamage;
        inventory.container.setItem(slotIndex, item);
      }
    }
  }
}
export function getRelevantEnchantments(item) {
  let unbreakingLevel = 0;
  let hasSilkTouch = false;

  try {
    const enchantableComponent = item.getComponent("minecraft:enchantable");
    if (enchantableComponent) {
      const enchantments = enchantableComponent.getEnchantments();
      for (const enchant of enchantments) {
        if (enchant.type.id === "unbreaking") {
          unbreakingLevel = enchant.level;
        } else if (enchant.type.id === "silk_touch") {
          hasSilkTouch = true;
        }
      }
    }
  } catch (error) {}
  return { unbreakingLevel, hasSilkTouch };
}

function changeBlockItemtoEntityItems(player) {
  const playerContainer = player.getComponent("inventory").container;
  for (let i = 0; i < playerContainer.size; i++) {
    const item = playerContainer.getItem(i);
    if (!item) continue;
    if (item.typeId.includes("hb_cb:spike_fence") && item.typeId.includes("_block")) {
      let replaceItem = new ItemStack(item.typeId.replace("_block", "_item"), item.amount);
      playerContainer.setItem(i, replaceItem);
    }
  }
}
