Amartya
📎 1 file 21,059 chars
📄
pasted-code-1794553182314.txt
txt 942 lines
▶
# DAVILxRTP
## Advanced Random Teleport GUI Plugin for Minecraft

Develop a professional, lightweight, fully functional Minecraft Random Teleport plugin named **DAVILxRTP**.

The plugin must provide a beautiful Minecraft-native GUI interface with fully customizable elements, multiple world teleportation options, safe random location detection, previous location support, and an advanced teleport countdown system.

---

# 1. PROJECT REQUIREMENTS

**Plugin Name:** DAVILxRTP

**Target Platform:** Paper / Spigot-compatible server

**Target Minecraft Version:** 1.21.11

**Java Version:** Java 21

**Plugin Type:** Server-side Minecraft Java Plugin ONLY.

### IMPORTANT DEVELOPMENT RULES

- Create a genuine Minecraft server plugin.
- Do NOT create a Fabric mod.
- Do NOT create a Forge mod.
- Do NOT create a client-side mod.
- Do NOT require a resource pack.
- Do NOT require any client-side modifications.
- The plugin must work directly on a Paper 1.21.11 server.
- All features must be fully functional.
- Do not deliver placeholder code or incomplete implementations.

# 2. MAIN COMMAND

Implement the following command:

`/rtp`

When a player executes `/rtp`, open the custom DAVILxRTP interface.

The interface must behave like a Minecraft ESC / Pause Menu-style interface rather than a traditional chest inventory GUI.

The interface should display a centered menu over the player's current Minecraft gameplay.

# 3. GUI DESIGN – MAIN INTERFACE

The GUI is the most important part of this plugin.

I want a professional Minecraft-native menu interface that feels like an actual Minecraft game menu.

Do NOT create:
- Traditional chest inventory GUI.
- Oversized inventory menus.
- Simple chat-based menus.
- Unorganized button layouts.

Instead, create a clean, centered, modal-style interface.

## 3.1 Background

When `/rtp` is executed:

- Display a menu overlay over the current Minecraft gameplay.
- Keep the existing game environment behind the menu.
- Apply a darkened background effect.
- Use a subtle blur if supported by the selected interface API.
- Keep the background visually clean.
- Make the interface feel like a native Minecraft pause/menu screen.

## 3.2 Main Layout

The interface must contain four main sections:

1. Header section.
2. Information section.
3. World selection buttons.
4. Close button.

All content must be properly centered.

Requirements:

- Consistent spacing between elements.
- Equal button widths.
- Balanced vertical alignment.
- Proper icon and text alignment.
- Responsive layout for different screen resolutions and GUI scales.
- No overlapping elements.
- No buttons positioned too low or too high.

## 3.3 Header Section

Display:

`RTP · Random Teleport`

Default styling:
- RTP: Orange/Gold.
- Separator: Gray.
- Random Teleport: White/Light Gray.

Add a warning icon on the right side.

The warning icon and all header text must be configurable.

## 3.4 Information Section

Display three information lines.

**Line 1:**

`A random safe spot in any world`

**Line 2:**

`200–5,000 blocks`

**Line 3:**

`Ready`

Default formatting:
- Random: Gold.
- Safe: Green.
- Distance: Gold.
- Ready: Green.

Each information line must support configurable text, icon, color, visibility, and formatting.

Information must update dynamically according to the player's RTP status.

# 4. WORLD SELECTION BUTTONS

Create four large horizontal buttons.

All buttons must have:
- Equal width.
- Consistent height.
- Proper spacing.
- Centered alignment.
- An icon beside the text.
- Minecraft-style appearance.
- Hover and disabled states where supported.

## 4.1 OVERWORLD BUTTON

Default settings:

- Material: `GRASS_BLOCK`
- Text: `Overworld`
- Color: Green
- Order: 1

Action:

Teleport the player to a random safe location in the configured Overworld.

## 4.2 NETHER BUTTON

Default settings:

- Material: `NETHERRACK`
- Text: `Nether`
- Color: Red/Orange
- Order: 2

Action:

Teleport the player to a random safe location in the configured Nether.

The system must carefully validate Nether locations and avoid lava and dangerous surroundings.

## 4.3 END BUTTON

Default settings:

- Material: `END_STONE`
- Text: `End`
- Color: Yellow/Gold
- Order: 3

Action:

Teleport the player to a random safe location in the configured End.

Prevent teleportation into the void or dangerous locations.

## 4.4 PREVIOUS SPOT BUTTON

Default settings:

- Material: `AMETHYST_BLOCK`
- Text: `Previous Spot`
- Color: Light Blue/Purple
- Order: 4

Action:

Teleport the player to their previous successful RTP location.

Requirements:
- Save the last successful RTP location.
- Store world, X, Y, Z, yaw, and pitch.
- Validate the saved location before teleporting.
- If no previous location exists, show an appropriate message.
- Disable the button when no previous location is available.
- Preserve player data after server restarts.

# 5. CLOSE BUTTON

Create a large centered button below the world selection buttons.

Default settings:

- Material: `BARRIER`
- Text: `Close`
- Color: Red.

Action:

- Close the RTP interface.
- Return the player to normal gameplay.
- Do not teleport the player.

The button must be independently configurable.

# 6. COMPLETE GUI CUSTOMIZATION THROUGH CONFIG.YML

THIS IS EXTREMELY IMPORTANT.

I want complete control over every GUI element without editing Java source code or recompiling the plugin.

Do not hardcode GUI appearance inside Java classes.

Every GUI component must have its own configuration.

## 6.1 Header Customization

Allow customization of:

- Header title.
- Subtitle.
- Text colors.
- Formatting.
- Warning icon.
- Warning tooltip.
- Header visibility.

## 6.2 Information Customization

Allow customization of:

- Each information line.
- Text.
- Text color.
- Icon/material.
- Highlighted words.
- Formatting.
- Visibility.
- Display order.

## 6.3 Button Customization

Every button must have independent settings.

Allow customization of:

- Button material/icon.
- Button name.
- Text color.
- Tooltip.
- Enabled/disabled state.
- Button order.
- Button visibility.
- Permission requirement.
- Sound.
- Click action.
- Unavailable-world message.

The administrator must be able to replace any default icon with any valid Minecraft item or block material supported by Minecraft 1.21.11.

Examples:

- GRASS_BLOCK
- DIRT
- DIAMOND_BLOCK
- EMERALD_BLOCK
- NETHERITE_BLOCK
- END_STONE
- AMETHYST_BLOCK
- DIAMOND
- EMERALD
- COMPASS
- ENDER_PEARL
- GOLD_INGOT
- REDSTONE
- BARRIER
- BEACON

Do not hardcode these materials.

Load all materials dynamically from `config.yml`.

If an invalid material is provided:
- Display a console warning.
- Use a configurable fallback material.
- Continue working without crashing.

## 6.4 Close Button Customization

Allow customization of:

- Material.
- Text.
- Text color.
- Tooltip.
- Sound.
- Visibility.

## 6.5 Layout Customization

Allow customization of supported properties:

- Button order.
- Button width.
- Button spacing.
- Header spacing.
- Information spacing.
- Close button placement.
- Overall menu width.
- Menu alignment.
- Responsive layout behaviour.

Do not add fake configuration options for properties that the selected API does not support.

## 6.6 Color Customization

Support:
- Minecraft legacy colors.
- Modern RGB/HEX colors where supported.
- Bold formatting.
- Italic formatting.
- Underlined formatting.
- Custom highlighted text.

## 6.7 Sound Customization

Allow customization of:

- Menu opening sound.
- Menu closing sound.
- Button click sound.
- Teleport starting sound.
- Teleport success sound.
- Teleport failure sound.
- Countdown sounds.

Each sound must support:
- Enable/disable.
- Sound name.
- Volume.
- Pitch.

