import { world, system, Player, Entity, BlockPermutation, ItemStack, BlockTypes, Block } from "@minecraft/server";
import showDialogueOnItemUse from "./util/show-dialogue-on-item-use";
import showsettings from "./util/showsettings";

import { compatableBlocks, compatableMiniBlocks } from "./globals";

let ow = world.getDimension("overworld");
const EVENT_ID = "float_mb:showtranslateui";
const SETTINGS_EVENT_ID = "float_mb:showsettings";
const FIRSTTIME_EVENT_ID = "float_mb:firsttime";
world.afterEvents.playerSpawn.subscribe((event) => {
  try {
    if (event.player) {
      if (event.player.hasTag("has_float_mb_book")) {
      } else {
        event.player.runCommandAsync("function fs/mb/init");
        const key = `float_mb:refresh_rate`;
        world.setDynamicProperty(key, 2);
        world.setDynamicProperty("float_mb:miniblockConvertion", true);
        world.getDynamicProperty("float_mb:miniblockConvertionSneakToggle", true);
      }
    }
  } catch {}
});
// Use a function to always get the latest refresh rate
function getSelectionBoxRefreshRate() {
  return world.getDynamicProperty("float_mb:refresh_rate") || 5;
}

function getMiniBlockConversion() {
  return world.getDynamicProperty("float_mb:miniblockConvertion") || false;
}

function getMiniBlockConversionSneakToggle() {
  return world.getDynamicProperty("float_mb:miniblockConvertionSneakToggle") || true;
}

// Remove the old slectionBoxRefreshRate variable and its update interval

system.runInterval(() => {
  const overworld = world.getDimension("overworld");
  const players = world.getPlayers();

  // Combine handling of both interaction and placement selection boxes
  const selectionBoxTypes = [
    "float_mb:quarter_block_selection_box",
    "float_mb:quarter_block_selection_box_placement",
    "float_mb:conversion_selection_box",
  ];

  selectionBoxTypes.forEach((type) => {
    const selectionBoxes = overworld.getEntities({ type });

    selectionBoxes.forEach((selectionBox) => {
      const isNearPlayer = players.some((player) => {
        const dx = player.location.x - selectionBox.location.x;
        const dy = player.location.y - selectionBox.location.y;
        const dz = player.location.z - selectionBox.location.z;
        return dx * dx + dy * dy + dz * dz <= 64; // 8^2 = 64
      });

      if (!isNearPlayer) {
        selectionBox.triggerEvent("float_mb:remove");
      }
    });
  });
}, 80);

let selectionBoxEntity = null;
let lastBlockLocation = null;
let lastBlockFace = null;
let currentBoxType = null;
let placementInteraction = null;
let quarterExists = null;

// Use a dynamic interval for the selection box logic
function runSelectionBoxInterval() {
  const refreshRate = getSelectionBoxRefreshRate();
  const miniblockConversion = getMiniBlockConversion();
  system.runTimeout(() => {
    const players = world.getPlayers();
    players.forEach((player) => {
      const equipment = player.getComponent("equippable");
      const selectedItem = equipment?.getEquipment("Mainhand");
      const selectionBoxEnabled = player.hasTag("selection_box");
      if (!selectionBoxEnabled) {
        return;
      }

      if (miniblockConversion) {
        const viewDirection = player.getViewDirection();
        const startPosition = player.getHeadLocation();
        const rayLength = 8;
        const rayDirection = {
          x: viewDirection.x,
          y: viewDirection.y,
          z: viewDirection.z,
        };

        const rayOptions = {
          maxDistance: rayLength,
          includeLiquidBlocks: false,
          includePassableBlocks: false,
        };

        const blockHit = player.dimension.getBlockFromRay(startPosition, rayDirection, rayOptions);

        if (blockHit && compatableBlocks.has(blockHit.block.typeId)) {
          //TESTING
          //console.error("§2§lBlock Hit: " + blockHit.block.typeId);
          if (
            selectedItem &&
            (selectedItem.typeId.includes("pickaxe") ||
              selectedItem.typeId.includes("shovel") ||
              selectedItem.typeId.includes("axe"))
          ) {
            const blockLocation = blockHit.block.location;
            const faceLocation = blockHit.faceLocation;
            const face = blockHit.face;

            if (
              !lastBlockLocation ||
              lastBlockLocation.x !== blockLocation.x ||
              lastBlockLocation.y !== blockLocation.y ||
              lastBlockLocation.z !== blockLocation.z ||
              lastBlockFace !== face ||
              currentBoxType !== "conversion"
            ) {
              // Remove the previous selection box if location or face has changed
              if (selectionBoxEntity && selectionBoxEntity.isValid()) {
                selectionBoxEntity.triggerEvent("float_mb:remove");
                selectionBoxEntity = null;
              }
              lastBlockLocation = blockLocation;
              lastBlockFace = face;
              currentBoxType = "conversion";
              quarterExists = null;
            }
            if (!selectionBoxEntity || !selectionBoxEntity.isValid()) {
              selectionBoxEntity = player.dimension.spawnEntity("float_mb:conversion_selection_box", {
                x: blockLocation.x + 0.5,
                y: blockLocation.y,
                z: blockLocation.z + 0.5,
              });
            }
          }
        } else {
          // Remove conversion selection box if not looking at a compatible block or not holding proper tool
          if (selectionBoxEntity && selectionBoxEntity.isValid() && currentBoxType === "conversion") {
            selectionBoxEntity.triggerEvent("float_mb:remove");
            selectionBoxEntity = null;
            currentBoxType = null;
            lastBlockLocation = null;
            lastBlockFace = null;
            quarterExists = null;
          }
        }
      } else {
        // Remove conversion selection box if miniblock conversion is disabled
        if (selectionBoxEntity && selectionBoxEntity.isValid() && currentBoxType === "conversion") {
          selectionBoxEntity.triggerEvent("float_mb:remove");
          selectionBoxEntity = null;
          currentBoxType = null;
          lastBlockLocation = null;
          lastBlockFace = null;
          quarterExists = null;
        }
      }

      // Check if player is holding a miniblock
      if (selectedItem && selectedItem.typeId.startsWith("float_mb:mini_")) {
        const viewDirection = player.getViewDirection();
        const startPosition = player.getHeadLocation();
        const rayLength = 8;
        const rayDirection = {
          x: viewDirection.x,
          y: viewDirection.y,
          z: viewDirection.z,
        };

        const rayOptions = {
          maxDistance: rayLength,
          includeLiquidBlocks: false,
          includePassableBlocks: false,
        };

        const blockHit = player.dimension.getBlockFromRay(startPosition, rayDirection, rayOptions);

        // Interaction Selection Box
        if (blockHit && blockHit.block.typeId.startsWith("float_mb:")) {
          const blockLocation = blockHit.block.location;
          const faceLocation = blockHit.faceLocation;
          const face = blockHit.face;

          // Check if the looked-at block location or face has changed
          if (
            !lastBlockLocation ||
            lastBlockLocation.x !== blockLocation.x ||
            lastBlockLocation.y !== blockLocation.y ||
            lastBlockLocation.z !== blockLocation.z ||
            lastBlockFace !== face
          ) {
            // Remove the previous selection box if location or face has changed
            if (selectionBoxEntity && selectionBoxEntity.isValid()) {
              selectionBoxEntity.triggerEvent("float_mb:remove");
              selectionBoxEntity = null;
              currentBoxType = null;
            }
            lastBlockLocation = blockLocation;
            lastBlockFace = face;
            quarterExists = null;
          }

          // Calculate the quarter that will be placed
          let quarterName = calculateQuarterName(blockHit.block, faceLocation, face, player);

          // Check if the quarterName matches an existing quarter in the blockHit
          quarterExists = blockHit.block.permutation.getState(`float_mb:${quarterName}`);

          if (quarterExists) {
            quarterName = calculateQuarterNamePlacing(blockHit.block, faceLocation, face, player);
            placementInteraction = true;
            quarterExists = null;
          }

          // Determine the required box type
          const desiredBoxType = placementInteraction ? "placement" : "interaction";

          // Remove and respawn if box type has changed
          if (currentBoxType !== desiredBoxType) {
            if (selectionBoxEntity && selectionBoxEntity.isValid()) {
              selectionBoxEntity.triggerEvent("float_mb:remove");
              selectionBoxEntity = null;
            }
            currentBoxType = desiredBoxType;
          }

          let selectionBoxPosition = { ...blockLocation };

          if (placementInteraction) {
            // Adjust for placement interaction
            switch (face) {
              case "Up":
                selectionBoxPosition.y += 1;
                break;
              case "Down":
                selectionBoxPosition.y -= 1;
                break;
              case "North":
                selectionBoxPosition.z -= 1;
                break;
              case "South":
                selectionBoxPosition.z += 1;
                break;
              case "East":
                selectionBoxPosition.x += 1;
                break;
              case "West":
                selectionBoxPosition.x -= 1;
                break;
            }
          }

          // Summon the correct selection box if not existing or invalid
          if (!selectionBoxEntity || !selectionBoxEntity.isValid()) {
            const entityType = placementInteraction
              ? "float_mb:quarter_block_selection_box_placement"
              : "float_mb:quarter_block_selection_box";

            const spawnPosition = {
              x: selectionBoxPosition.x + 0.5,
              y: selectionBoxPosition.y + (placementInteraction ? 1 : 0),
              z: selectionBoxPosition.z + 0.5,
            };

            selectionBoxEntity = player.dimension.spawnEntity(entityType, spawnPosition);
          }

          const selectionBoxLocationBlock = player.dimension.getBlock(selectionBoxPosition);

          // Set the correct selection state
          let eventName;
          if (blockHit.block.typeId !== selectedItem.typeId && !placementInteraction) {
            eventName = "cant_place_selection";
          } else if (
            placementInteraction &&
            selectionBoxLocationBlock.typeId !== selectedItem.typeId &&
            selectionBoxLocationBlock.typeId !== "minecraft:air"
          ) {
            eventName = "cant_place_selection";
          } else {
            eventName = placementInteraction ? "no_breaking_selection" : "no_breaking_selection";
          }
          selectionBoxEntity.triggerEvent(`float_mb:${eventName}`);
          if (quarterName !== "Unknown") {
            // Call the appropriate event to display the correct quarter selection box
            selectionBoxEntity.triggerEvent(`float_mb:${quarterName.toLowerCase().replace(/ /g, "_")}`);
          }

          quarterExists = null;
          placementInteraction = null;
          return;
          //PLACEMENT SELECTION BOX
        } else if (blockHit) {
          const blockLocation = blockHit.block.location;
          const faceLocation = blockHit.faceLocation;
          const face = blockHit.face;

          if (
            !lastBlockLocation ||
            lastBlockLocation.x !== blockLocation.x ||
            lastBlockLocation.y !== blockLocation.y ||
            lastBlockLocation.z !== blockLocation.z ||
            lastBlockFace !== face
          ) {
            // Remove the previous selection box if location or face has changed
            if (selectionBoxEntity && selectionBoxEntity.isValid()) {
              selectionBoxEntity.triggerEvent("float_mb:remove");
              selectionBoxEntity = null;
            }
            lastBlockLocation = blockLocation;
            lastBlockFace = face;
            quarterExists = null;
          }

          // Calculate the quarter that will be placed
          const quarterName = calculateQuarterNamePlacing(blockHit.block, faceLocation, face, player);

          if (quarterName) {
            //Trouble shooting error commands
            //console.error("quarterName " + quarterName);
            //console.error("Face " + face);

            // Determine the position for the selection box based on the face of the block hit
            let selectionBoxPosition = { ...blockLocation };
            switch (face) {
              case "Up":
                selectionBoxPosition.y += 1;
                break;
              case "Down":
                selectionBoxPosition.y -= 1;
                break;
              case "North":
                selectionBoxPosition.z -= 1;
                break;
              case "South":
                selectionBoxPosition.z += 1;
                break;
              case "East":
                selectionBoxPosition.x += 1;
                break;
              case "West":
                selectionBoxPosition.x -= 1;
                break;
            }

            // Summon the selection box if it does not exist
            const existingPlacementBlock = player.dimension.getBlock(selectionBoxPosition);
            if (existingPlacementBlock.typeId === "minecraft:air") {
              if (!selectionBoxEntity || !selectionBoxEntity.isValid()) {
                selectionBoxEntity = player.dimension.spawnEntity("float_mb:quarter_block_selection_box_placement", {
                  x: selectionBoxPosition.x + 0.5,
                  y: selectionBoxPosition.y + 1,
                  z: selectionBoxPosition.z + 0.5,
                });
              }
              selectionBoxEntity.triggerEvent(`float_mb:no_breaking_selection`);

              if (quarterName !== "Unknown") {
                // Call the appropriate event to display the correct quarter selection box
                selectionBoxEntity.triggerEvent(`float_mb:${quarterName.toLowerCase().replace(/ /g, "_")}`);
              }
            } else if (existingPlacementBlock.typeId === selectedItem.typeId) {
              if (!selectionBoxEntity || !selectionBoxEntity.isValid()) {
                selectionBoxEntity = player.dimension.spawnEntity("float_mb:quarter_block_selection_box_placement", {
                  x: selectionBoxPosition.x + 0.5,
                  y: selectionBoxPosition.y + 1,
                  z: selectionBoxPosition.z + 0.5,
                });
              }
              selectionBoxEntity.triggerEvent(`float_mb:wrong_face_selection`);

              if (quarterName !== "Unknown") {
                // Call the appropriate event to display the correct quarter selection box
                selectionBoxEntity.triggerEvent(`float_mb:${quarterName.toLowerCase().replace(/ /g, "_")}`);
              }
            }
          }
          return;
        }
        // No valid block hit, remove the selection box
        if (selectionBoxEntity && selectionBoxEntity.isValid()) {
          selectionBoxEntity.triggerEvent("float_mb:remove");
          selectionBoxEntity = null;
          lastBlockLocation = null;
          quarterExists = null;
        }
      }

      // Check if player is holding a pickaxe, shovel, or axe and looking at a miniblock
      if (
        selectedItem &&
        (selectedItem.typeId.includes("pickaxe") ||
          selectedItem.typeId.includes("shovel") ||
          selectedItem.typeId.includes("axe"))
      ) {
        const viewDirection = player.getViewDirection();
        const startPosition = player.getHeadLocation();
        const rayLength = 8; // Distance to check in front of player
        const rayDirection = {
          x: viewDirection.x,
          y: viewDirection.y,
          z: viewDirection.z,
        };

        const rayOptions = {
          maxDistance: rayLength,
          includeLiquidBlocks: false,
          includePassableBlocks: false,
        };

        const blockHit = player.dimension.getBlockFromRay(startPosition, rayDirection, rayOptions);

        if (blockHit && blockHit.block.typeId.startsWith("float_mb:")) {
          const blockLocation = blockHit.block.location;
          const faceLocation = blockHit.faceLocation;
          const face = blockHit.face;

          if (
            !lastBlockLocation ||
            lastBlockLocation.x !== blockLocation.x ||
            lastBlockLocation.y !== blockLocation.y ||
            lastBlockLocation.z !== blockLocation.z ||
            lastBlockFace !== face
          ) {
            // Remove the previous selection box if location or face has changed
            if (selectionBoxEntity && selectionBoxEntity.isValid()) {
              selectionBoxEntity.triggerEvent("float_mb:remove");
              selectionBoxEntity = null;
            }
            lastBlockLocation = blockLocation;
            lastBlockFace = face;
            quarterExists = null;
          }

          // Calculate the quarter that will be broken
          const quarterName = calculateQuarterNameBreaking(blockHit.block, faceLocation, face, player);

          if (quarterName) {
            // Display the quarter name on the player's actionbar
            //player.onScreenDisplay.setActionBar(`Looking at: ${quarterName}`);

            // Summon the selection box if it does not exist
            if (!selectionBoxEntity || !selectionBoxEntity.isValid()) {
              selectionBoxEntity = player.dimension.spawnEntity("float_mb:quarter_block_selection_box", {
                x: blockLocation.x + 0.5,
                y: blockLocation.y,
                z: blockLocation.z + 0.5,
              });
            }
            selectionBoxEntity.triggerEvent(`float_mb:breaking_selection`);

            if (quarterName !== "Unknown") {
              // Call the appropriate event to display the correct quarter selection box
              selectionBoxEntity.triggerEvent(`float_mb:${quarterName.toLowerCase().replace(/ /g, "_")}`);
            }
          }

          return;
        }
        // No valid block hit, remove the selection box
        if (selectionBoxEntity && selectionBoxEntity.isValid() && currentBoxType !== "conversion") {
          selectionBoxEntity.triggerEvent("float_mb:remove");
          selectionBoxEntity = null;
          currentBoxType = null;
          lastBlockLocation = null;
          lastBlockFace = null;
          quarterExists = null;
        }
      }

      // Remove selection box if player stops holding a miniblock or tool
      if (
        selectionBoxEntity &&
        selectionBoxEntity.isValid() &&
        (!selectedItem ||
          (!selectedItem.typeId.startsWith("float_mb:mini_") &&
            !(
              selectedItem.typeId.includes("pickaxe") ||
              selectedItem.typeId.includes("shovel") ||
              selectedItem.typeId.includes("axe")
            )))
      ) {
        selectionBoxEntity.triggerEvent("float_mb:remove");
        selectionBoxEntity = null;
        currentBoxType = null;
        lastBlockLocation = null;
        lastBlockFace = null;
        quarterExists = null;
      }
    });
    // Schedule the next run with the latest refresh rate
    runSelectionBoxInterval();
  }, refreshRate);
}

