galaxy.linux

Create a complete Minecraft Paper plugin called "SpawnHUD" for Paper 1.21.11 (Java 21, Maven, paper-api 1.21.11-R0.1-SNAPSHOT). Give me every file in full: pom.xml, plugin.yml, config.yml, and the Java source. Also give short build steps (mvn clean package) and where to put the jar.

COMMANDS AND PERMISSIONS

  • /spawn: teleports the player to spawn after a countdown.
  • /setspawn (permission spawnhud.set): saves the player's current location, including yaw and pitch, to config.yml.
  • /spawnreload (permission spawnhud.reload): reloads config.yml.
  • Permission spawnhud.bypass: teleports instantly with no countdown, and sends the "teleport-direct" message.
  • If the sender is not a player, send the "only-player" message.
  • If the player lacks permission, send the "no-permission" message and play its sound.
  • If no spawn is set, send "spawn-location-not-set".

COUNTDOWN BEHAVIOR

  • The delay is teleport-delay seconds (default 5), run with a BukkitRunnable once per second.
  • Each second, show the "teleport-countdown" message (with %countdown% replaced) in the ACTION BAR, so it appears as small HUD text above the hotbar and not in chat.
  • If hud.subtitle is true, also show a subtitle-only title: an empty title and the countdown number as the subtitle, with short fade times.
  • Play the "teleport-countdown" sound each second. If rising-pitch is true, raise the pitch a little each second.
  • If the player moves to a different block (check in PlayerMoveEvent, ignoring head rotation only), cancel the countdown. Show "teleport-cancelled" in the action bar and play its sound.
  • Cancel the task if the player quits or starts /spawn again while a countdown is running.
  • When the countdown ends, teleport the player, show "teleport-success" in the action bar, and play its sound.
  • Keep a Map<UUID, BukkitTask> and clean it up properly.

TEXT FORMAT

  • Use Adventure MiniMessage for all messages. Colors and gradients live in config.yml, for example <gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient>, <#55FF88>, and <bold>.
  • Use the Unicode small-caps text exactly as written in the config below.
  • Send messages with player.sendActionBar(Component) and player.showTitle(...). Do not use legacy § codes.

SOUNDS (important, they must work on 1.21.11)

  • Do not use the Sound enum or old names like BLOCK_NOTE_BLOCK_PLING.
  • Use the string-key method: player.playSound(player.getLocation(), "minecraft:block.note_block.pling", SoundCategory.MASTER, volume, pitch).
  • Read sound, volume, and pitch from config.yml under sounds.<name>. Add the "minecraft:" prefix automatically if it's missing. Catch invalid names and log a warning once.
  • Respect sounds.enabled.

CONFIG.YML (use these defaults) spawn: world: world, x: -362.47045508629077, y: 102.0, z: -635.5247924339028, yaw: -177.30249, pitch: 0.14998226 teleport-delay: 5 hud: actionbar: true, subtitle: true, chat-for-errors: true messages (MiniMessage): only-player: "<#FF5555>✘ <dark_gray>┃ <gray>ᴏɴʟʏ ᴘʟᴀʏᴇʀs ᴄᴀɴ ᴜsᴇ ᴛʜɪs ᴄᴏᴍᴍᴀɴᴅ" spawn-location-not-set: "<#FF5555>✘ <dark_gray>┃ <gray>ꜱᴘᴀᴡɴ ʟᴏᴄᴀᴛɪᴏɴ ɪs ɴᴏᴛ sᴇᴛ ʏᴇᴛ" set-spawn-success: "<#55FF88>✔ <dark_gray>┃ <gray>ꜱᴘᴀᴡɴ ʟᴏᴄᴀᴛɪᴏɴ sᴀᴠᴇᴅ <#FFD700>✦" no-permission: "<#FF5555>✘ <dark_gray>┃ <gray>ʏᴏᴜ ᴅᴏɴ'ᴛ ʜᴀᴠᴇ ᴘᴇʀᴍɪssɪᴏɴ" reload-config-success: "<#55FF88>✔ <dark_gray>┃ <gray>ᴄᴏɴꜰɪɢ ʀᴇʟᴏᴀᴅᴇᴅ <#FFD700>✦" teleport-countdown: "<bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold> <dark_gray>┃ <gray>ᴛᴇʟᴇᴘᴏʀᴛɪɴɢ ɪɴ <#FFD700>%countdown%ꜱ <dark_gray>• <gray>ᴅᴏɴ'ᴛ ᴍᴏᴠᴇ" teleport-cancelled: "<#FF5555>✘ <#FF8888>ᴄᴀɴᴄᴇʟʟᴇᴅ <dark_gray>┃ <gray>ʏᴏᴜ ᴍᴏᴠᴇᴅ" teleport-success: "<#55FF88>✔ <white>ᴡᴇʟᴄᴏᴍᴇ ᴛᴏ <bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold> <#FFD700>✦" teleport-direct: "<#55FF88>✔ <dark_gray>┃ <gray>ᴛᴇʟᴇᴘᴏʀᴛᴇᴅ ᴛᴏ <bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold>" sounds: enabled: true, each with sound, volume, pitch: teleport-countdown: block.note_block.chime, 0.8, 1.0, rising-pitch: true teleport-success: entity.player.levelup, 0.9, 1.3 teleport-cancelled: block.note_block.bass, 0.9, 0.7 set-spawn-success: block.amethyst_block.chime, 1.0, 1.4 no-permission: entity.villager.no, 0.8, 1.0 reload-config-success: block.note_block.bell, 1.0, 1.5

