package fr.luc.gamingcore.util;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public final class TextUtil {

    private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
    private static final LegacyComponentSerializer AMPERSAND_SERIALIZER = LegacyComponentSerializer.legacyAmpersand();

    private static String prefix = "<gradient:#00C9FF:#92FE9D>[Guilde]</gradient> <dark_gray>»</dark_gray> <gray>";

    private TextUtil() {}

    public static void setPrefix(String newPrefix) {
        if (newPrefix != null) {
            prefix = newPrefix;
        }
    }

    public static String getPrefix() {
        return prefix;
    }

    /**
     * Parses a string containing MiniMessage tags or legacy color codes into a Component.
     */
    public static Component parse(String input) {
        if (input == null || input.isEmpty()) {
            return Component.empty();
        }
        String formatted = input.replace('§', '&');
        if (formatted.contains("&")) {
            return AMPERSAND_SERIALIZER.deserialize(formatted);
        }
        return MINI_MESSAGE.deserialize(input);
    }

    public static void sendMessage(CommandSender sender, String message) {
        if (sender == null || message == null) return;
        sender.sendMessage(parse(prefix + message));
    }

    public static void sendRawMessage(CommandSender sender, String message) {
        if (sender == null || message == null) return;
        sender.sendMessage(parse(message));
    }

    public static void sendActionBar(Player player, String message) {
        if (player == null || message == null) return;
        player.sendActionBar(parse(message));
    }
}