// Start the dynamic interval loop
runSelectionBoxInterval();

function calculateQuarterNamePlacing(block, FaceLocation, face, player) {
  // Retrieve the cardinal direction from dynamic properties
  const blockLocation = block.location;
  const dynamicKey = `float_mb:dir_${blockLocation.x}_${blockLocation.y}_${blockLocation.z}`;
  const dynamicProperties = world.getDynamicProperty(dynamicKey);
  const cardinalDirection = dynamicProperties ?? "north";

  const relativeX = FaceLocation.x - Math.floor(FaceLocation.x);
  const relativeZ = FaceLocation.z - Math.floor(FaceLocation.z);
  const isBottomHalf = FaceLocation.y - Math.floor(FaceLocation.y) < 0.5;

  let newState = "Unknown";
  if (isBottomHalf) {
    if (face === "Up") {
      newState =
        relativeX < 0.5 && relativeZ < 0.5
          ? "bottom_quarter_1"
          : relativeX >= 0.5 && relativeZ < 0.5
          ? "bottom_quarter_2"
          : relativeX < 0.5 && relativeZ >= 0.5
          ? "bottom_quarter_4"
          : "bottom_quarter_3";
    } else if (face === "Down") {
      newState =
        relativeX < 0.5 && relativeZ < 0.5
          ? "top_quarter_1"
          : relativeX >= 0.5 && relativeZ < 0.5
          ? "top_quarter_2"
          : relativeX < 0.5 && relativeZ >= 0.5
          ? "top_quarter_4"
          : "top_quarter_3";
    } else if (face === "North") {
      newState = relativeX < 0.5 ? "bottom_quarter_4" : "bottom_quarter_3";
    } else if (face === "South") {
      newState = relativeX < 0.5 ? "bottom_quarter_1" : "bottom_quarter_2";
    } else if (face === "East") {
      newState = relativeZ < 0.5 ? "bottom_quarter_1" : "bottom_quarter_4";
    } else if (face === "West") {
      newState = relativeZ < 0.5 ? "bottom_quarter_2" : "bottom_quarter_3";
    }
  } else {
    if (face === "North") {
      newState = relativeX < 0.5 ? "top_quarter_4" : "top_quarter_3";
    } else if (face === "South") {
      newState = relativeX < 0.5 ? "top_quarter_1" : "top_quarter_2";
    } else if (face === "East") {
      newState = relativeZ < 0.5 ? "top_quarter_1" : "top_quarter_4";
    } else if (face === "West") {
      newState = relativeZ < 0.5 ? "top_quarter_2" : "top_quarter_3";
    }
  }
  return newState;
}