CODE QUALITY

  • Use only the Paper API, with no external dependencies. Do not use deprecated methods.
  • Add short comments, handle null worlds safely, and make sure the plugin compiles without errors.
Kodari AI
KodariNov 7 at 7:07 am 3
SpawnHUD
A Paper plugin providing a HUD-based spawn teleportation system with countdown. Players use /spawn to teleport after a configurable delay, with action bar countdown messages and optional subtitles. Includes /setspawn and /spawnreload commands with permission checks. Features movement cancellation, rising pitch sounds, MiniMessage formatting with gradients and small-caps text, configurable sounds with string-key sound names, and proper task management. Uses Adventure API for modern text components and supports bypass permission for instant teleportation.
  • Create the Paper plugin, Maven configuration, and requested defaults.

  • Handle countdowns, movement cancellation, MiniMessage HUD output, and configurable sounds.

Created SpawnHUD with the requested configuration, commands, countdown HUD, and sounds.

Build and install: Click Compile in Kodari’s top bar, then Compile in the window. Download the resulting JAR and place it in your Paper server’s plugins folder.

Sound keys are checked for valid syntax; the string-based sound API cannot confirm whether a syntactically valid sound exists.

galaxy.linux

Update my existing SpawnHUD Paper 1.21.11 plugin (the code you wrote earlier). Add a /spawn COOLDOWN of 3 seconds. Give me the full updated files that changed (Java source and config.yml), not just snippets.

COOLDOWN BEHAVIOR

  • After a player runs /spawn, they cannot run it again for 3 seconds.
  • Start the cooldown when the player runs /spawn, so it also applies if the countdown is cancelled by moving.
  • If the player runs /spawn during the cooldown, do not start a countdown. Show the "cooldown-active" message in the ACTION BAR with the remaining time (replace %time% with the seconds left, rounded up), and play the "cooldown-active" sound.
  • Players with the permission spawnhud.bypass skip the cooldown.
  • Store cooldowns in a Map<UUID, Long> using System.currentTimeMillis(). Remove the entry when the player quits (PlayerQuitEvent) so the map doesn't leak memory.
  • Read the cooldown length from config.yml as "cooldown: 3" (in seconds). It must work after /spawnreload.
  • Cooldown value 0 disables the cooldown.

ADD TO CONFIG.YML cooldown: 3

messages: cooldown-active: "<#FF5555>✘ <dark_gray>┃ <gray>ᴡᴀɪᴛ <#FFD700>%time%ꜱ <gray>ʙᴇꜰᴏʀᴇ ᴜsɪɴɢ <bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold> <gray>ᴀɢᴀɪɴ"

sounds: cooldown-active: sound: "block.note_block.bass" volume: 0.8 pitch: 0.8

RULES

  • Keep everything else working exactly as before: action bar countdown, subtitle, sounds using string keys like "minecraft:block.note_block.bass" with SoundCategory.MASTER, MiniMessage text, and move-cancel.
  • Use only the Paper API, no deprecated methods, and make sure it compiles.
  • Tell me which files changed and where each change goes.
