package app.voltplan.cable.util

import java.text.NumberFormat
import java.util.Locale
import kotlin.math.roundToInt

/**
 * Locale-aware numeric helpers that mirror the iOS NumberFormatter usage
 * (minimumFractionDigits = 0, maximumFractionDigits = 1).
 */
object Fmt {
    private fun formatter(maxFraction: Int): NumberFormat =
        NumberFormat.getNumberInstance(Locale.getDefault()).apply {
            minimumFractionDigits = 0
            maximumFractionDigits = maxFraction
        }

    /** Locale-aware, 0–1 fraction digits. Equivalent to the iOS display formatter. */
    fun number(value: Double): String = formatter(1).format(value)

    /** Locale-aware integer (0 fraction digits). */
    fun integer(value: Double): String = formatter(0).format(value)

    fun roundToTenth(value: Double): Double = (value * 10).roundToInt() / 10.0

    fun roundToNearestFive(value: Double): Double = (value / 5).roundToInt() * 5.0

    /** Parses user input accepting both "." and "," decimal separators. */
    fun parseInput(text: String): Double? {
        val trimmed = text.trim()
        if (trimmed.isEmpty()) return null
        trimmed.toDoubleOrNull()?.let { return it }
        // Try swapping the locale separator the other way.
        val swapped = if (trimmed.contains(',')) trimmed.replace(',', '.') else trimmed.replace('.', ',')
        swapped.replace(',', '.').toDoubleOrNull()?.let { return it }
        return try {
            NumberFormat.getNumberInstance(Locale.getDefault()).parse(trimmed)?.toDouble()
        } catch (_: Exception) {
            null
        }
    }

    /** Formats a recommended fuse rating: "%.0f" when whole, "%.1f" otherwise. */
    fun fuse(value: Double): String =
        if (value == value.roundToInt().toDouble()) value.roundToInt().toString()
        else String.format(Locale.US, "%.1f", value)
}