function calculateQuarterName(block, FaceLocation, face, player) {
  const dirKey = `float_mb:dir_${block.location.x}_${block.location.y}_${block.location.z}`;
  const cardinalDirection = world.getDynamicProperty(dirKey) || "north"; // fallback if not stored

  const verticalHalf = block.permutation.getState("minecraft:vertical_half");
  //console.error("§2§lCardinal Direction: " + cardinalDirection);

  // Check if the interaction is on a whole block face
  const isTopBottomWholeBlockFace = FaceLocation.y % 1 === 0;

  // Check if the interaction is on the side of a whole block
  const isSideOfWholeBlock = FaceLocation.x % 1 === 0 || FaceLocation.z % 1 === 0;

  // Determine the target block's location based on the cardinal direction and face
  let targetLocation = { ...block.location };
  let placedquarter = false;

  targetLocation = {
    x: Math.floor(block.location.x),
    y: Math.floor(block.location.y),
    z: Math.floor(block.location.z),
  };

  const targetBlock = block.dimension.getBlock(targetLocation);

  // Determine which quarter segment to update based on the face interacted with
  let updatedState = "Unknown";

  // Check if the quarter block already has more than one bottom_quarter_[1_4] traits set
  const bottomQuarters = [
    block.permutation.getState("float_mb:bottom_quarter_1"),
    block.permutation.getState("float_mb:bottom_quarter_2"),
    block.permutation.getState("float_mb:bottom_quarter_3"),
    block.permutation.getState("float_mb:bottom_quarter_4"),
  ];
  const topQuarters = [
    block.permutation.getState("float_mb:top_quarter_1"),
    block.permutation.getState("float_mb:top_quarter_2"),
    block.permutation.getState("float_mb:top_quarter_3"),
    block.permutation.getState("float_mb:top_quarter_4"),
  ];

  const activeBottomQuarters = bottomQuarters.filter(Boolean).length;
  const activeTopQuarters = topQuarters.filter(Boolean).length;
  const relativeX = FaceLocation.x - Math.floor(FaceLocation.x);
  const relativeZ = FaceLocation.z - Math.floor(FaceLocation.z);
  const isBottomHalf = FaceLocation.y - Math.floor(FaceLocation.y) < 0.5;
  const isTopHalf = FaceLocation.y - Math.floor(FaceLocation.y) >= 0.5;

  if (face === "Up") {
    if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_1") &&
      block.permutation.getState("float_mb:bottom_quarter_2")
    ) {
      updatedState = "bottom_quarter_1";
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_2") &&
      block.permutation.getState("float_mb:bottom_quarter_1")
    ) {
      updatedState = "bottom_quarter_2";
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_3") &&
      block.permutation.getState("float_mb:bottom_quarter_4")
    ) {
      updatedState = "bottom_quarter_3";
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_4") &&
      block.permutation.getState("float_mb:bottom_quarter_3")
    ) {
      updatedState = "bottom_quarter_4";
      placedquarter = true;
    } else placedquarter = false;

    if (!placedquarter) {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        updatedState = "top_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        updatedState = "top_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        updatedState = "top_quarter_4";
      } else {
        updatedState = "top_quarter_3";
      }
    }
  } else if (face === "Down") {
    if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_1") &&
      block.permutation.getState("float_mb:top_quarter_2")
    ) {
      updatedState = "top_quarter_1";
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_2") &&
      block.permutation.getState("float_mb:top_quarter_1")
    ) {
      updatedState = "top_quarter_2";
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_3") &&
      block.permutation.getState("float_mb:top_quarter_4")
    ) {
      updatedState = "top_quarter_3";
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_4") &&
      block.permutation.getState("float_mb:top_quarter_3")
    ) {
      updatedState = "top_quarter_4";
      placedquarter = true;
    } else placedquarter = false;
    if (!placedquarter) {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        updatedState = "bottom_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        updatedState = "bottom_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        updatedState = "bottom_quarter_4";
      } else {
        updatedState = "bottom_quarter_3";
      }
    }
  } else if (isBottomHalf) {
    if (activeBottomQuarters >= 1) {
      switch (face) {
        case "North":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_4") &&
            block.permutation.getState("float_mb:top_quarter_4") &&
            relativeX < 0.5
          ) {
            updatedState = "bottom_quarter_4";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_3") &&
            block.permutation.getState("float_mb:top_quarter_3") &&
            relativeX > 0.5
          ) {
            updatedState = "bottom_quarter_3";
          } else {
            updatedState = relativeX < 0.5 ? "bottom_quarter_1" : "bottom_quarter_2";
          }
          break;
        case "South":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_1") &&
            block.permutation.getState("float_mb:top_quarter_1") &&
            relativeX < 0.5
          ) {
            updatedState = "bottom_quarter_1";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_2") &&
            block.permutation.getState("float_mb:top_quarter_2") &&
            relativeX > 0.5
          ) {
            updatedState = "bottom_quarter_2";
          } else {
            updatedState = relativeX < 0.5 ? "bottom_quarter_4" : "bottom_quarter_3";
          }
          break;
        case "East":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_1") &&
            block.permutation.getState("float_mb:top_quarter_1") &&
            relativeZ < 0.5
          ) {
            updatedState = "bottom_quarter_1";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_4") &&
            block.permutation.getState("float_mb:top_quarter_4") &&
            relativeZ > 0.5
          ) {
            updatedState = "bottom_quarter_4";
          } else {
            updatedState = relativeZ < 0.5 ? "bottom_quarter_2" : "bottom_quarter_3";
          }
          break;
        case "West":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_2") &&
            block.permutation.getState("float_mb:top_quarter_2") &&
            relativeZ < 0.5
          ) {
            updatedState = "bottom_quarter_2";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_3") &&
            block.permutation.getState("float_mb:top_quarter_3") &&
            relativeZ > 0.5
          ) {
            updatedState = "bottom_quarter_3";
          } else {
            updatedState = relativeZ < 0.5 ? "bottom_quarter_1" : "bottom_quarter_4";
          }
          break;
        default:
          console.error("Bottom quarter placement error.");
      }
    }
  } else if (isTopHalf) {
    if (activeTopQuarters >= 1) {
      switch (face) {
        case "North":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_4") &&
            block.permutation.getState("float_mb:bottom_quarter_4") &&
            relativeX < 0.5
          ) {
            updatedState = "top_quarter_4";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_3") &&
            block.permutation.getState("float_mb:bottom_quarter_3") &&
            relativeX > 0.5
          ) {
            updatedState = "top_quarter_3";
          } else {
            updatedState = relativeX < 0.5 ? "top_quarter_1" : "top_quarter_2";
          }

          break;
        case "South":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_1") &&
            block.permutation.getState("float_mb:bottom_quarter_1") &&
            relativeX < 0.5
          ) {
            updatedState = "top_quarter_1";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_2") &&
            block.permutation.getState("float_mb:bottom_quarter_2") &&
            relativeX > 0.5
          ) {
            updatedState = "top_quarter_2";
          } else {
            updatedState = relativeX < 0.5 ? "top_quarter_4" : "top_quarter_3";
          }
          break;
        case "East":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_1") &&
            block.permutation.getState("float_mb:bottom_quarter_1") &&
            relativeZ < 0.5
          ) {
            updatedState = "top_quarter_1";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_4") &&
            block.permutation.getState("float_mb:bottom_quarter_4") &&
            relativeZ > 0.5
          ) {
            updatedState = "top_quarter_4";
          } else {
            updatedState = relativeZ < 0.5 ? "top_quarter_2" : "top_quarter_3";
          }
          break;
        case "West":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_2") &&
            block.permutation.getState("float_mb:bottom_quarter_2") &&
            relativeZ < 0.5
          ) {
            updatedState = "top_quarter_2";
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_3") &&
            block.permutation.getState("float_mb:bottom_quarter_3") &&
            relativeZ > 0.5
          ) {
            updatedState = "top_quarter_3";
          } else {
            updatedState = relativeZ < 0.5 ? "top_quarter_1" : "top_quarter_4";
          }
          break;
        default:
          console.error("Bottom quarter placement error.");
      }
    }
  } else {
    // Proceed with the original logic if there are not more than one bottom_quarter traits set
    switch (face) {
      case "North":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "south" && verticalHalf === "bottom"
            ? "bottom_quarter_4"
            : cardinalDirection === "west" && verticalHalf === "bottom"
            ? "bottom_quarter_2"
            : "top_quarter_4"),
        };
        break;
      case "South":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "north" && verticalHalf === "bottom"
            ? "bottom_quarter_4"
            : cardinalDirection === "east" && verticalHalf === "bottom"
            ? "bottom_quarter_2"
            : "top_quarter_2"),
        };
        break;
      case "East":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "west" && verticalHalf === "bottom"
            ? "bottom_quarter_4"
            : cardinalDirection === "north" && verticalHalf === "bottom"
            ? "bottom_quarter_2"
            : "top_quarter_1"),
        };
        break;
      case "West":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "south" && verticalHalf === "bottom"
            ? "bottom_quarter_2"
            : cardinalDirection === "east" && verticalHalf === "bottom"
            ? "bottom_quarter_4"
            : "top_quarter_3"),
        };
        break;
      default:
        console.error("Invalid face interaction.");
        return;
    }
  }

  return updatedState;
}