# 7. EXAMPLE CONFIG.YML

Provide a clean, organized, fully documented configuration file.

Use a structure similar to:

```yaml
settings:
  prefix: "&6[DAVILxRTP]"

gui:
  enabled: true

  header:
    enabled: true
    title: "&6RTP &8· &fRandom Teleport"
    warning:
      enabled: true
      material: "YELLOW_STAINED_GLASS"
      tooltip: "&eRTP Information"

  information:
    enabled: true

    line-1:
      enabled: true
      icon: "PAPER"
      text: "&7A &6random &asafe &7spot in any world"

    line-2:
      enabled: true
      icon: "COMPASS"
      text: "&e200-5,000 &7blocks"

    line-3:
      enabled: true
      icon: "GLOWSTONE_DUST"
      text: "&aReady"

  buttons:
    overworld:
      enabled: true
      material: "GRASS_BLOCK"
      name: "&aOverworld"
      order: 1
      sound: "UI_BUTTON_CLICK"

    nether:
      enabled: true
      material: "NETHERRACK"
      name: "&cNether"
      order: 2
      sound: "UI_BUTTON_CLICK"

    end:
      enabled: true
      material: "END_STONE"
      name: "&eEnd"
      order: 3
      sound: "UI_BUTTON_CLICK"

    previous:
      enabled: true
      material: "AMETHYST_BLOCK"
      name: "&bPrevious Spot"
      order: 4
      sound: "UI_BUTTON_CLICK"

  close-button:
    enabled: true
    material: "BARRIER"
    name: "&cClose"
    sound: "UI_BUTTON_CLICK"

worlds:
  overworld:
    enabled: true
    world-name: "world"
    min-distance: 200
    max-distance: 5000

  nether:
    enabled: true
    world-name: "world_nether"
    min-distance: 100
    max-distance: 2000

  end:
    enabled: true
    world-name: "world_the_end"
    min-distance: 200
    max-distance: 3000

teleport:
  countdown: 5

  hud:
    enabled: true
    text: "&eTeleporting in &f{time}s..."
    success-text: "&aTeleported successfully!"

  cancel:
    on-move: true
    on-combat: true
    on-damage: true
    on-disconnect: true
    on-death: true
    on-world-change: true

    messages:
      move: "&cTeleport cancelled! You moved."
      combat: "&cTeleport cancelled! You are in combat."
      damage: "&cTeleport cancelled! You took damage."

cooldown:
  enabled: true
  duration: 300

sounds:
  enabled: true

data:
  storage: "YAML"

debug: false
```

The above configuration is a starting structure. Add all remaining configurable settings with proper documentation.

# 8. RANDOM TELEPORT ENGINE

Implement a reliable and optimized RTP engine.

When a player selects a world:

1. Validate the selected world.
2. Check world availability.
3. Check player permissions.
4. Check cooldown.
5. Generate random X and Z coordinates.
6. Find a suitable Y coordinate.
7. Validate the destination.
8. Check surrounding blocks.
9. Confirm that the destination is safe.
10. Start the teleport countdown.
11. Teleport the player after successful validation.

Never teleport players into:

- Lava.
- Fire.
- Void.
- Cactus.
- Solid blocks.
- Dangerous locations.
- Unstable locations.
- Locations without safe ground.

Require:
- Suitable solid ground.
- Enough empty space for the player.
- Safe surrounding blocks.
- Valid world height.
- Valid destination coordinates.

Use separate safety validation rules for Overworld, Nether, and End.

If no safe location is found after a configurable number of attempts, cancel the request and display an appropriate message.

# 9. DISTANCE CONFIGURATION

Default distances:

**Overworld**
- Minimum: 200 blocks.
- Maximum: 5,000 blocks.

**Nether**
- Minimum: 100 blocks.
- Maximum: 2,000 blocks.

**End**
- Minimum: 200 blocks.
- Maximum: 3,000 blocks.