Kodari AI
KodariNov 7 at 8:02 am 2
  • Track /spawn use per player and check the current configured cooldown.

  • Add the cooldown message and sound, and clear player entries on quit.

Updated src/main/java/com/kodari/spawnhud/SpawnHUD.java and src/main/resources/config.yml.

src/main/java/com/kodari/spawnhud/SpawnHUD.java

Java
package com.kodari.spawnhud;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.SoundCategory;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public final class SpawnHUD extends JavaPlugin implements Listener {
    private final MiniMessage miniMessage = MiniMessage.miniMessage();
    private final Map<UUID, BukkitTask> countdowns = new HashMap<>();
    private final Map<UUID, Long> cooldowns = new HashMap<>();
    private final Set<String> warnedSounds = new HashSet<>();

    @Override
    public void onEnable() {
        saveDefaultConfig();
        getServer().getPluginManager().registerEvents(this, this);
    }

    @Override
    public void onDisable() {
        countdowns.values().forEach(BukkitTask::cancel);
        countdowns.clear();
        cooldowns.clear();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player player)) {
            sender.sendMessage(message("only-player", null));
            return true;
        }
        switch (command.getName().toLowerCase(java.util.Locale.ROOT)) {
            case "setspawn" -> {
                if (!checkPermission(player, "spawnhud.set")) return true;
                Location location = player.getLocation();
                getConfig().set("spawn.world", location.getWorld().getName());
                getConfig().set("spawn.x", location.getX());
                getConfig().set("spawn.y", location.getY());
                getConfig().set("spawn.z", location.getZ());
                getConfig().set("spawn.yaw", location.getYaw());
                getConfig().set("spawn.pitch", location.getPitch());
                saveConfig();
                player.sendMessage(message("set-spawn-success", null));
                playSound(player, "set-spawn-success", 0);
            }
            case "spawnreload" -> {
                if (!checkPermission(player, "spawnhud.reload")) return true;
                reloadConfig();
                player.sendMessage(message("reload-config-success", null));
                playSound(player, "reload-config-success", 0);
            }
            case "spawn" -> startTeleport(player);
            default -> { return false; }
        }
        return true;
    }

    private boolean checkPermission(Player player, String permission) {
        if (player.hasPermission(permission)) return true;
        error(player, "no-permission");
        playSound(player, "no-permission", 0);
        return false;
    }

    private void startTeleport(Player player) {
        UUID playerId = player.getUniqueId();
        if (!player.hasPermission("spawnhud.bypass")) {
            long now = System.currentTimeMillis();
            long cooldownMillis = Math.max(0L, (long) getConfig().getInt("cooldown", 3)) * 1000L;
            Long lastUse = cooldowns.get(playerId);
            if (cooldownMillis > 0 && lastUse != null) {
                long remaining = cooldownMillis - (now - lastUse);
                if (remaining > 0) {
                    String text = getConfig().getString("messages.cooldown-active", "")
                            .replace("%time%", Long.toString((remaining + 999L) / 1000L));
                    player.sendActionBar(miniMessage.deserialize(text));
                    playSound(player, "cooldown-active", 0);
                    return;
                }
            }
            if (cooldownMillis > 0) cooldowns.put(playerId, now);
            else cooldowns.remove(playerId);
        }
        cancelCountdown(player.getUniqueId());
        if (spawnLocation() == null) {
            error(player, "spawn-location-not-set");
            return;
        }
        int delay = Math.max(0, getConfig().getInt("teleport-delay", 5));
        if (player.hasPermission("spawnhud.bypass")) {
            teleport(player, "teleport-direct");
            return;
        }
        if (delay == 0) {
            teleport(player, "teleport-success");
            return;
        }

        BukkitRunnable runnable = new BukkitRunnable() {
            private int remaining = delay;

            @Override
            public void run() {
                if (!player.isOnline()) {
                    cancelCountdown(player.getUniqueId());
                    return;
                }
                if (remaining == 0) {
                    // Remove the task before teleporting so the move event cannot cancel it.
                    cancelCountdown(player.getUniqueId());
                    teleport(player, "teleport-success");
                    return;
                }
                hud(player, "teleport-countdown", Integer.toString(remaining));
                if (getConfig().getBoolean("hud.subtitle", true)) {
                    player.showTitle(Title.title(Component.empty(), Component.text(remaining),
                            Title.Times.times(Duration.ofMillis(100), Duration.ofMillis(800), Duration.ofMillis(100))));
                }
                playSound(player, "teleport-countdown", delay - remaining);
                remaining--;
            }
        };
        BukkitTask task = runnable.runTaskTimer(this, 0L, 20L);
        countdowns.put(player.getUniqueId(), task);
    }

    private void teleport(Player player, String messageKey) {
        Location destination = spawnLocation();
        if (destination == null) {
            error(player, "spawn-location-not-set");
            return;
        }
        if (player.teleport(destination)) {
            hud(player, messageKey, null);
            playSound(player, "teleport-success", 0);
        }
    }

    private Location spawnLocation() {
        ConfigurationSection section = getConfig().getConfigurationSection("spawn");
        if (section == null || !section.isString("world") || !section.isSet("x")
                || !section.isSet("y") || !section.isSet("z")) return null;
        World world = Bukkit.getWorld(section.getString("world", ""));
        if (world == null) return null;
        return new Location(world, section.getDouble("x"), section.getDouble("y"), section.getDouble("z"),
                (float) section.getDouble("yaw"), (float) section.getDouble("pitch"));
    }

    private Component message(String key, String countdown) {
        String text = getConfig().getString("messages." + key, "");
        if (countdown != null) text = text.replace("%countdown%", countdown);
        return miniMessage.deserialize(text);
    }

    private void hud(Player player, String key, String countdown) {
        if (getConfig().getBoolean("hud.actionbar", true)) player.sendActionBar(message(key, countdown));
    }

    private void error(Player player, String key) {
        if (getConfig().getBoolean("hud.chat-for-errors", true)) player.sendMessage(message(key, null));
        else hud(player, key, null);
    }

    private void playSound(Player player, String name, int elapsed) {
        if (!getConfig().getBoolean("sounds.enabled", true)) return;
        String path = "sounds." + name + ".";
        String sound = getConfig().getString(path + "sound", "");
        if (!sound.contains(":")) sound = "minecraft:" + sound;
        if (NamespacedKey.fromString(sound) == null) {
            if (warnedSounds.add(sound)) getLogger().warning("Invalid sound key: " + sound);
            return;
        }
        float volume = (float) getConfig().getDouble(path + "volume", 1.0);
        float pitch = (float) getConfig().getDouble(path + "pitch", 1.0);
        if (getConfig().getBoolean(path + "rising-pitch", false)) pitch += elapsed * 0.1f;
        pitch = Math.max(0.0f, Math.min(2.0f, pitch));
        try {
            player.playSound(player.getLocation(), sound, SoundCategory.MASTER, volume, pitch);
        } catch (IllegalArgumentException ex) {
            if (warnedSounds.add(sound)) getLogger().warning("Invalid sound key: " + sound);
        }
    }

    private void cancelCountdown(UUID playerId) {
        BukkitTask task = countdowns.remove(playerId);
        if (task != null) task.cancel();
    }

    @EventHandler(ignoreCancelled = true)
    public void onMove(PlayerMoveEvent event) {
        Location from = event.getFrom();
        Location to = event.getTo();
        if (to == null || (from.getWorld().equals(to.getWorld()) && from.getBlockX() == to.getBlockX()
                && from.getBlockY() == to.getBlockY() && from.getBlockZ() == to.getBlockZ())) return;
        Player player = event.getPlayer();
        if (!countdowns.containsKey(player.getUniqueId())) return;
        cancelCountdown(player.getUniqueId());
        hud(player, "teleport-cancelled", null);
        playSound(player, "teleport-cancelled", 0);
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent event) {
        cancelCountdown(event.getPlayer().getUniqueId());
        cooldowns.remove(event.getPlayer().getUniqueId());
    }
}

