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

export function recallHome(player, item) {
  system.runTimeout(() => {
    player.playSound("mob.phantom.flap", {
      pitch: 1.4,
      volume: 1,
      location: player.location,
    });
    system.runTimeout(() => {
      player.playSound("mob.phantom.flap", {
        pitch: 1.6,
        volume: 1,
        location: player.location,
      });
    }, 5);
  }, 10);
  const contents = item
    ? new ItemInventoryContents(item).getContainer()?.content ?? []
    : [];

  const hasReach = contents.some(
    (stack) => stack?.typeId === "pb_gat:orb_reach"
  );
  const maxDistance = hasReach ? 1000 : 500;

  let spawnPoint;
  try {
    spawnPoint = player.getSpawnPoint();
  } catch (e) {}

  if (
    spawnPoint &&
    typeof spawnPoint === "object" &&
    "x" in spawnPoint &&
    "y" in spawnPoint &&
    "z" in spawnPoint &&
    spawnPoint.dimension &&
    typeof spawnPoint.dimension === "object" &&
    "id" in spawnPoint.dimension
  ) {
    const dimension = world.getDimension(spawnPoint.dimension.id);

    const homeLocation = {
      x: spawnPoint.x + 0.5,
      y:
        spawnPoint.y > -64 && spawnPoint.y < 32000
          ? spawnPoint.y
          : getSurfaceY(dimension, spawnPoint.x, spawnPoint.z),
      z: spawnPoint.z + 0.5,
    };
    const dx = homeLocation.x - player.location.x;
    const dz = homeLocation.z - player.location.z;
    const distSq = dx * dx + dz * dz;

    if (distSq > maxDistance * maxDistance) {
      player.sendMessage(
        `§4->§r Too far from home (limit ${maxDistance} blocks).`
      );
      return;
    }

    try {
      player.teleport(homeLocation, { dimension });
      player.sendMessage(`§a->§r You have returned home.`);
      system.runTimeout(() => {
        player.dimension.spawnParticle("pb_gat:pearl_teleport", homeLocation);
        player.playSound("mob.shulker.teleport", {
          pitch: 1,
          volume: 1,
          location: player.location,
        });
      }, 5);
    } catch {}
  } else {
    // fallback to world spawn location
    const fallback = world.getDefaultSpawnLocation();
    const surfaceY = getSurfaceY(player.dimension, fallback.x, fallback.z);

    const homeLocation = {
      x: fallback.x + 0.5,
      y: surfaceY,
      z: fallback.z + 0.5,
    };

    const dx = homeLocation.x - player.location.x;
    const dz = homeLocation.z - player.location.z;
    const distSq = dx * dx + dz * dz;

    if (distSq > maxDistance * maxDistance) {
      player.sendMessage(
        `§4->§r Too far from home (limit ${maxDistance} blocks).`
      );
      return;
    }

    try {
      player.teleport(homeLocation);
      player.sendMessage(`§a->§r You have returned to world spawn.`);
      system.runTimeout(() => {
        player.dimension.spawnParticle("pb_gat:pearl_teleport", homeLocation);
        player.playSound("mob.shulker.teleport", {
          pitch: 1,
          volume: 1,
          location: player.location,
        });
      }, 5);
    } catch {}
  }
}

function getSurfaceY(dimension, x, z) {
  for (let y = 320; y >= -64; y--) {
    const block = dimension.getBlock({ x, y, z });
    if (block && !block.isAir) return y + 1;
  }
  return 64;
}