Allow administrators to change each world's minimum and maximum distances independently.

Validate all configured distances.

# 10. TELEPORT COUNTDOWN HUD

This feature is extremely important.

When a player selects a world, start the configured teleport countdown.

During the countdown, display a small message:

`Teleporting in 5s...`

Then dynamically update:

- Teleporting in 4s...
- Teleporting in 3s...
- Teleporting in 2s...
- Teleporting in 1s...

## HUD POSITION

Display the message near the center of the player's HUD, just above the health and hunger bar area.

Requirements:

- Small and clean text.
- Properly centered.
- Not a huge title.
- Not a large subtitle animation.
- Readable during gameplay.
- Configurable text and color.
- Dynamically updated countdown.

Use the closest supported native Minecraft HUD messaging method.

IMPORTANT:

Standard ActionBar messaging does not provide arbitrary pixel positioning. Do not falsely claim that the message can be positioned at an exact custom coordinate using the normal API.

Use the closest supported native HUD position without requiring client-side modifications.

After successful teleportation, display:

`&aTeleported successfully!`

Remove the countdown HUD after completion or cancellation.

# 11. MOVEMENT CANCELLATION

If the player moves during the teleport countdown:

- Immediately cancel the teleport request.
- Stop the countdown.
- Remove the HUD message.
- Do not teleport the player.
- Display a configurable cancellation message.

Default:

`&cTeleport cancelled! You moved.`

IMPORTANT MOVEMENT DETECTION:

- Detect actual player position changes.
- Do not cancel due to simple camera rotation.
- Do not cancel due to looking around.
- Allow configuration of movement detection rules.
- Avoid false positives.

# 12. COMBAT CANCELLATION

Teleportation must be cancelled if the player enters combat during the countdown.

Combat detection must include:

- Player attacks another player.
- Another player attacks the RTP player.
- Player deals damage to another entity.
- Another entity damages the RTP player.

When combat is detected:

1. Immediately cancel RTP.
2. Stop the countdown.
3. Remove the HUD message.
4. Cancel the pending teleport request.
5. Display a configurable combat cancellation message.

Default:

`&cTeleport cancelled! You are in combat.`

Use appropriate Paper damage and combat events.

Provide optional compatibility with external combat-tag plugins where practical.

# 13. OTHER TELEPORT CANCELLATION CONDITIONS

Cancel pending teleportation when:

- Player disconnects.
- Player dies.
- Player changes world.
- Player starts another RTP request.
- Destination becomes unsafe.
- An administrator cancels the request.

All pending countdown tasks must be properly stopped and cleaned up.

# 14. COOLDOWN SYSTEM

Implement a configurable cooldown system.

Default cooldown: 5 minutes.

Requirements:

- Configurable cooldown duration.
- Display remaining cooldown.
- Separate cooldown settings for different worlds if configured.
- Support LuckPerms groups.
- Allow authorized players to bypass cooldown.
- Prevent cooldown exploitation.

# 15. PREVIOUS SPOT STORAGE

Save player data persistently.

Requirements:

- Store previous RTP locations.
- Store world, X, Y, Z, yaw, and pitch.
- Preserve data after server restarts.
- Validate saved locations before teleportation.
- Prevent invalid or corrupted player data from crashing the plugin.

Use efficient YAML or another suitable storage method.

# 16. PERMISSIONS

Implement the following permissions:

- `davilxrtp.use`
- `davilxrtp.overworld`
- `davilxrtp.nether`
- `davilxrtp.end`
- `davilxrtp.previous`
- `davilxrtp.bypass.cooldown`
- `davilxrtp.admin`

All permissions must work correctly with LuckPerms.

Allow individual permissions to control access to each world button.

# 17. ADMIN COMMANDS

Implement:

`/rtp`  
Open the RTP interface.

`/rtp reload`  
Reload the complete configuration.

`/rtp help`  
Display all available commands.

`/rtp test `  
Test the RTP system for a specified world.