src/main/resources/config.yml

YAML
spawn:
  world: world
  x: -362.47045508629077
  y: 102.0
  z: -635.5247924339028
  yaw: -177.30249
  pitch: 0.14998226
teleport-delay: 5
cooldown: 3
hud:
  actionbar: true
  subtitle: true
  chat-for-errors: true
messages:
  only-player: "<#FF5555>✘ <dark_gray>┃ <gray>ᴏɴʟʏ ᴘʟᴀʏᴇʀs ᴄᴀɴ ᴜsᴇ ᴛʜɪs ᴄᴏᴍᴍᴀɴᴅ"
  spawn-location-not-set: "<#FF5555>✘ <dark_gray>┃ <gray>ꜱᴘᴀᴡɴ ʟᴏᴄᴀᴛɪᴏɴ ɪs ɴᴏᴛ sᴇᴛ ʏᴇᴛ"
  set-spawn-success: "<#55FF88>✔ <dark_gray>┃ <gray>ꜱᴘᴀᴡɴ ʟᴏᴄᴀᴛɪᴏɴ sᴀᴠᴇᴅ <#FFD700>✦"
  no-permission: "<#FF5555>✘ <dark_gray>┃ <gray>ʏᴏᴜ ᴅᴏɴ'ᴛ ʜᴀᴠᴇ ᴘᴇʀᴍɪssɪᴏɴ"
  reload-config-success: "<#55FF88>✔ <dark_gray>┃ <gray>ᴄᴏɴꜰɪɢ ʀᴇʟᴏᴀᴅᴇᴅ <#FFD700>✦"
  teleport-countdown: "<bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold> <dark_gray>┃ <gray>ᴛᴇʟᴇᴘᴏʀᴛɪɴɢ ɪɴ <#FFD700>%countdown%ꜱ <dark_gray>• <gray>ᴅᴏɴ'ᴛ ᴍᴏᴠᴇ"
  teleport-cancelled: "<#FF5555>✘ <#FF8888>ᴄᴀɴᴄᴇʟʟᴇᴅ <dark_gray>┃ <gray>ʏᴏᴜ ᴍᴏᴠᴇᴅ"
  teleport-success: "<#55FF88>✔ <white>ᴡᴇʟᴄᴏᴍᴇ ᴛᴏ <bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold> <#FFD700>✦"
  teleport-direct: "<#55FF88>✔ <dark_gray>┃ <gray>ᴛᴇʟᴇᴘᴏʀᴛᴇᴅ ᴛᴏ <bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold>"
  cooldown-active: "<#FF5555>✘ <dark_gray>┃ <gray>ᴡᴀɪᴛ <#FFD700>%time%ꜱ <gray>ʙᴇꜰᴏʀᴇ ᴜsɪɴɢ <bold><gradient:#00E5FF:#CC75FF>ꜱᴘᴀᴡɴ</gradient></bold> <gray>ᴀɢᴀɪɴ"
