package com.discordrules;

import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.IFormattableTextComponent;

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

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

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