`/rtp setspawn`  
Set an optional reference location if required by the RTP algorithm.

All admin commands must have proper permission checks.

# 18. CONFIGURATION RELOAD

The command:

`/rtp reload`

Must reload:

- GUI title.
- Subtitle.
- Icons.
- Materials.
- Button names.
- Button colors.
- Information text.
- Button order.
- World settings.
- RTP distances.
- Cooldowns.
- Countdown.
- HUD text.
- Cancellation settings.
- Sounds.
- Messages.
- Permissions where applicable.

Newly opened interfaces must immediately use the updated configuration.

Do not require a server restart for normal configuration changes.

# 19. ERROR HANDLING

Handle all possible errors:

- World does not exist.
- World is disabled.
- No safe location found.
- Player lacks permission.
- Player is on cooldown.
- Previous location does not exist.
- Player disconnects.
- Player dies.
- Player enters combat.
- Player moves.
- Teleportation fails.
- Invalid material.
- Invalid sound.
- Invalid configuration.
- Unsupported GUI property.

Display clear messages and console warnings.

Never allow an invalid configuration value to crash the plugin.

# 20. PERFORMANCE AND OPTIMIZATION

The plugin must be lightweight and optimized.

Requirements:

- Avoid unnecessary repeating tasks.
- Avoid blocking the main server thread with expensive location searches.
- Use asynchronous processing where appropriate.
- Perform Bukkit/Paper world operations safely on the server thread.
- Avoid memory leaks.
- Support multiple players teleporting simultaneously.
- Maintain separate countdown tasks per player.
- Prevent duplicate teleport requests.
- Clean up tasks after completion or cancellation.
- Avoid unnecessary database operations.

# 21. API AND GUI TECHNICAL REQUIREMENTS

Before implementing the interface, investigate the actual Paper 1.21.11 API.

Use the native Dialog API if it supports the requested interface and interaction behaviour.

However, understand that native Dialog API properties may be limited.

It may not expose:
- Arbitrary pixel positioning.
- Exact button heights.
- Custom background colors.
- Every native item-icon layout.
- Full-screen Pause Menu replacement.

Do not promise unsupported functionality.

If the requested full-screen ESC/Pause-menu-style interface cannot be recreated exactly through the available server-side API, implement the closest supported native Minecraft interface.

Do not introduce client-side mods or resource packs as a workaround.

Every configuration option must correspond to an actual implemented feature.

# 22. PROJECT STRUCTURE AND CODE QUALITY

Use a clean and professional project structure.

Separate the following systems into appropriate classes:

- Main plugin class.
- Command manager.
- GUI manager.
- GUI configuration manager.
- Button manager.
- Material manager.
- Color formatting manager.
- RTP engine.
- Safe location finder.
- Teleport manager.
- Countdown manager.
- HUD manager.
- Movement detection manager.
- Combat detection manager.
- Cooldown manager.
- Previous location manager.
- Player data manager.
- Permission manager.
- Sound manager.

Use clean Java code and proper error handling.

# 23. FINAL DELIVERABLES

Provide:

1. Complete Java source code.
2. Maven or Gradle project.
3. Correct `plugin.yml`.
4. Complete default `config.yml`.
5. README.md installation guide.
6. Compiled `DAVILxRTP.jar`.

The final JAR must be ready to install into the server's `plugins` folder.

# 24. FINAL TESTING REQUIREMENTS

Before delivery, test everything.

### GUI Tests
- `/rtp` opens the interface.
- Interface is properly centered.
- Background overlay works where supported.
- All buttons appear correctly.
- Icons load from configuration.
- Text customization works.
- Colors work.
- Button ordering works.
- Close button works.
- GUI reload works.

### RTP Tests
- Overworld RTP works.
- Nether RTP works.
- End RTP works.
- Previous Spot works.
- Safe location detection works.
- Distance restrictions work.
- Multiple simultaneous players work.