sounds:
  enabled: true
  cooldown-active:
    sound: "block.note_block.bass"
    volume: 0.8
    pitch: 0.8
  teleport-countdown:
    sound: block.note_block.chime
    volume: 0.8
    pitch: 1.0
    rising-pitch: true
  teleport-success:
    sound: entity.player.levelup
    volume: 0.9
    pitch: 1.3
  teleport-cancelled:
    sound: block.note_block.bass
    volume: 0.9
    pitch: 0.7
  set-spawn-success:
    sound: block.amethyst_block.chime
    volume: 1.0
    pitch: 1.4
  no-permission:
    sound: entity.villager.no
    volume: 0.8
    pitch: 1.0
  reload-config-success:
    sound: block.note_block.bell
    volume: 1.0
    pitch: 1.5

For an existing server, add the new settings to plugins/SpawnHUD/config.yml and run /spawnreload; updating the bundled file does not overwrite the server’s existing config.

galaxy.linux

Change Name to NexaSpawn | And add Countdown like Teleporting in 5s

Kodari AI
KodariMon at 3:30 am 1
  1. Rename

[Generation stopped]

galaxy.linux

Change Name to NexaSpawn | And add Countdown like Teleporting in 5s after hit 0s he teleporting to spawn

Kodari AI
KodariMon at 3:32 am 1
  1. Rename the plugin to NexaSpawn.

  2. Show a 5-to-0 countdown before teleporting.

Renamed the plugin to NexaSpawn and updated the countdown text to show “Teleporting in 5s,” counting down until teleport.