function calculateQuarterNameBreaking(block, FaceLocation, face, player) {
  // Retrieve the current permutation of the block
  const currentPermutation = block.permutation;

  // Determine the relative position of the interaction
  const relativeX = FaceLocation.x - Math.floor(FaceLocation.x);
  const relativeZ = FaceLocation.z - Math.floor(FaceLocation.z);
  let isBottomHalf = FaceLocation.y - Math.floor(FaceLocation.y) < 0.5;

  // Check if the interaction is on a whole block face
  const isTopBottomWholeBlockFace = FaceLocation.y % 1 === 0;

  // Check if the interaction is on the side of a whole block
  const isSideOfWholeBlock = FaceLocation.x % 1 === 0 || FaceLocation.z % 1 === 0;

  // Get the cardinal direction of the block
  const blockLocation = block.location;
  const dynamicKey = `float_mb:dir_${blockLocation.x}_${blockLocation.y}_${blockLocation.z}`;
  const dynamicProperties = world.getDynamicProperty(dynamicKey);
  const cardinalDirection = dynamicProperties ?? "north";

  let quarterToRemove = "Unknown";

  // If interacting with a whole block face, always remove a top quarter
  if (isTopBottomWholeBlockFace) {
    //console.error("Interaction on a whole block face, removing a top quarter.");
    isBottomHalf = false; // Force to top half
  }

  // Determine which quarter to remove based on the face, cardinal direction, and relative face locations
  if (isTopBottomWholeBlockFace) {
    if (face === "Up") {
      // If interacting with a whole block face, calculate the location on the face using relativeX and relativeZ
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "top_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "top_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "top_quarter_4";
      } else {
        quarterToRemove = "top_quarter_3";
      }
    } else if (face === "Down") {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "bottom_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "bottom_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "bottom_quarter_4";
      } else {
        quarterToRemove = "bottom_quarter_3";
      }
    }
  } else if (isSideOfWholeBlock) {
    // If interacting with the side of a whole block

    quarterToRemove =
      face === "East"
        ? relativeZ >= 0.5
          ? isBottomHalf
            ? "bottom_quarter_3"
            : "top_quarter_3"
          : isBottomHalf
          ? "bottom_quarter_2"
          : "top_quarter_2"
        : face === "West"
        ? relativeZ < 0.5
          ? isBottomHalf
            ? "bottom_quarter_1"
            : "top_quarter_1"
          : isBottomHalf
          ? "bottom_quarter_4"
          : "top_quarter_4"
        : face === "North"
        ? relativeX < 0.5
          ? isBottomHalf
            ? "bottom_quarter_1"
            : "top_quarter_1"
          : isBottomHalf
          ? "bottom_quarter_2"
          : "top_quarter_2"
        : face === "South"
        ? relativeX >= 0.5
          ? isBottomHalf
            ? "bottom_quarter_3"
            : "top_quarter_3"
          : isBottomHalf
          ? "bottom_quarter_4"
          : "top_quarter_4"
        : null;
  } else {
    // If interacting with a specific quarter

    if (face === "Up") {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "bottom_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "bottom_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "bottom_quarter_4";
      } else {
        quarterToRemove = "bottom_quarter_3";
      }
    } else if (face === "Down") {
      //console.error("running down");
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "top_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "top_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "top_quarter_4";
      } else {
        quarterToRemove = "top_quarter_3";
      }
    } else {
      quarterToRemove =
        face === "North"
          ? relativeX < 0.5
            ? isBottomHalf
              ? "bottom_quarter_4"
              : "top_quarter_4"
            : isBottomHalf
            ? "bottom_quarter_3"
            : "top_quarter_3"
          : face === "South"
          ? relativeX >= 0.5
            ? isBottomHalf
              ? "bottom_quarter_2"
              : "top_quarter_2"
            : isBottomHalf
            ? "bottom_quarter_1"
            : "top_quarter_1"
          : face === "East"
          ? relativeZ >= 0.5
            ? isBottomHalf
              ? "bottom_quarter_4"
              : "top_quarter_4"
            : isBottomHalf
            ? "bottom_quarter_1"
            : "top_quarter_1"
          : face === "West"
          ? relativeZ < 0.5
            ? isBottomHalf
              ? "bottom_quarter_2"
              : "top_quarter_2"
            : isBottomHalf
            ? "bottom_quarter_3"
            : "top_quarter_3"
          : quarterToRemove;
    }
  }

  return quarterToRemove;
}
let quarterExists2 = null;
//Block Component Registry
world.beforeEvents.worldInitialize.subscribe((event) => {
  event.blockComponentRegistry.registerCustomComponent("float_mb:on_step_on", {
    onStepOn: (e) => {
      const tag = e.block.getTags().map((t) => t.replace(/^mini_/, ""));
      if (
        tag[0] === "bamboo" ||
        tag[0] === "mangrove_roots" ||
        tag[0] === "mud" ||
        tag[0] === "mud_bricks" ||
        tag[0] === "muddy_mangrove_roots" ||
        tag[0] === "packed_mud"
      ) {
        const soundId = "block." + tag[0] + ".step";
        e.entity.playSound(soundId, { location: e.entity.location, volume: 0.4 });
      } else {
        const soundId = "step." + tag[0];
        try {
          e.entity.playSound(soundId, { location: e.entity.location, volume: 0.4 });
        } catch (error) {}
      }
    },
  });
  // Quarter placement
  event.blockComponentRegistry.registerCustomComponent("float_mb:on_interact_quarter", {
    onPlayerInteract: (e) => {
      const equipment = e.player.getComponent("equippable");
      const selectedItem = equipment?.getEquipment("Mainhand");
      const onplace = false;

      if (selectedItem?.typeId === e.block.typeId) {
        //console.error("Block type ID: " + e.block.typeId, "Facelocation: " + e.faceLocation.x);
        quarterPlace(e.block, e.faceLocation, e.face, onplace, e.player);
        // Remove 1 item from the player's main hand if not in creative mode
        if (e.player.getGameMode() !== "creative") {
          if (selectedItem.amount > 1) {
            selectedItem.amount -= 1;
            equipment.setEquipment("Mainhand", selectedItem);
          } else {
            equipment.setEquipment("Mainhand", undefined);
          }
        }
        playPlaceSound(e);
      } else if (selectedItem?.typeId.startsWith("float_mb:mini_")) {
        if (selectedItem?.typeId !== e.block.typeId) {
          const viewDirection = e.player.getViewDirection();
          const startPosition = e.player.getHeadLocation();
          const rayLength = 8;
          const rayDirection = {
            x: viewDirection.x,
            y: viewDirection.y,
            z: viewDirection.z,
          };
          const rayOptions = {
            maxDistance: rayLength,
            includeLiquidBlocks: false,
            includePassableBlocks: false,
          };
          const blockHit = e.player.dimension.getBlockFromRay(startPosition, rayDirection, rayOptions);
          let quarterName = calculateQuarterName(blockHit.block, e.faceLocation, e.face, e.player);

          // Check if the quarterName matches an existing quarter in the blockHit
          quarterExists2 = blockHit.block.permutation.getState(`float_mb:${quarterName}`);
          if (quarterExists2) {
            quarterName = calculateQuarterNamePlacing(blockHit.block, e.faceLocation, e.face, e.player);
            quarterExists2 = null;
            const blockLocation = blockHit.block.location;
            let selectionBoxPosition = { ...blockLocation };
            switch (e.face) {
              case "Up":
                selectionBoxPosition.y += 1;
                break;
              case "Down":
                selectionBoxPosition.y -= 1;
                break;
              case "North":
                selectionBoxPosition.z -= 1;
                break;
              case "South":
                selectionBoxPosition.z += 1;
                break;
              case "East":
                selectionBoxPosition.x += 1;
                break;
              case "West":
                selectionBoxPosition.x -= 1;
                break;
            }
            // Create a new block permutation based on the block held in the player's mainhand
            const newBlockTypeId = selectedItem.typeId;
            const targetBlock = blockHit.block.dimension.getBlock(selectionBoxPosition);
            if (targetBlock.typeId === "minecraft:air") {
              if (quarterName !== "bottom_quarter_1") {
                const newPermutation = BlockPermutation.resolve(newBlockTypeId, {
                  "float_mb:bottom_quarter_1": false,
                  [`float_mb:${quarterName}`]: true,
                });
                const targetBlock = blockHit.block.dimension.getBlock(selectionBoxPosition);
                if (targetBlock) {
                  targetBlock.setPermutation(newPermutation);
                }
              } else {
                const newPermutation = BlockPermutation.resolve(newBlockTypeId, {
                  [`float_mb:${quarterName}`]: true,
                });
                // Set the newPermutation on the block at selectionBoxPosition
                const targetBlock = blockHit.block.dimension.getBlock(selectionBoxPosition);
                if (targetBlock) {
                  targetBlock.setPermutation(newPermutation);
                }
              }
              if (e.player.getGameMode() !== "creative") {
                if (selectedItem.amount > 1) {
                  selectedItem.amount -= 1;
                  equipment.setEquipment("Mainhand", selectedItem);
                } else {
                  equipment.setEquipment("Mainhand", undefined);
                }
              }
              playPlaceSound(e);
            } else if (selectedItem.typeId === targetBlock.typeId) {
              const newBlock = e.block.dimension.getBlock(selectionBoxPosition);
              const existingStates = newBlock.permutation.getAllStates();
              const mergedStates = { ...existingStates, [`float_mb:${quarterName}`]: true };
              newBlock.setPermutation(BlockPermutation.resolve(newBlock.typeId, mergedStates));
            }
          }
        }
      }
    },
  });
  event.blockComponentRegistry.registerCustomComponent("float_mb:on_place_quarter", {
    beforeOnPlayerPlace: (e) => {
      const player = e.player;
      const onplace = true;
      const viewDirection = player.getViewDirection();
      const startPosition = player.getHeadLocation();
      const rayLength = 10; // Adjust the ray length as needed
      const rayDirection = {
        x: viewDirection.x,
        y: viewDirection.y,
        z: viewDirection.z,
      };

      const rayOptions = {
        maxDistance: rayLength,
        includeLiquidBlocks: false,
        includePassableBlocks: true,
      };

      const blockHit = player.dimension.getBlockFromRay(startPosition, rayDirection, rayOptions);
      if (blockHit) {
        const faceLocation = blockHit.faceLocation;
        const blockLocation = blockHit.block.location;
        const combinedLocation = {
          x: blockLocation.x + faceLocation.x,
          y: blockLocation.y + faceLocation.y,
          z: blockLocation.z + faceLocation.z,
        };

        //console.error(`Combined Location: x=${combinedLocation.x}, y=${combinedLocation.y}, z=${combinedLocation.z}`);
        const equipment = e.player.getComponent("equippable");
        const selectedItem = equipment?.getEquipment("Mainhand");
        storeCardinalDirectionOnPlace(e.block, player);

        quarterPlace(e.block, combinedLocation, e.face, onplace, player, e.permutationToPlace);
        playPlaceSound(e);
        e.cancel = true; // Prevent the default placement behavior
      } else {
        console.log("No block was hit by the ray.");
      }
    },
  });
});
function destroyQuarter(quarterBlock, FaceLocation, face, player, destroyedBlockPermutation) {
  // Retrieve the current permutation of the block
  const currentPermutation = destroyedBlockPermutation;

  // Determine the relative position of the interaction
  const relativeX = FaceLocation.x - Math.floor(FaceLocation.x);
  const relativeZ = FaceLocation.z - Math.floor(FaceLocation.z);
  let isBottomHalf = FaceLocation.y - Math.floor(FaceLocation.y) < 0.5;

  // Check if the interaction is on a whole block face
  const isTopBottomWholeBlockFace = FaceLocation.y % 1 === 0;

  // Check if the interaction is on the side of a whole block
  const isSideOfWholeBlock = FaceLocation.x % 1 === 0 || FaceLocation.z % 1 === 0;

  // Get the cardinal direction of the block
  const blockLocation = quarterBlock.location;
  const dynamicKey = `float_mb:dir_${blockLocation.x}_${blockLocation.y}_${blockLocation.z}`;
  const dynamicProperties = world.getDynamicProperty(dynamicKey);
  const cardinalDirection = dynamicProperties ?? "north";

  let quarterToRemove = null;
  //console.error("Cardinal direction: " + cardinalDirection);
  //console.error("face: " + face);
  //console.error("Relative X: " + relativeX);
  //console.error("Relative Z: " + relativeZ);
  //console.error(isBottomHalf ? "Bottom half" : "Top half");
  //console.error(isSideOfWholeBlock ? "Side of whole block" : "Not side of whole block");

  // If interacting with a whole block face, always remove a top quarter
  if (isTopBottomWholeBlockFace) {
    //console.error("Interaction on a whole block face, removing a top quarter.");
    isBottomHalf = false; // Force to top half
  }

  // Determine which quarter to remove based on the face, cardinal direction, and relative face locations
  if (isTopBottomWholeBlockFace) {
    if (face === "Up") {
      // If interacting with a whole block face, calculate the location on the face using relativeX and relativeZ
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:top_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:top_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "float_mb:top_quarter_4";
      } else {
        quarterToRemove = "float_mb:top_quarter_3";
      }
    } else if (face === "Down") {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:bottom_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:bottom_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "float_mb:bottom_quarter_4";
      } else {
        quarterToRemove = "float_mb:bottom_quarter_3";
      }
    }
  } else if (isSideOfWholeBlock) {
    // If interacting with the side of a whole block

    quarterToRemove =
      face === "East"
        ? relativeZ >= 0.5
          ? isBottomHalf
            ? "float_mb:bottom_quarter_3"
            : "float_mb:top_quarter_3"
          : isBottomHalf
          ? "float_mb:bottom_quarter_2"
          : "float_mb:top_quarter_2"
        : face === "West"
        ? relativeZ < 0.5
          ? isBottomHalf
            ? "float_mb:bottom_quarter_1"
            : "float_mb:top_quarter_1"
          : isBottomHalf
          ? "float_mb:bottom_quarter_4"
          : "float_mb:top_quarter_4"
        : face === "North"
        ? relativeX < 0.5
          ? isBottomHalf
            ? "float_mb:bottom_quarter_1"
            : "float_mb:top_quarter_1"
          : isBottomHalf
          ? "float_mb:bottom_quarter_2"
          : "float_mb:top_quarter_2"
        : face === "South"
        ? relativeX >= 0.5
          ? isBottomHalf
            ? "float_mb:bottom_quarter_3"
            : "float_mb:top_quarter_3"
          : isBottomHalf
          ? "float_mb:bottom_quarter_4"
          : "float_mb:top_quarter_4"
        : null;
  } else {
    // If interacting with a specific quarter

    if (face === "Up") {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:bottom_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:bottom_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "float_mb:bottom_quarter_4";
      } else {
        quarterToRemove = "float_mb:bottom_quarter_3";
      }
    } else if (face === "Down") {
      //console.error("running down");
      if (relativeX < 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:top_quarter_1";
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        quarterToRemove = "float_mb:top_quarter_2";
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        quarterToRemove = "float_mb:top_quarter_4";
      } else {
        quarterToRemove = "float_mb:top_quarter_3";
      }
    } else {
      quarterToRemove =
        face === "North"
          ? relativeX < 0.5
            ? isBottomHalf
              ? "float_mb:bottom_quarter_4"
              : "float_mb:top_quarter_4"
            : isBottomHalf
            ? "float_mb:bottom_quarter_3"
            : "float_mb:top_quarter_3"
          : face === "South"
          ? relativeX >= 0.5
            ? isBottomHalf
              ? "float_mb:bottom_quarter_2"
              : "float_mb:top_quarter_2"
            : isBottomHalf
            ? "float_mb:bottom_quarter_1"
            : "float_mb:top_quarter_1"
          : face === "East"
          ? relativeZ >= 0.5
            ? isBottomHalf
              ? "float_mb:bottom_quarter_4"
              : "float_mb:top_quarter_4"
            : isBottomHalf
            ? "float_mb:bottom_quarter_1"
            : "float_mb:top_quarter_1"
          : face === "West"
          ? relativeZ < 0.5
            ? isBottomHalf
              ? "float_mb:bottom_quarter_2"
              : "float_mb:top_quarter_2"
            : isBottomHalf
            ? "float_mb:bottom_quarter_3"
            : "float_mb:top_quarter_3"
          : quarterToRemove;
    }
  }

  if (quarterToRemove && quarterBlock.typeId !== "minecraft:air") {
    //console.error("Removing quarter: " + quarterToRemove);
    // Update the permutation to remove the specified quarter
    const updatedPermutation = currentPermutation.withState(quarterToRemove, false);

    // Set the updated permutation on the block
    system.run(() => {
      quarterBlock.setPermutation(updatedPermutation);
    });

    // Only drop the item if the permutation actually changed (i.e., a quarter was removed)
    if (
      player.getGameMode() !== "creative" &&
      currentPermutation.getAllStates &&
      updatedPermutation.getAllStates &&
      JSON.stringify(currentPermutation.getAllStates()) !== JSON.stringify(updatedPermutation.getAllStates())
    ) {
      system.run(() => {
        const itemStack = new ItemStack(quarterBlock.typeId, 1);
        quarterBlock.dimension.spawnItem(itemStack, quarterBlock.location);
      });
    }

    // Check if all quarters are removed, and if so, destroy the block
    const allQuarters = [
      "float_mb:bottom_quarter_1",
      "float_mb:bottom_quarter_2",
      "float_mb:bottom_quarter_3",
      "float_mb:bottom_quarter_4",
      "float_mb:top_quarter_1",
      "float_mb:top_quarter_2",
      "float_mb:top_quarter_3",
      "float_mb:top_quarter_4",
    ];
    const hasAnyQuarter = allQuarters.some((quarter) => updatedPermutation.getState(quarter));

    if (!hasAnyQuarter) {
      removeCardinalDirectionDynamic(quarterBlock);
      playDestroySoundBlock(quarterBlock);
      system.run(() => {
        quarterBlock.setType(BlockTypes.get("minecraft:air"));
      });
    }
    playDestroySoundBlock(quarterBlock);
  }
}

