import { world, system, EquipmentSlot } from "@minecraft/server";
import * as utils from "../utils";

export async function onItemUse(event) {
  const player = event.source;
  const item = event.itemStack;

  if (item && item.typeId === "pu_sg:pirate_compass") {
    if (!player.getDynamicProperty("pu_sg_pirate_compass")) {
      const playerLocation = player.location;
      const dimension = player.dimension;
      dimension.playSound("pu_sg:pirate_compass_use", playerLocation);
      // Generate random distance (250 to 500) and angle
      const distance = Math.floor(Math.random() * 251) + 250; // Random number between 250 and 500
      const angle = Math.random() * 2 * Math.PI; // Random angle in radians

      // Calculate target coordinates
      const offsetX = Math.floor(distance * Math.cos(angle));
      const offsetZ = Math.floor(distance * Math.sin(angle));
      const targetX = Math.floor(playerLocation.x) + offsetX;
      const targetZ = Math.floor(playerLocation.z) + offsetZ;

      // Start at the player's Y-coordinate
      let targetY = Math.floor(playerLocation.y);

      let block = dimension.getBlock({ x: targetX, y: targetY, z: targetZ });

      // Failsafe: Search for a valid block above ground level
      while ((!block || block.isAir()) && targetY >= -40) {
        targetY--; // Move down until hitting a solid block or reaching -63
        block = dimension.getBlock({ x: targetX, y: targetY, z: targetZ });
      }

      // If no valid block is found, adjust to minimum Y-coordinate
      if (targetY < -40) {
        targetY = -40; // Set to lowest valid level
      }

      // Add an offset (4-8 blocks) for placement
      targetY += 4 + Math.floor(Math.random() * 5);

      // Use the structure command to place the structure at the validated location
      utils.runPlayerCommand(
        player,
        `structure load pu_sg:pirate_chest ${targetX} ${targetY} ${targetZ}`
      );

      // Store the location and prevent re-use
      player.setDynamicProperty(
        "pu_sg_pirate_compass_coordinates",
        `X: ${targetX}, Y: ${targetY}, Z: ${targetZ}`
      );
      player.setDynamicProperty("pu_sg_pirate_compass", true);
      utils.runPlayerCommand(player, `tellraw @s {\"rawtext\":[{\"translate\":\"pu_sg_treasure_coordinates.text\"}]}`);
      system.runTimeout(() => {
        player.sendMessage( `X: ${targetX}, Y: ${targetY}, Z: ${targetZ}`);
      },1)
    } else {
      utils.runPlayerCommand(player, "tellraw @s {\"rawtext\":[{\"translate\":\"pu_sg_compass_in_use.text\"}]}");
    }
  }
}



export async function onTick() {
  try {
    for (const player of world.getPlayers()) {
      const equippable = player.getComponent('equippable');
      if (equippable) {
        const mainhand = equippable.getEquipment(EquipmentSlot.Mainhand);
        if (mainhand && mainhand.typeId === "pu_sg:pirate_compass") {
          if (player.getDynamicProperty("pu_sg_pirate_compass")) {
            const coordinates = player.getDynamicProperty("pu_sg_pirate_compass_coordinates");

            // Display the treasure coordinates in the action bar
            utils.runPlayerCommand(player, `title @s actionbar ${coordinates}`);
          }
        }
      }

      if (player.getDynamicProperty("pu_sg_pirate_compass")) {
        const coordinates = player.getDynamicProperty("pu_sg_pirate_compass_coordinates");
        const treasureLocation = {
          x: Number(coordinates.split(",")[0].split(":")[1]),
          y: Number(coordinates.split(",")[1].split(":")[1]),
          z: Number(coordinates.split(",")[2].split(":")[1])
        };
        const playerLocation = player.location;

        // Calculate distance to the treasure
        const distance = Math.sqrt(
          Math.pow(playerLocation.x - treasureLocation.x, 2) +
          Math.pow(playerLocation.y - treasureLocation.y, 2) +
          Math.pow(playerLocation.z - treasureLocation.z, 2)
        );
        // Check if the player is within 2 blocks of the treasure
        if (distance <= 3) {
          utils.runPlayerCommand(player, `titleraw @s actionbar {\"rawtext\":[{\"translate\":\"pu_sg_treasure_found.text\"}]}`);
          player.setDynamicProperty("pu_sg_pirate_compass", false);
        }
      }
    }
  } catch (e) {
    console.warn(e);
  }
}
