package com.discordrules;

import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;

public class DiscordFormatter {
    public static MutableComponent formatRules(String rawDiscordText) {
        String processedText = ServerRulesConfig.STRIP_EMOJIS.get()
            ? stripEmojis(rawDiscordText) : rawDiscordText;
        ChatFormatting headerColor = parseColor(ServerRulesConfig.HEADER_COLOR.get(), ChatFormatting.GOLD);
        ChatFormatting bodyColor = parseColor(ServerRulesConfig.BODY_COLOR.get(), ChatFormatting.YELLOW);
        MutableComponent rootComponent = Component.empty();
        String[] lines = processedText.split("\n");
        for (String line : lines) {
            MutableComponent lineComponent;
            if (line.startsWith("**") && line.endsWith("**")) {
                String cleanLine = line.replace("**", "");
                lineComponent = Component.literal(cleanLine).withStyle(headerColor, ChatFormatting.BOLD);
            } else if (line.trim().startsWith("-") || line.trim().startsWith("\u2022")) {
                lineComponent = Component.literal("  " + line.trim()).withStyle(bodyColor);
            } else {
                lineComponent = Component.literal(line).withStyle(bodyColor);
            }
            rootComponent.append(lineComponent).append(Component.literal("\n"));
        }
        return rootComponent;
    }

    private static String stripEmojis(String text) {
        if (text == null) return "";
        return text.replaceAll("[\\x{1F300}-\\x{1F9FF}]", "");
    }

    private static ChatFormatting parseColor(String name, ChatFormatting fallback) {
        try {
            return ChatFormatting.valueOf(name.toUpperCase());
        } catch (IllegalArgumentException e) {
            return fallback;
        }
    }
}
