package com.discordrules;

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

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 = new TextComponent("");
        String[] lines = processedText.split("\n");
        for (String line : lines) {
            MutableComponent lineComponent;
            if (line.startsWith("**") && line.endsWith("**")) {
                String cleanLine = line.replace("**", "");
                lineComponent = new TextComponent(cleanLine);
                lineComponent.withStyle(headerColor, ChatFormatting.BOLD);
            } else if (line.trim().startsWith("-") || line.trim().startsWith("\u2022")) {
                lineComponent = new TextComponent("  " + line.trim());
                lineComponent.withStyle(bodyColor);
            } else {
                lineComponent = new TextComponent(line);
                lineComponent.withStyle(bodyColor);
            }
            rootComponent.append(lineComponent).append(new TextComponent("\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;
        }
    }
}