function placeQuarter(quarterBlock, FaceLocation, face, player, permutationToPlace) {
  const updatedPermutation = permutationToPlace.withState("float_mb:bottom_quarter_1", false);

  // Retrieve the cardinal direction from dynamic properties
  const blockLocation = quarterBlock.location;
  const dynamicKey = `float_mb:dir_${blockLocation.x}_${blockLocation.y}_${blockLocation.z}`;
  const dynamicProperties = world.getDynamicProperty(dynamicKey);
  const cardinalDirection = dynamicProperties ?? "north";

  const block = quarterBlock.dimension.getBlock(quarterBlock.location);

  const relativeX = FaceLocation.x - Math.floor(FaceLocation.x);
  const relativeZ = FaceLocation.z - Math.floor(FaceLocation.z);
  const isBottomHalf = FaceLocation.y - Math.floor(FaceLocation.y) < 0.5;

  let newState = {};

  //console.error("§1Cardinal direction: " + cardinalDirection);
  //console.error("§2face: " + face);

  // Determine the correct quarter to place based on the face and cardinal direction
  // NOTE - ALL CARDINAL DIRECTIONS ARE THE SAME faces with new dynamic properties
  if (isBottomHalf) {
    if (face === "Up") {
      newState =
        relativeX < 0.5 && relativeZ < 0.5
          ? { "float_mb:bottom_quarter_1": true }
          : relativeX >= 0.5 && relativeZ < 0.5
          ? { "float_mb:bottom_quarter_2": true }
          : relativeX < 0.5 && relativeZ >= 0.5
          ? { "float_mb:bottom_quarter_4": true }
          : { "float_mb:bottom_quarter_3": true };
    } else if (face === "Down") {
      newState =
        relativeX < 0.5 && relativeZ < 0.5
          ? { "float_mb:top_quarter_1": true }
          : relativeX >= 0.5 && relativeZ < 0.5
          ? { "float_mb:top_quarter_2": true }
          : relativeX < 0.5 && relativeZ >= 0.5
          ? { "float_mb:top_quarter_4": true }
          : { "float_mb:top_quarter_3": true };
    } else if (face === "North") {
      newState = relativeX < 0.5 ? { "float_mb:bottom_quarter_4": true } : { "float_mb:bottom_quarter_3": true };
    } else if (face === "South") {
      newState = relativeX < 0.5 ? { "float_mb:bottom_quarter_1": true } : { "float_mb:bottom_quarter_2": true };
    } else if (face === "East") {
      newState = relativeZ < 0.5 ? { "float_mb:bottom_quarter_1": true } : { "float_mb:bottom_quarter_4": true };
    } else if (face === "West") {
      newState = relativeZ < 0.5 ? { "float_mb:bottom_quarter_2": true } : { "float_mb:bottom_quarter_3": true };
    }
  } else {
    if (face === "North") {
      newState = relativeX < 0.5 ? { "float_mb:top_quarter_4": true } : { "float_mb:top_quarter_3": true };
    } else if (face === "South") {
      newState = relativeX < 0.5 ? { "float_mb:top_quarter_1": true } : { "float_mb:top_quarter_2": true };
    } else if (face === "East") {
      newState = relativeZ < 0.5 ? { "float_mb:top_quarter_1": true } : { "float_mb:top_quarter_4": true };
    } else if (face === "West") {
      newState = relativeZ < 0.5 ? { "float_mb:top_quarter_2": true } : { "float_mb:top_quarter_3": true };
    }
  }

  if (Object.keys(newState).length === 0) {
    //player.sendMessage("§cDo not sneak while placing a Mini Block on top/bottom of an existing Mini Block.");
    block.setType(permutationToPlace.type.id); // Set block to the quarter plank we are placing
    const defaultPermutation = BlockPermutation.resolve(block.typeId, {
      "float_mb:bottom_quarter_1": true,
      "float_mb:bottom_quarter_2": false,
      "float_mb:bottom_quarter_3": false,
      "float_mb:bottom_quarter_4": false,
      "float_mb:top_quarter_1": false,
      "float_mb:top_quarter_2": false,
      "float_mb:top_quarter_3": false,
      "float_mb:top_quarter_4": false,
    });
    block.setPermutation(defaultPermutation);
    return;
  }
  const finalPermutation = updatedPermutation.withState(Object.keys(newState)[0], Object.values(newState)[0]);
  // Set the new state on the block
  system.run(() => {
    block.setPermutation(finalPermutation);
    playPlaceSoundBlock(block);
    // Remove 1 item from player's main hand if not in creative
    if (player.getGameMode() !== "creative") {
      const equipment = player.getComponent("equippable");
      const selectedItem = equipment?.getEquipment("Mainhand");
      if (selectedItem) {
        if (selectedItem.amount > 1) {
          selectedItem.amount -= 1;
          equipment.setEquipment("Mainhand", selectedItem);
        } else {
          equipment.setEquipment("Mainhand", undefined);
        }
      }
    }
  });
}

