const targetY = 256
// List to store claimed chunk coordinates
let claimedChunks = new Set();

// The command to teleport and claim
ServerEvents.commandRegistry(event => {
  const { commands: Commands } = event;
  event.register(
      Commands.literal('mychunk')
        //.setDescription('Random Teleport to an unclaimed chunk and claim it.')
        //.requires(source => source.hasPermissionLevel(2)) // Requires OP or specific permission
        .executes((context) => {
            const player = context.getSource().getPlayer();
            //const world = player.getWorld();
            let randomChunk;

            let playerHomeChunkX = player.persistentData.chunkX
            let playerHomeChunkZ = player.persistentData.chunkZ

            if (playerHomeChunkX != undefined) {
                player.tell(`У вас уже есть стартовый чанк! Вы были телепортированы к нему`)
                player.setPosition(playerHomeChunkX, targetY, playerHomeChunkZ);
                return 0;
            }

            // Attempt to find an unclaimed chunk
            for (let i = 0; i < 100; i++) { // max attempts to find an unclaimed chunk
                randomChunk = getRandomChunk();
                let chunkKey = `${randomChunk.x},${randomChunk.z}`;

                try {
                  if (!stringToSet(player.server.persistentData.claimedChunks).has(chunkKey)) {
                    claimedChunks.add(chunkKey); // Mark the chunk as claimed
                    player.server.persistentData.claimedChunks = setToString(claimedChunks)
                    break; // Found an unclaimed chunk
                  }
                } catch (e) {
                  claimedChunks.add(chunkKey); // Mark the chunk as claimed
                  player.server.persistentData.claimedChunks = setToString(claimedChunks)
                  break; // Found an unclaimed chunk
                }
                
                randomChunk = null; // Reset if claimed
            }

            if (randomChunk) {
                // Teleport the player to the random chunk location
                player.server.runCommand(`/effect give ${player.profile.name} tombstone:feather_fall 30 255`);
                player.server.runCommand(`/effect give ${player.profile.name} minecraft:resistance 25 255`);
                player.setPosition(randomChunk.x + 8, targetY, randomChunk.z + 8); // Center in the chunk
                player.persistentData.chunkX = randomChunk.x + 8
                player.persistentData.chunkZ = randomChunk.z + 8
                player.server.runCommand(`/chunkbychunk:spawnthemedchunk forest ${player.x} ${player.y} ${player.z}`);
                player.server.runCommand(`/chunkbychunk:spawnThemedChunk forest ${player.x} ${player.y} ${player.z}`);
                player.runCommand(`/ftbchunks claim`); // Claim the chunk
                // Use the /ftb claim command
                
                player.tell(`Вы были телепортированы на случайный чанк координатой ${randomChunk.x}, ${randomChunk.z}, он теперь ваш!`);
                player.tell(`Для телепорта в свой чанк, снова используйте команду /mychunk`);
              } else {
                player.tell(`Не получилось найти свободный чанк после нескольких попыток.`);
            }

            return 1;
        })
      );
});



// Function to generate a random chunk
function getRandomChunk() {
  const chunkX = Math.floor(Math.random() * 1000) * 16; // Customize the range as needed
  const chunkZ = Math.floor(Math.random() * 1000) * 16; // Customize the range as needed
  return { x: chunkX, z: chunkZ };
}

// Function to convert a Set to a string
function setToString(set) {
  return Array.from(set).join(',');
}

// Function to convert a string back to a Set
function stringToSet(str) {
  return new Set(str.split(','));
}