// Constants - Thanks to liopyu
const spawnHeightmapTypeIndex = 3;
const heightmapTypeOptions = [
  //DO NOT CHANGE
  "motion_blocking_no_leaves", //0
  "ocean_floor", //1
  "motion_blocking", //2
  "world_surface", //3
  "world_surface_wg", //4
  "ocean_floor_wg", //5
];
const spawnHeightmapType = heightmapTypeOptions[spawnHeightmapTypeIndex];

function teleportToDimension(player, dimension) {
  let level = Utils.server.getLevel(dimension);
  let chunk = level.getChunk(player.x, player.z);

  Utils.server.runCommandSilent(
    `execute in ${dimension} run forceload add ${chunk.pos.x} ${chunk.pos.z}`
  );

  Utils.server.scheduleInTicks(1, (callback) => {
    const spawnY = level.getHeight(spawnHeightmapType, player.x, player.z);

    Utils.server.runCommandSilent(
      `execute as ${player.username} in ${dimension} run tp ${player.x} ${spawnY} ${player.z}`
    );
    Utils.server.runCommandSilent(
      `execute in ${dimension} run forceload remove ${chunk.pos.x} ${chunk.pos.z}`
    );
  });
}