function storeCardinalDirectionOnPlace(block, player) {
  //console.error("Storing cardinal direction on place");
  const rotation = ((player.getRotation().y % 360) + 360) % 360;
  let cardinalDirection;
  if (rotation >= 315 || rotation < 45) {
    cardinalDirection = "south";
  } else if (rotation >= 45 && rotation < 135) {
    cardinalDirection = "west";
  } else if (rotation >= 135 && rotation < 225) {
    cardinalDirection = "north";
  } else {
    cardinalDirection = "east";
  }

  const key = `float_mb:dir_${block.location.x}_${block.location.y}_${block.location.z}`;
  world.setDynamicProperty(key, cardinalDirection);
  //console.error(`Stored dynamic property: ${key} = ${cardinalDirection}`);
}

function removeCardinalDirectionDynamic(block) {
  const key = `float_mb:dir_:${block.location.x},${block.location.y},${block.location.z}`;
  world.setDynamicProperty(key, null);
  //console.error(`Removed cardinal direction dynamic property for ${key}`);
}

function updateQuarter(quarterBlock, FaceLocation, face, player) {
  const block = quarterBlock;

  const dirKey = `float_mb:dir_${block.location.x}_${block.location.y}_${block.location.z}`;
  const cardinalDirection = world.getDynamicProperty(dirKey) || "north"; // fallback if not stored

  const verticalHalf = block.permutation.getState("minecraft:vertical_half");
  //console.error("§2§lCardinal Direction: " + cardinalDirection);

  // Check if the interaction is on a whole block face
  const isTopBottomWholeBlockFace = FaceLocation.y % 1 === 0;

  // Check if the interaction is on the side of a whole block
  const isSideOfWholeBlock = FaceLocation.x % 1 === 0 || FaceLocation.z % 1 === 0;

  // Determine the target block's location based on the cardinal direction and face
  let targetLocation = { ...block.location };
  let placedquarter = false;

  targetLocation = {
    x: Math.floor(block.location.x),
    y: Math.floor(block.location.y),
    z: Math.floor(block.location.z),
  };

  const targetBlock = block.dimension.getBlock(targetLocation);

  // Determine which quarter segment to update based on the face interacted with
  let updatedState = {};

  // Check if the quarter block already has more than one bottom_quarter_[1_4] traits set
  const bottomQuarters = [
    block.permutation.getState("float_mb:bottom_quarter_1"),
    block.permutation.getState("float_mb:bottom_quarter_2"),
    block.permutation.getState("float_mb:bottom_quarter_3"),
    block.permutation.getState("float_mb:bottom_quarter_4"),
  ];
  const topQuarters = [
    block.permutation.getState("float_mb:top_quarter_1"),
    block.permutation.getState("float_mb:top_quarter_2"),
    block.permutation.getState("float_mb:top_quarter_3"),
    block.permutation.getState("float_mb:top_quarter_4"),
  ];

  const activeBottomQuarters = bottomQuarters.filter(Boolean).length;
  const activeTopQuarters = topQuarters.filter(Boolean).length;
  const relativeX = FaceLocation.x - Math.floor(FaceLocation.x);
  const relativeZ = FaceLocation.z - Math.floor(FaceLocation.z);
  const isBottomHalf = FaceLocation.y - Math.floor(FaceLocation.y) < 0.5;
  const isTopHalf = FaceLocation.y - Math.floor(FaceLocation.y) >= 0.5;

  if (face === "Up") {
    if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_1") &&
      block.permutation.getState("float_mb:bottom_quarter_2")
    ) {
      updatedState = { "float_mb:bottom_quarter_1": true };
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_2") &&
      block.permutation.getState("float_mb:bottom_quarter_1")
    ) {
      updatedState = { "float_mb:bottom_quarter_2": true };
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_3") &&
      block.permutation.getState("float_mb:bottom_quarter_4")
    ) {
      updatedState = { "float_mb:bottom_quarter_3": true };
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:bottom_quarter_4") &&
      block.permutation.getState("float_mb:bottom_quarter_3")
    ) {
      updatedState = { "float_mb:bottom_quarter_4": true };
      placedquarter = true;
    } else placedquarter = false;

    if (!placedquarter) {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        updatedState = { "float_mb:top_quarter_1": true };
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        updatedState = { "float_mb:top_quarter_2": true };
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        updatedState = { "float_mb:top_quarter_4": true };
      } else {
        updatedState = { "float_mb:top_quarter_3": true };
      }
    }
  } else if (face === "Down") {
    if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_1") &&
      block.permutation.getState("float_mb:top_quarter_2")
    ) {
      updatedState = { "float_mb:top_quarter_1": true };
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ < 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_2") &&
      block.permutation.getState("float_mb:top_quarter_1")
    ) {
      updatedState = { "float_mb:top_quarter_2": true };
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX >= 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_3") &&
      block.permutation.getState("float_mb:top_quarter_4")
    ) {
      updatedState = { "float_mb:top_quarter_3": true };
      placedquarter = true;
    } else if (
      !isTopBottomWholeBlockFace &&
      relativeX < 0.5 &&
      relativeZ >= 0.5 &&
      !block.permutation.getState("float_mb:top_quarter_4") &&
      block.permutation.getState("float_mb:top_quarter_3")
    ) {
      updatedState = { "float_mb:top_quarter_4": true };
      placedquarter = true;
    } else placedquarter = false;
    if (!placedquarter) {
      if (relativeX < 0.5 && relativeZ < 0.5) {
        updatedState = { "float_mb:bottom_quarter_1": true };
      } else if (relativeX >= 0.5 && relativeZ < 0.5) {
        updatedState = { "float_mb:bottom_quarter_2": true };
      } else if (relativeX < 0.5 && relativeZ >= 0.5) {
        updatedState = { "float_mb:bottom_quarter_4": true };
      } else {
        updatedState = { "float_mb:bottom_quarter_3": true };
      }
    }
  } else if (isBottomHalf) {
    if (activeBottomQuarters >= 1) {
      switch (face) {
        case "North":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_4") &&
            block.permutation.getState("float_mb:top_quarter_4") &&
            relativeX < 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_4": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_3") &&
            block.permutation.getState("float_mb:top_quarter_3") &&
            relativeX > 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_3": true };
          } else {
            updatedState =
              relativeX < 0.5 ? { "float_mb:bottom_quarter_1": true } : { "float_mb:bottom_quarter_2": true };
          }
          break;
        case "South":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_1") &&
            block.permutation.getState("float_mb:top_quarter_1") &&
            relativeX < 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_1": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_2") &&
            block.permutation.getState("float_mb:top_quarter_2") &&
            relativeX > 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_2": true };
          } else {
            updatedState =
              relativeX < 0.5 ? { "float_mb:bottom_quarter_4": true } : { "float_mb:bottom_quarter_3": true };
          }
          break;
        case "East":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_1") &&
            block.permutation.getState("float_mb:top_quarter_1") &&
            relativeZ < 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_1": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_4") &&
            block.permutation.getState("float_mb:top_quarter_4") &&
            relativeZ > 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_4": true };
          } else {
            updatedState =
              relativeZ < 0.5 ? { "float_mb:bottom_quarter_2": true } : { "float_mb:bottom_quarter_3": true };
          }
          break;
        case "West":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_2") &&
            block.permutation.getState("float_mb:top_quarter_2") &&
            relativeZ < 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_2": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:bottom_quarter_3") &&
            block.permutation.getState("float_mb:top_quarter_3") &&
            relativeZ > 0.5
          ) {
            updatedState = { "float_mb:bottom_quarter_3": true };
          } else {
            updatedState =
              relativeZ < 0.5 ? { "float_mb:bottom_quarter_1": true } : { "float_mb:bottom_quarter_4": true };
          }
          break;
        default:
          console.error("Bottom quarter placement error.");
      }
    }
  } else if (isTopHalf) {
    if (activeTopQuarters >= 1) {
      switch (face) {
        case "North":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_4") &&
            block.permutation.getState("float_mb:bottom_quarter_4") &&
            relativeX < 0.5
          ) {
            updatedState = { "float_mb:top_quarter_4": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_3") &&
            block.permutation.getState("float_mb:bottom_quarter_3") &&
            relativeX > 0.5
          ) {
            updatedState = { "float_mb:top_quarter_3": true };
          } else {
            updatedState = relativeX < 0.5 ? { "float_mb:top_quarter_1": true } : { "float_mb:top_quarter_2": true };
          }

          break;
        case "South":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_1") &&
            block.permutation.getState("float_mb:bottom_quarter_1") &&
            relativeX < 0.5
          ) {
            updatedState = { "float_mb:top_quarter_1": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_2") &&
            block.permutation.getState("float_mb:bottom_quarter_2") &&
            relativeX > 0.5
          ) {
            updatedState = { "float_mb:top_quarter_2": true };
          } else {
            updatedState = relativeX < 0.5 ? { "float_mb:top_quarter_4": true } : { "float_mb:top_quarter_3": true };
          }
          break;
        case "East":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_1") &&
            block.permutation.getState("float_mb:bottom_quarter_1") &&
            relativeZ < 0.5
          ) {
            updatedState = { "float_mb:top_quarter_1": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_4") &&
            block.permutation.getState("float_mb:bottom_quarter_4") &&
            relativeZ > 0.5
          ) {
            updatedState = { "float_mb:top_quarter_4": true };
          } else {
            updatedState = relativeZ < 0.5 ? { "float_mb:top_quarter_2": true } : { "float_mb:top_quarter_3": true };
          }
          break;
        case "West":
          if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_2") &&
            block.permutation.getState("float_mb:bottom_quarter_2") &&
            relativeZ < 0.5
          ) {
            updatedState = { "float_mb:top_quarter_2": true };
          } else if (
            !isSideOfWholeBlock &&
            !block.permutation.getState("float_mb:top_quarter_3") &&
            block.permutation.getState("float_mb:bottom_quarter_3") &&
            relativeZ > 0.5
          ) {
            updatedState = { "float_mb:top_quarter_3": true };
          } else {
            updatedState = relativeZ < 0.5 ? { "float_mb:top_quarter_1": true } : { "float_mb:top_quarter_4": true };
          }
          break;
        default:
          console.error("Bottom quarter placement error.");
      }
    }
  } else {
    // Proceed with the original logic if there are not more than one bottom_quarter traits set
    switch (face) {
      case "North":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "south" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_4": true }
            : cardinalDirection === "west" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_2": true }
            : { "float_mb:top_quarter_4": true }),
        };
        break;
      case "South":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "north" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_4": true }
            : cardinalDirection === "east" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_2": true }
            : { "float_mb:top_quarter_2": true }),
        };
        break;
      case "East":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "west" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_4": true }
            : cardinalDirection === "north" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_2": true }
            : { "float_mb:top_quarter_1": true }),
        };
        break;
      case "West":
        updatedState = {
          ...updatedState,
          ...(cardinalDirection === "south" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_2": true }
            : cardinalDirection === "east" && verticalHalf === "bottom"
            ? { "float_mb:bottom_quarter_4": true }
            : { "float_mb:top_quarter_3": true }),
        };
        break;
      default:
        console.error("Invalid face interaction.");
        return;
    }
  }

  // Check if the updated state matches the existing state
  const existingState = block.permutation.getAllStates();
  const isSameState = Object.entries(updatedState).every(([key, value]) => existingState[key] === value);
  let faceLocationMatches = true;

  if (isSameState) {
    // Update the block's permutation with the new state
    faceLocationMatches =
      Math.floor(FaceLocation.x) === Math.floor(block.location.x) &&
      Math.floor(FaceLocation.z) === Math.floor(block.location.z);
  }

  if (isSameState || !faceLocationMatches) {
    // Determine the direction of the face the player interacted with
    let newQuarterState = {};
    if (updatedState["float_mb:bottom_quarter_4"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        }
      }
    } else if (updatedState["float_mb:bottom_quarter_3"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        }
      }
    } else if (updatedState["float_mb:bottom_quarter_2"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        }
      }
    } else if (updatedState["float_mb:bottom_quarter_1"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        } else if (face === "Down") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        }
      }
    } else if (updatedState["float_mb:top_quarter_4"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_4": true };
        }
      }
    } else if (updatedState["float_mb:top_quarter_3"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_3": true };
        }
      }
    } else if (updatedState["float_mb:top_quarter_2"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_1": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_2": true };
        }
      }
    } else if (updatedState["float_mb:top_quarter_1"]) {
      if (cardinalDirection === "north") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        }
      } else if (cardinalDirection === "south") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        }
      } else if (cardinalDirection === "east") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        }
      } else if (cardinalDirection === "west") {
        if (face === "North") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "West") {
          newQuarterState = { "float_mb:top_quarter_2": true };
        } else if (face === "East") {
          newQuarterState = { "float_mb:top_quarter_3": true };
        } else if (face === "South") {
          newQuarterState = { "float_mb:top_quarter_4": true };
        } else if (face === "Up") {
          newQuarterState = { "float_mb:bottom_quarter_1": true };
        }
      }
    }

    // Calculate the new block's location based on the face direction
    const newBlockLocation = {
      x: block.location.x + (face === "East" ? 1 : face === "West" ? -1 : 0),
      y: block.location.y + (face === "Up" ? 1 : face === "Down" ? -1 : 0),
      z: block.location.z + (face === "South" ? 1 : face === "North" ? -1 : 0),
    };

    // Check if a quarter block already exists at the calculated location
    const newBlock = block.dimension.getBlock(newBlockLocation);
    if (newBlock.typeId === block.typeId) {
      // If a quarter block exists, merge the newQuarterState with the existing block's states
      const existingStates = newBlock.permutation.getAllStates();
      const mergedStates = { ...existingStates, ...newQuarterState };
      newBlock.setPermutation(BlockPermutation.resolve(block.typeId, mergedStates));
    } else {
      // If no quarter block exists, place a new quarter block at the calculated location
      newBlock.setType(block.typeId);

      // Inherit the cardinal direction from the original block

      // If the updatedState was bottom_quarter_1 and it has changed, set it to false
      if (newQuarterState["float_mb:bottom_quarter_1"] === true) {
        newBlock.setPermutation(BlockPermutation.resolve(block.typeId, newQuarterState));
      } else {
        newQuarterState["float_mb:bottom_quarter_1"] = false;
        newBlock.setPermutation(BlockPermutation.resolve(block.typeId, newQuarterState));
      }
    }
    return;
  }

  // Update the target block's permutation to reflect the new quarter placement
  for (const [key, value] of Object.entries(updatedState)) {
    targetBlock.setPermutation(targetBlock.permutation.withState(key, value));
  }
  // Log all active quarters on the block for debugging purposes
  //console.error("Active quarters on the block:");
  //console.error("bottom_quarter_1:", block.permutation.getState("float_mb:bottom_quarter_1"));
  //console.error("bottom_quarter_2:", block.permutation.getState("float_mb:bottom_quarter_2"));
  //console.error("bottom_quarter_3:", block.permutation.getState("float_mb:bottom_quarter_3"));
  //console.error("bottom_quarter_4:", block.permutation.getState("float_mb:bottom_quarter_4"));
}

