package eu.gaudian.translator.view.composable

import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign

@Composable
 fun AutoResizeSingleLineText(
    text: String,
    modifier: Modifier = Modifier,
    style: androidx.compose.ui.text.TextStyle,
    minFontSize: androidx.compose.ui.unit.TextUnit = style.fontSize * 0.5f,
    maxFontSize: androidx.compose.ui.unit.TextUnit = style.fontSize,
    textAlign: TextAlign = TextAlign.Start,
    color: Color = Color.Unspecified,
    fontWeight: FontWeight? = null,
) {
    var fontSize by remember(text) { mutableStateOf(maxFontSize) }

    Text(
        text = text,
        maxLines = 1,
        softWrap = false,
        textAlign = textAlign,
        style = style.copy(fontSize = fontSize),
        onTextLayout = { result ->
            if (result.didOverflowWidth) {
                val next = fontSize * 0.95f
                if (next.value >= minFontSize.value && next != fontSize) {
                    fontSize = next
                }
            }
        },
        modifier = modifier,
        color = color
    )
}


 fun insertBreakOpportunities(text: String): String {
    if (text.isEmpty()) return text
    val zwsp = "\u200B"
    return text
        // Keep hyphen (or dash) at the end of the line and allow a break after it
        .replace("‑", "‑$zwsp") // non-breaking hyphen U+2011
        .replace("-", "-$zwsp") // hyphen-minus
        .replace("–", "–$zwsp") // en dash
        .replace("—", "—$zwsp") // em dash
        .replace("·", "·$zwsp") // middle dot
        .replace("/", "/$zwsp") // slash
}

@Suppress("DEPRECATION") //TODO find a solution for this
@Composable
fun ClickableText(
    text: AnnotatedString,
    style: androidx.compose.ui.text.TextStyle,
){
    val uriHandler = LocalUriHandler.current

    ClickableText(
        text = text,
        style = style,
        onClick = { offset ->
            text.getStringAnnotations("URL", offset, offset)
                .firstOrNull()?.let { uriHandler.openUri(it.item) }
        }
    )

}