package dev.ulfrx.recipe.ui.components.recipe

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import dev.ulfrx.recipe.ui.theme.RecipeTheme
import kotlin.math.round

/**
 * Right-aligned amount + unit pair shared by [IngredientRow] (recipe detail
 * and meal-plan editor) and the addable-catalog rows in the "Dodaj składnik"
 * search panel. Amount is locale-formatted with a comma decimal; unit is
 * rendered muted so the value reads as primary.
 */
@Composable
fun IngredientAmount(
    amount: Double,
    unit: String,
    modifier: Modifier = Modifier,
) {
    val colors = RecipeTheme.colors
    val typography = RecipeTheme.typography
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(RecipeTheme.spacing.xs),
    ) {
        BasicText(
            text = formatIngredientAmount(amount),
            style =
                typography.body.copy(
                    color = colors.content,
                    fontWeight = FontWeight.SemiBold,
                    fontSize = AmountTextSize,
                    lineHeight = AmountLineHeight,
                ),
        )
        BasicText(
            text = unit,
            style =
                typography.body.copy(
                    color = colors.contentMuted,
                    fontSize = UnitTextSize,
                    lineHeight = AmountLineHeight,
                ),
        )
    }
}

/** One-decimal-place comma-formatted amount: 200.0 → "200", 1.5 → "1,5". */
internal fun formatIngredientAmount(value: Double): String {
    val scaled = round(value * 10.0).toLong()
    val whole = scaled / 10
    val frac = (scaled % 10).toInt()
    return if (frac == 0) whole.toString() else "$whole,$frac"
}

private val AmountTextSize = 12.sp
private val UnitTextSize = 11.sp
private val AmountLineHeight = 16.sp