function quarterPlace(quarterBlock, faceLocation, face, onplace, player, permutationToPlace) {
  if (onplace) {
    placeQuarter(quarterBlock, faceLocation, face, player, permutationToPlace);
  } else {
    updateQuarter(quarterBlock, faceLocation, face, player);
  }
}
function quarterDestroy(quarterBlock, faceLocation, face, onplace, player, destroyedBlockPermutation) {
  destroyQuarter(quarterBlock, faceLocation, face, player, destroyedBlockPermutation);
}

//Breaking Block Control
function handleBeforePlayerBreak(e) {
  const miniblockConversion = getMiniBlockConversion();
  if (e.block.typeId.startsWith("float_mb:mini")) {
    const player = e.player;
    const onplace = true;
    const viewDirection = player.getViewDirection();
    const startPosition = player.getHeadLocation();
    const rayLength = 10; // Adjust the ray length as needed
    const rayDirection = {
      x: viewDirection.x,
      y: viewDirection.y,
      z: viewDirection.z,
    };

    const rayOptions = {
      maxDistance: rayLength,
      includeLiquidBlocks: false,
      includePassableBlocks: true,
    };

    const blockHit = player.dimension.getBlockFromRay(startPosition, rayDirection, rayOptions);
    if (blockHit) {
      const faceLocation = blockHit.faceLocation;
      const blockLocation = blockHit.block.location;
      const combinedLocation = {
        x: blockLocation.x + faceLocation.x,
        y: blockLocation.y + faceLocation.y,
        z: blockLocation.z + faceLocation.z,
      };

      const equipment = e.player.getComponent("equippable");
      const selectedItem = equipment?.getEquipment("Mainhand");
      //console.error("blockhit id: " + blockHit.block.typeId);

      system.run(() => {
        quarterDestroy(e.block, combinedLocation, blockHit.face, onplace, player, e.block.permutation);
      });
      e.cancel = true; // Prevent the default placement behavior
    } else {
      console.log("No block was hit by the ray.");
    }
  } else if (compatableBlocks.has(e.block.typeId) && miniblockConversion) {
    const player = e.player;
    const onplace = true;
    const viewDirection = player.getViewDirection();
    const startPosition = player.getHeadLocation();
    const rayLength = 10; // Adjust the ray length as needed
    const rayDirection = {
      x: viewDirection.x,
      y: viewDirection.y,
      z: viewDirection.z,
    };

    const rayOptions = {
      maxDistance: rayLength,
      includeLiquidBlocks: false,
      includePassableBlocks: true,
    };

    const blockHit = player.dimension.getBlockFromRay(startPosition, rayDirection, rayOptions);
    if (blockHit) {
      const faceLocation = blockHit.faceLocation;
      const blockLocation = blockHit.block.location;
      const combinedLocation = {
        x: blockLocation.x + faceLocation.x,
        y: blockLocation.y + faceLocation.y,
        z: blockLocation.z + faceLocation.z,
      };

      const equipment = e.player.getComponent("equippable");
      const selectedItem = equipment?.getEquipment("Mainhand");
      if (
        selectedItem &&
        (selectedItem.typeId.includes("pickaxe") ||
          selectedItem.typeId.includes("shovel") ||
          selectedItem.typeId.includes("axe"))
      ) {
        convertToMiniBlock(e.block, combinedLocation, blockHit.face, onplace, e.player, e.block.permutation);
        e.cancel = true; // Prevent the default placement behavior
      }
    }
  }
}

function convertToMiniBlock(block, FaceLocation, face, player, destroyedBlockPermutation) {
  // Only convert if the block is in compatableBlocks and has a miniblock counterpart
  if (!compatableBlocks.has(block.typeId)) return;

  // Find the corresponding miniblock typeId
  let miniBlockTypeId = null;
  // Find the index of the block type in compatableBlocks
  const blockTypesArray = Array.from(compatableBlocks);
  const miniBlocksArray = Array.from(compatableMiniBlocks);
  const index = blockTypesArray.indexOf(block.typeId);
  if (index !== -1 && miniBlocksArray[index]) {
    miniBlockTypeId = miniBlocksArray[index];
  }
  if (!miniBlockTypeId) return;

  // Replace the block with the miniblock, default to bottom_quarter_1 true
  const newPermutation = BlockPermutation.resolve(miniBlockTypeId, {
    "float_mb:bottom_quarter_1": true,
    "float_mb:bottom_quarter_2": true,
    "float_mb:bottom_quarter_3": true,
    "float_mb:bottom_quarter_4": true,
    "float_mb:top_quarter_1": true,
    "float_mb:top_quarter_2": true,
    "float_mb:top_quarter_3": true,
    "float_mb:top_quarter_4": true,
  });

  system.run(() => {
    block.setType(miniBlockTypeId);
    block.setPermutation(newPermutation);
  });
  //const rotation = ((player.getRotation().y % 360) + 360) % 360;
  // Store the cardinal direction for the new miniblock
  // Get the player closest to the block
  const players = world.getPlayers();
  let closestPlayer = null;
  let minDistSq = Infinity;
  for (const p of players) {
    const dx = p.location.x - block.location.x;
    const dy = p.location.y - block.location.y;
    const dz = p.location.z - block.location.z;
    const distSq = dx * dx + dy * dy + dz * dz;
    if (distSq < minDistSq) {
      minDistSq = distSq;
      closestPlayer = p;
    }
  }
  const nearestPlayer = closestPlayer;

  storeCardinalDirectionOnPlace(block, nearestPlayer);

  destroyQuarter(block, FaceLocation, face, nearestPlayer, newPermutation);
  playDestroySoundBlock(block);
}