### Teleport Tests
- Countdown works.
- HUD message appears.
- HUD updates every second.
- Movement cancels RTP.
- Combat cancels RTP.
- Damage cancellation works.
- Disconnect cancellation works.
- Death cancellation works.
- No teleport happens after cancellation.

### Configuration Tests
- All GUI settings work.
- All icons can be changed.
- All button names can be changed.
- Colors can be changed.
- Sounds can be changed.
- Messages can be changed.
- `/rtp reload` works correctly.

### Compatibility Tests
- Paper 1.21.11.
- Java 21.
- LuckPerms.
- No client-side modifications.
- No unexpected console errors.
- No server crashes.

---

# FINAL INSTRUCTION TO THE DEVELOPER

Build **DAVILxRTP** as a complete, production-quality Minecraft Paper 1.21.11 plugin.

The most important priorities are:

1. A beautiful, centered, Minecraft-native ESC/Pause-menu-style RTP interface.
2. Complete GUI customization through `config.yml`.
3. Fully functional Overworld, Nether, and End random teleportation.
4. Persistent Previous Spot functionality.
5. Small Teleporting HUD message near the health and hunger bars.
6. Immediate teleport cancellation when the player moves or enters combat.
7. Reliable safe-location detection.
8. Lightweight performance and stable operation.

Do not replace the requested interface with a traditional chest inventory GUI.

Do not hardcode GUI icons, text, colors, or settings.

Do not add configuration options that do nothing.

Do not deliver placeholder buttons or incomplete functionality.

Test the complete plugin before delivery.

**FINAL OUTPUT: A working, properly compiled, fully tested `DAVILxRTP.jar` ready to install on a Paper 1.21.11 Minecraft server.**
Kodari AI
KodariNov 13 at 7:01 am 5
DavilxRTP
A Minecraft Paper plugin providing a fully customizable, GUI-based random teleport system. Features a centered, pause-menu-style interface with configurable header, information lines, and world selection buttons for Overworld, Nether, End, and Previous Spot. Includes safe location detection, teleport countdown with HUD messages, movement and combat cancellation, persistent player data storage, cooldown system, and complete config.yml customization for all GUI elements, sounds, and messages.

Created the DAVILxRTP source project with a native Paper dialog, random teleport searches, countdown cancellation, cooldowns, and persistent previous locations.

Paper dialogs cannot provide item icons on buttons, exact pause-menu positioning, or true disabled buttons. The plugin therefore requires Paper 1.21.11, not Spigot.

The project has not been compiled or tested in a server, so a working JAR cannot yet be guaranteed. To build it in Kodari:

  1. Click Compile in the top bar, or on mobile tap ⋮ → Compile Project.

  2. Click Compile, then Download if the build succeeds.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
README.md
settings.gradle
Code
8 663
src/main/java/com/davilxrtp/DavilRtp.java
package com.davilxrtp;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.util.List;

