package eu.gaudian.translator.utils

import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight

/**
 * Formats a simple subset of Markdown (bold, italic) into an AnnotatedString.
 */
fun formatMarkdownText(text: String): AnnotatedString {
    val formattedText = text.trim()
    return buildAnnotatedString {
        var i = 0
        while (i < formattedText.length) {
            when {
                formattedText.startsWith("**", i) -> {
                    val endIndex = formattedText.indexOf("**", i + 2)
                    if (endIndex != -1) {
                        pushStyle(SpanStyle(fontWeight = FontWeight.Bold))
                        append(formattedText.substring(i + 2, endIndex))
                        pop()
                        i = endIndex + 2
                    } else {
                        append(formattedText[i])
                        i++
                    }
                }
                formattedText.startsWith("*", i) -> {
                    val endIndex = formattedText.indexOf("*", i + 1)
                    if (endIndex != -1) {
                        pushStyle(SpanStyle(fontStyle = FontStyle.Italic))
                        append(formattedText.substring(i + 1, endIndex))
                        pop()
                        i = endIndex + 1
                    } else {
                        append(formattedText[i])
                        i++
                    }
                }
                else -> {
                    append(formattedText[i])
                    i++
                }
            }
        }
    }
}