The existing spawnhud.* permissions still apply; players with spawnhud.bypass teleport instantly. Since the plugin name changed, copy your existing plugins/SpawnHUD/config.yml to plugins/NexaSpawn/config.yml if you want to keep your saved spawn and settings.

galaxy.linux

nexaspawn.bypass spawnhud. to NexaSpawn.

Kodari AI
KodariMon at 3:36 am 1
  • Rename the permission nodes to nexaspawn.* in the plugin descriptor and command checks.

Updated the permission nodes to nexaspawn.set, nexaspawn.reload, and nexaspawn.bypass. Update any permission assignments that use the old spawnhud.* nodes.

galaxy.linux

spawnhud.* make to nexaspawn

Kodari AI
KodariMon at 3:43 am 1

I’ll add nexaspawn.* as the permission that grants all three NexaSpawn permissions.

Added nexaspawn.* to grant nexaspawn.set, nexaspawn.reload, and nexaspawn.bypass.

galaxy.linux

26.1.2

Kodari AI
KodariYesterday at 4:28 pm 1

NexaSpawn is a Paper plugin, so it can target Minecraft 26.1.2. Would you like me to update its Paper API dependency and plugin metadata to 26.1.2?

galaxy.linux

Supported?

Kodari AI
KodariYesterday at 4:29 pm 1

Yes, Kodari supports Paper plugin development for Minecraft 26.1.2. NexaSpawn currently targets Paper 1.21.11, though, so its compatibility with 26.1.2 hasn’t been verified.

galaxy.linux

Make it to 26.1.2

Kodari AI
KodariYesterday at 4:29 pm 1

I’ll update the Paper API target and plugin metadata to 26.1.2, and use Java 25 as required by the newer Paper API.

Updated NexaSpawn’s Paper API target and plugin metadata to 26.1.2, with Java 25.

The changes haven’t been compiled or tested yet.