public final class DavilRtp extends JavaPlugin {
    private static final LegacyComponentSerializer COLORS = LegacyComponentSerializer.builder().character('&').hexColors().build();
    private File dataFile;
    private YamlConfiguration data;
    private TeleportManager teleports;
    private DialogMenu menu;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        dataFile = new File(getDataFolder(), "data.yml");
        data = YamlConfiguration.loadConfiguration(dataFile);
        teleports = new TeleportManager(this);
        menu = new DialogMenu(this, teleports);
        getServer().getPluginManager().registerEvents(teleports, this);
    }

    @Override
    public void onDisable() {
        if (teleports != null) teleports.shutdown();
        if (data != null) saveData();
    }

    public Component color(String text) {
        return COLORS.deserialize(text == null ? "" : text);
    }

    public void message(CommandSender sender, String key) {
        sender.sendMessage(color(getConfig().getString("settings.prefix", "") + getConfig().getString("messages." + key, key)));
    }

    public void sound(Player player, String key) {
        String path = "sounds." + key;
        if (!getConfig().getBoolean("sounds.enabled", true) || !getConfig().getBoolean(path + ".enabled", false)) return;
        String name = getConfig().getString(path + ".name", "");
        if (!name.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) {
            getLogger().warning("Invalid sound key at " + path + ": " + name);
            return;
        }
        float volume = (float) Math.max(0, getConfig().getDouble(path + ".volume", 1));
        float pitch = (float) Math.max(0.01, Math.min(2, getConfig().getDouble(path + ".pitch", 1)));
        player.playSound(player.getLocation(), name, volume, pitch);
    }

    public YamlConfiguration data() { return data; }

    public void saveData() {
        try {
            data.save(dataFile);
        } catch (IOException e) {
            getLogger().severe("Could not save data.yml: " + e.getMessage());
        }
    }

    public Location readLocation(String path) {
        ConfigurationSection section = data.getConfigurationSection(path);
        if (section == null) return null;
        String worldName = section.getString("world");
        if (worldName == null || Bukkit.getWorld(worldName) == null || !section.isDouble("x") || !section.isDouble("y") || !section.isDouble("z")) return null;
        double x = section.getDouble("x"), y = section.getDouble("y"), z = section.getDouble("z");
        float yaw = (float) section.getDouble("yaw"), pitch = (float) section.getDouble("pitch");
        if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z) || !Float.isFinite(yaw) || !Float.isFinite(pitch)) return null;
        return new Location(Bukkit.getWorld(worldName), x, y, z, yaw, pitch);
    }

    public void writeLocation(String path, Location location) {
        data.set(path + ".world", location.getWorld().getName());
        data.set(path + ".x", location.getX());
        data.set(path + ".y", location.getY());
        data.set(path + ".z", location.getZ());
        data.set(path + ".yaw", (double) location.getYaw());
        data.set(path + ".pitch", (double) location.getPitch());
        saveData();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (args.length == 0) {
            if (!(sender instanceof Player player)) { sender.sendMessage("Players only."); return true; }
            if (!player.hasPermission("davilxrtp.use")) { message(sender, "no-permission"); return true; }
            if (!getConfig().getBoolean("gui.enabled", true)) { message(sender, "unavailable"); return true; }
            menu.open(player);
            return true;
        }
        String action = args[0].toLowerCase(java.util.Locale.ROOT);
        if (action.equals("help")) {
            sender.sendMessage(color("&6/rtp &7- Open the RTP menu"));
            if (sender.hasPermission("davilxrtp.admin")) sender.sendMessage(color("&6/rtp reload | test <world> | setspawn | cancel [player]"));
            return true;
        }
        if (!sender.hasPermission("davilxrtp.admin")) { message(sender, "no-permission"); return true; }
        switch (action) {
            case "reload" -> { reloadConfig(); message(sender, "reloaded"); }
            case "setspawn" -> {
                if (!(sender instanceof Player p)) { sender.sendMessage("Players only."); break; }
                writeLocation("spawns." + p.getWorld().getName(), p.getLocation());
                sender.sendMessage(color("&aRTP reference location saved for this world."));
            }
            case "test" -> {
                if (!(sender instanceof Player p)) { sender.sendMessage("Players only."); break; }
                if (args.length != 2 || !List.of("overworld", "nether", "end").contains(args[1].toLowerCase(java.util.Locale.ROOT))) {
                    sender.sendMessage("Usage: /rtp test <overworld|nether|end>"); break;
                }
                teleports.request(p, args[1].toLowerCase(java.util.Locale.ROOT));
            }
            case "cancel" -> {
                Player target = args.length > 1 ? Bukkit.getPlayerExact(args[1]) : sender instanceof Player p ? p : null;
                if (target == null) { sender.sendMessage("Player not found."); break; }
                teleports.cancel(target, "cancelled");
                if (!target.equals(sender)) sender.sendMessage("RTP request cancelled if pending.");
            }
            default -> sender.sendMessage("Usage: /rtp [help|reload|test|setspawn|cancel]");
        }
        return true;
    }
}