// Double-sneak detection and toggle miniblock conversion
const doubleSneakTimers = new Map();

function handlePlayerButtonInput(e) {
  const player = e.player;
  const button = e.button;
  const newButtonState = e.newButtonState;
  const SneakToggle = getMiniBlockConversionSneakToggle();
  if (!SneakToggle) {
    return;
  }
  if (button === "Sneak" && newButtonState === "Pressed") {
    // Only care about sneak button pressed down
    const now = Date.now();
    const last = doubleSneakTimers.get(player.id) || 0;
    if (now - last < 400) {
      // 400ms window for double-tap
      // Toggle the dynamic property
      const current = world.getDynamicProperty("float_mb:miniblockConvertion");
      world.setDynamicProperty("float_mb:miniblockConvertion", !current);
      // Optionally, notify the player
      player.sendMessage(`§eMiniBlock Conversion: ${!current ? "§aEnabled" : "§cDisabled"}`);
      doubleSneakTimers.delete(player.id);
    } else {
      doubleSneakTimers.set(player.id, now);
      // Remove timer after 500ms to avoid memory leak
      system.runTimeout(() => {
        if (doubleSneakTimers.get(player.id) === now) {
          doubleSneakTimers.delete(player.id);
        }
      }, 10); // 10 ticks ~ 500ms
    }
  }
}

world.beforeEvents.playerBreakBlock.subscribe(handleBeforePlayerBreak);

world.afterEvents.playerButtonInput.subscribe(handlePlayerButtonInput);

//Rotating Mini Blocks
function handleBeforeItemUse(event) {}
world.beforeEvents.itemUseOn.subscribe(handleBeforeItemUse);

function playPlaceSound(event) {
  const tag = event.block.getTags().map((t) => t.replace(/^mini_/, ""));
  if (
    tag[0] === "stone" ||
    tag[0] === "sand" ||
    tag[0] === "grass" ||
    tag[0] === "snow" ||
    tag[0] === "gravel" ||
    tag[0] === "honey_block" ||
    tag[0] === "bone_block" ||
    tag[0] === "wood" ||
    tag[0] === "cloth"
  ) {
    const soundId = "dig." + tag[0];
    event.block.dimension.runCommandAsync(
      `playsound ${soundId} @a ${event.block.location.x} ${event.block.location.y} ${event.block.location.z}`
    );
  } else if (tag[0] === "mud_bricks" || tag[0] === "packed_mud" || tag[0] === "mangrove_roots") {
    const soundId = "block." + tag[0] + ".place";
    system.run(() => {
      event.block.dimension.playSound(soundId, event.block.location);
    });
  } else if (tag[0] === "tuff") {
    const soundId = "place." + tag[0];
    system.run(() => {
      event.block.dimension.playSound(soundId, event.block.location);
    });
  } else if (tag[0] === "glass") {
    system.run(() => {
      event.block.dimension.playSound("dig.stone", event.block.location);
    });
  } else if (tag[0] === "resin") {
    system.run(() => {
      event.block.dimension.playSound("block.resin.place", event.block.location);
    });
  } else if (tag[0] === "resin_brick") {
    system.run(() => {
      event.block.dimension.playSound("block.resin_brick.place", event.block.location);
    });
  } else if (tag[0] === "mud") {
    system.run(() => {
      event.block.dimension.playSound("block.mud.place", event.block.location);
    });
  } else {
    const soundId = "place." + tag[0];
    system.run(() => {
      event.block.dimension.playSound(soundId, event.block.location);
    });
  }
}
function playPlaceSoundBlock(block) {
  const tag = block.getTags().map((t) => t.replace(/^mini_/, ""));
  if (
    tag[0] === "stone" ||
    tag[0] === "sand" ||
    tag[0] === "grass" ||
    tag[0] === "snow" ||
    tag[0] === "gravel" ||
    tag[0] === "honey_block" ||
    tag[0] === "bone_block" ||
    tag[0] === "wood" ||
    tag[0] === "cloth"
  ) {
    const soundId = "dig." + tag[0];
    block.dimension.runCommandAsync(
      `playsound ${soundId} @a ${block.location.x} ${block.location.y} ${block.location.z}`
    );
  } else if (tag[0] === "mud_bricks" || tag[0] === "packed_mud" || tag[0] === "mangrove_roots") {
    const soundId = "block." + tag[0] + ".place";
    system.run(() => {
      block.dimension.playSound(soundId, block.location);
    });
  } else if (tag[0] === "tuff") {
    const soundId = "place." + tag[0];
    system.run(() => {
      block.dimension.playSound(soundId, block.location);
    });
  } else if (tag[0] === "glass") {
    system.run(() => {
      block.dimension.playSound("dig.stone", block.location);
    });
  } else if (tag[0] === "resin") {
    system.run(() => {
      block.dimension.playSound("block.resin.place", block.location);
    });
  } else if (tag[0] === "resin_brick") {
    system.run(() => {
      block.dimension.playSound("block.resin_brick.place", block.location);
    });
  } else if (tag[0] === "mud") {
    system.run(() => {
      block.dimension.playSound("block.mud.place", block.location);
    });
  } else {
    const soundId = "place." + tag[0];
    system.run(() => {
      block.dimension.playSound(soundId, block.location);
    });
  }
}
function playDestroySoundBlock(block) {
  const tag = block.getTags().map((t) => t.replace(/^mini_/, ""));
  if (
    tag[0] === "stone" ||
    tag[0] === "sand" ||
    tag[0] === "grass" ||
    tag[0] === "snow" ||
    tag[0] === "gravel" ||
    tag[0] === "honey_block" ||
    tag[0] === "bone_block" ||
    tag[0] === "wood" ||
    tag[0] === "cloth" ||
    tag[0] === "copper" ||
    tag[0] === "moss" ||
    tag[0] === "deepslate" ||
    tag[0] === "deepslate_bricks"
  ) {
    const soundId = "dig." + tag[0];
    system.run(() => {
      block.dimension.playSound(soundId, block.location);
    });
  } else if (tag[0] === "mud_bricks" || tag[0] === "packed_mud" || tag[0] === "mangrove_roots") {
    const soundId = "block." + tag[0] + ".break";
    system.run(() => {
      block.dimension.playSound(soundId, block.location);
    });
  } else if (tag[0] === "tuff" || tag[0] === "tuff_bricks") {
    const soundId = "place." + tag[0];
    system.run(() => {
      block.dimension.playSound(soundId, block.location);
    });
  } else if (tag[0] === "glass") {
    system.run(() => {
      block.dimension.playSound("random.glass", block.location);
    });
  } else if (tag[0] === "resin") {
    system.run(() => {
      block.dimension.playSound("block.resin.break", block.location);
    });
  } else if (tag[0] === "resin_brick") {
    system.run(() => {
      block.dimension.playSound("block.resin_brick.break", block.location);
    });
  } else if (tag[0] === "mud") {
    system.run(() => {
      block.dimension.playSound("block.mud.break", block.location);
    });
  } else {
    const soundId = "break." + tag[0];
    system.run(() => {
      block.dimension.playSound(soundId, block.location);
    });
  }
}

//Book translate UI
system.afterEvents.scriptEventReceive.subscribe(
  showDialogueOnItemUse({
    EventTypeId: EVENT_ID,
    title: {
      translate: "float_mb:guide.name",
    },
    content: {
      rawtext: [
        { translate: "float_mb:info.part_01", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_02", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_03", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_04", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_05", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_06", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_07", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_08", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_09", with: ["\n"] },
        { text: "§r\n\n" },
        { translate: "float_mb:info.part_10", with: ["\n"] },
        { text: "§r\n\n" },
      ],
    },
    exit: {
      translate: "float_mb:guide_exit",
    },
    soundOnOpen: "item.book.page_turn",
    soundOnClose: "item.book.page_turn",
  })
);

function handleScriptEvents(event) {
  var Players,
    Nearest,
    TempPlayer = undefined;
  var Dist,
    XDist,
    ZDist = 0.0;
  var i = 0;
  try {
    if (event.id == SETTINGS_EVENT_ID) {
      showsettings(event.sourceEntity);
    } else if (event.id == FIRSTTIME_EVENT_ID) {
      if (event.sourceEntity != undefined) {
        firstTimeQueue.push(event.sourceEntity);
      }
      system.runTimeout(processFirstTimers, 45);
    } else if (event.id == "float_mb:turnpage") {
      Players = world.getAllPlayers();
      Nearest = undefined;
      TempPlayer = undefined;
      Dist = Infinity;
      XDist = 0.0;
      ZDist = 0.0;
      i = 0;
      for (;;) {
        TempPlayer = Players[i];
        if (String(TempPlayer.name).valueOf() == String(event.message).valueOf()) {
          if (Nearest == undefined) {
            Nearest = TempPlayer;
            XDist *= XDist;
            ZDist = TempPlayer.location.z - event.sourceEntity.location.z;
            ZDist *= ZDist;
            Dist = XDist + ZDist;
          } else {
            XDist = TempPlayer.location.x - event.sourceEntity.location.x;
            XDist *= XDist;
            ZDist = TempPlayer.location.z - event.sourceEntity.location.z;
            ZDist *= ZDist;
            if (Dist > XDist + ZDist) {
              Dist = XDist + ZDist;
              Nearest = TempPlayer;
            }
          }
        }
        i++;
        if (i >= Players.length) {
          if (Nearest == undefined) {
          } else {
            let deltaX = Nearest.location.x - event.sourceEntity.location.x;
            let deltaZ = Nearest.location.z - event.sourceEntity.location.z;
            let targetAngle = Math.atan2(deltaZ, deltaX);
            let playerRotation = Nearest.getRotation().y * (Math.PI / 180);
            let angleDifference = targetAngle - playerRotation;
            angleDifference = ((angleDifference + Math.PI) % (2 * Math.PI)) - Math.PI / 2.0;
            if (angleDifference > 0) {
              system.runTimeout(() => {
                Nearest.dimension.runCommandAsync(`event entity @e[type=float_mb:book,c=1] float_mb:backflip`);
              }, 0);
            }
          }
          return;
        }
      }
    }
  } catch (e) {}
}

system.afterEvents.scriptEventReceive.subscribe(handleScriptEvents);