Kodari can make mistakes. Review important code before using.
Files
src
pom.xml
Code
4 345
src/main/java/com/kodari/spawnhud/SpawnHUD.java
package com.kodari.spawnhud;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.SoundCategory;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public final class SpawnHUD extends JavaPlugin implements Listener {
    private final MiniMessage miniMessage = MiniMessage.miniMessage();
    private final Map<UUID, BukkitTask> countdowns = new HashMap<>();
    private final Map<UUID, Long> cooldowns = new HashMap<>();
    private final Set<String> warnedSounds = new HashSet<>();

    @Override
    public void onEnable() {
        saveDefaultConfig();
        getServer().getPluginManager().registerEvents(this, this);
    }

    @Override
    public void onDisable() {
        countdowns.values().forEach(BukkitTask::cancel);
        countdowns.clear();
        cooldowns.clear();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player player)) {
            sender.sendMessage(message("only-player", null));
            return true;
        }
        switch (command.getName().toLowerCase(java.util.Locale.ROOT)) {
            case "setspawn" -> {
                if (!checkPermission(player, "nexaspawn.set")) return true;
                Location location = player.getLocation();
                getConfig().set("spawn.world", location.getWorld().getName());
                getConfig().set("spawn.x", location.getX());
                getConfig().set("spawn.y", location.getY());
                getConfig().set("spawn.z", location.getZ());
                getConfig().set("spawn.yaw", location.getYaw());
                getConfig().set("spawn.pitch", location.getPitch());
                saveConfig();
                player.sendMessage(message("set-spawn-success", null));
                playSound(player, "set-spawn-success", 0);
            }
            case "spawnreload" -> {
                if (!checkPermission(player, "nexaspawn.reload")) return true;
                reloadConfig();
                player.sendMessage(message("reload-config-success", null));
                playSound(player, "reload-config-success", 0);
            }
            case "spawn" -> startTeleport(player);
            default -> { return false; }
        }
        return true;
    }

    private boolean checkPermission(Player player, String permission) {
        if (player.hasPermission(permission)) return true;
        error(player, "no-permission");
        playSound(player, "no-permission", 0);
        return false;
    }

    private void startTeleport(Player player) {
        UUID playerId = player.getUniqueId();
        if (!player.hasPermission("nexaspawn.bypass")) {
            long now = System.currentTimeMillis();
            long cooldownMillis = Math.max(0L, (long) getConfig().getInt("cooldown", 3)) * 1000L;
            Long lastUse = cooldowns.get(playerId);
            if (cooldownMillis > 0 && lastUse != null) {
                long remaining = cooldownMillis - (now - lastUse);
                if (remaining > 0) {
                    String text = getConfig().getString("messages.cooldown-active", "")
                            .replace("%time%", Long.toString((remaining + 999L) / 1000L));
                    player.sendActionBar(miniMessage.deserialize(text));
                    playSound(player, "cooldown-active", 0);
                    return;
                }
            }
            if (cooldownMillis > 0) cooldowns.put(playerId, now);
            else cooldowns.remove(playerId);
        }
        cancelCountdown(player.getUniqueId());
        if (spawnLocation() == null) {
            error(player, "spawn-location-not-set");
            return;
        }
        int delay = Math.max(0, getConfig().getInt("teleport-delay", 5));
        if (player.hasPermission("nexaspawn.bypass")) {
            teleport(player, "teleport-direct");
            return;
        }
        if (delay == 0) {
            teleport(player, "teleport-success");
            return;
        }

        BukkitRunnable runnable = new BukkitRunnable() {
            private int remaining = delay;

            @Override
            public void run() {
                if (!player.isOnline()) {
                    cancelCountdown(player.getUniqueId());
                    return;
                }
                if (remaining == 0) {
                    // Remove the task before teleporting so the move event cannot cancel it.
                    cancelCountdown(player.getUniqueId());
                    teleport(player, "teleport-success");
                    return;
                }
                hud(player, "teleport-countdown", Integer.toString(remaining));
                if (getConfig().getBoolean("hud.subtitle", true)) {
                    player.showTitle(Title.title(Component.empty(), Component.text(remaining),
                            Title.Times.times(Duration.ofMillis(100), Duration.ofMillis(800), Duration.ofMillis(100))));
                }
                playSound(player, "teleport-countdown", delay - remaining);
                remaining--;
            }
        };
        BukkitTask task = runnable.runTaskTimer(this, 0L, 20L);
        countdowns.put(player.getUniqueId(), task);
    }

    private void teleport(Player player, String messageKey) {
        Location destination = spawnLocation();
        if (destination == null) {
            error(player, "spawn-location-not-set");
            return;
        }
        if (player.teleport(destination)) {
            hud(player, messageKey, null);
            playSound(player, "teleport-success", 0);
        }
    }

    private Location spawnLocation() {
        ConfigurationSection section = getConfig().getConfigurationSection("spawn");
        if (section == null || !section.isString("world") || !section.isSet("x")
                || !section.isSet("y") || !section.isSet("z")) return null;
        World world = Bukkit.getWorld(section.getString("world", ""));
        if (world == null) return null;
        return new Location(world, section.getDouble("x"), section.getDouble("y"), section.getDouble("z"),
                (float) section.getDouble("yaw"), (float) section.getDouble("pitch"));
    }

    private Component message(String key, String countdown) {
        String text = getConfig().getString("messages." + key, "");
        if (countdown != null) text = text.replace("%countdown%", countdown);
        return miniMessage.deserialize(text);
    }

    private void hud(Player player, String key, String countdown) {
        if (getConfig().getBoolean("hud.actionbar", true)) player.sendActionBar(message(key, countdown));
    }

    private void error(Player player, String key) {
        if (getConfig().getBoolean("hud.chat-for-errors", true)) player.sendMessage(message(key, null));
        else hud(player, key, null);
    }

    private void playSound(Player player, String name, int elapsed) {
        if (!getConfig().getBoolean("sounds.enabled", true)) return;
        String path = "sounds." + name + ".";
        String sound = getConfig().getString(path + "sound", "");
        if (!sound.contains(":")) sound = "minecraft:" + sound;
        if (NamespacedKey.fromString(sound) == null) {
            if (warnedSounds.add(sound)) getLogger().warning("Invalid sound key: " + sound);
            return;
        }
        float volume = (float) getConfig().getDouble(path + "volume", 1.0);
        float pitch = (float) getConfig().getDouble(path + "pitch", 1.0);
        if (getConfig().getBoolean(path + "rising-pitch", false)) pitch += elapsed * 0.1f;
        pitch = Math.max(0.0f, Math.min(2.0f, pitch));
        try {