import { system } from "@minecraft/server";
import { ItemInventoryContents } from "../utilities.js";

export function bridgeBuilder(player, item) {
  system.run(() => {
    const origin = player.location;
    const dimension = player.dimension;

    player.playSound("mob.wither.break_block", {
      pitch: 1.5,
      volume: 0.5,
      location: player.location,
    });

    let length = 10;
    let speed = 3;
    let blockType = "pb_gat:bridge_block";
    let guard = false;

    if (item) {
      const contents =
        new ItemInventoryContents(item).getContainer()?.content ?? [];

      if (contents.some((stack) => stack?.typeId === "pb_gat:orb_reach")) {
        length = 20;
      }

      if (contents.some((stack) => stack?.typeId === "pb_gat:orb_speed")) {
        speed = 1;
      }

      const hasLife = contents.some(
        (stack) => stack?.typeId === "pb_gat:orb_life"
      );
      const hasEmber = contents.some(
        (stack) => stack?.typeId === "pb_gat:orb_ember"
      );

      if (hasLife && hasEmber) {
        blockType = "pb_gat:ember_bridge_block_life";
      } else if (hasEmber) {
        blockType = "pb_gat:ember_bridge_block";
      } else if (hasLife) {
        blockType = "pb_gat:bridge_block_life";
      }

      if (contents.some((stack) => stack?.typeId === "pb_gat:orb_guard_rail")) {
        guard = true;
      }
    }

    const view = player.getViewDirection();
    const angle = Math.atan2(view.z, view.x) * (180 / Math.PI);
    const snappedAngle = Math.round(angle / 45) * 45;
    const radians = (snappedAngle * Math.PI) / 180;

    const dirX = Math.round(Math.cos(radians));
    const dirZ = Math.round(Math.sin(radians));

    const isDiagonal = Math.abs(dirX) === 1 && Math.abs(dirZ) === 1;

    const startX = Math.floor(origin.x);
    const startY = Math.round(origin.y - 1);
    const startZ = Math.floor(origin.z);

    for (let step = 0; step <= length + 1; step++) {
      const centerX = startX + dirX * step;
      const centerZ = startZ + dirZ * step;

      system.runTimeout(() => {
        // Build core bridge (3x3)
        if (step >= 1 && step <= length) {
          for (let dx = -1; dx <= 1; dx++) {
            for (let dz = -1; dz <= 1; dz++) {
              const x = centerX + dx;
              const z = centerZ + dz;
              const block = dimension.getBlock({ x, y: startY, z });
              if (
                block &&
                (block.isAir ||
                  block.typeId === "pb_gat:bridge_block" ||
                  block.typeId === "pb_gat:bridge_block_life" ||
                  block.typeId === "pb_gat:ember_bridge_block" ||
                  block.typeId === "pb_gat:ember_bridge_block_life")
              ) {
                player.playSound("step.stone", {
                  pitch: 1,
                  volume: 0.7,
                  location: block.location,
                });
                block.setType(blockType);
              }
            }
          }
        }

        // Add guard rails if enabled
        if (guard) {
          const railY = startY + 1;

          if (isDiagonal) {
            // For diagonals, compute a perpendicular offset
            const perpX = -dirZ; // 90 degree turn
            const perpZ = dirX;

            const railOffsets = [
              { dx: perpX, dz: perpZ },
              { dx: -perpX, dz: -perpZ },
            ];

            for (const { dx, dz } of railOffsets) {
              const x = centerX + dx;
              const z = centerZ + dz;
              const block = dimension.getBlock({ x, y: railY, z });
              if (
                block &&
                (block.isAir ||
                  block.typeId === "pb_gat:bridge_block" ||
                  block.typeId === "pb_gat:bridge_block_life" ||
                  block.typeId === "pb_gat:ember_bridge_block" ||
                  block.typeId === "pb_gat:ember_bridge_block_life")
              ) {
                player.playSound("step.stone", {
                  pitch: 1,
                  volume: 0.7,
                  location: block.location,
                });
                block.setType(blockType);
              }
            }
          } else {
            // Cardinal directions: rails left/right or front/back
            for (let offset = -2; offset <= 2; offset++) {
              if (dirX !== 0) {
                // East/West
                const x = centerX;
                const z = centerZ + offset;
                if (Math.abs(offset) === 2) {
                  const block = dimension.getBlock({ x, y: railY, z });
                  if (
                    block &&
                    (block.isAir ||
                      block.typeId === "pb_gat:bridge_block" ||
                      block.typeId === "pb_gat:bridge_block_life" ||
                      block.typeId === "pb_gat:ember_bridge_block" ||
                      block.typeId === "pb_gat:ember_bridge_block_life")
                  ) {
                    player.playSound("step.stone", {
                      pitch: 1,
                      volume: 0.7,
                      location: block.location,
                    });
                    block.setType(blockType);
                  }
                }
              } else if (dirZ !== 0) {
                // North/South
                const x = centerX + offset;
                const z = centerZ;
                if (Math.abs(offset) === 2) {
                  const block = dimension.getBlock({ x, y: railY, z });
                  if (
                    block &&
                    (block.isAir ||
                      block.typeId === "pb_gat:bridge_block" ||
                      block.typeId === "pb_gat:bridge_block_life" ||
                      block.typeId === "pb_gat:ember_bridge_block" ||
                      block.typeId === "pb_gat:ember_bridge_block_life")
                  ) {
                    player.playSound("step.stone", {
                      pitch: 1,
                      volume: 0.7,
                      location: block.location,
                    });
                    block.setType(blockType);
                  }
                }
              }
            }
          }
        }
      }, step * speed);
    }
  });
}
