package com.tomhempel.rbarometer.questionnaire

import com.tomhempel.rbarometer.LanguageManager
import com.tomhempel.rbarometer.ui.localization.UiStrings

/**
 * Resolves stored answer values to spinner indices (keys, localized labels, or free text).
 */
object SpinnerSelectionHelper {

    /** Label shown in the spinner for one option (literal text or translated key). */
    fun optionDisplayLabel(languageId: String, option: String): String {
        val trimmed = option.trim()
        if (trimmed.isEmpty()) return trimmed
        val translated = LanguageManager.getText(languageId, trimmed).trim()
        if (translated.isEmpty()) return trimmed
        if (translated.equals(trimmed, ignoreCase = true)) return trimmed
        if (UiStrings.stripBrackets(translated).equals(trimmed, ignoreCase = true)) return trimmed
        return translated
    }

    fun buildStringSpinnerItems(languageId: String, optionKeys: List<String>): List<String> {
        val prompt = SpinnerAnswerRules.chooseAnswerPrompt(languageId)
        return listOf(prompt) + optionKeys.map { optionDisplayLabel(languageId, it) }
    }

    fun indexForSavedValue(
        languageId: String,
        displayItems: List<String>,
        saved: String?,
        optionKeys: List<String> = emptyList(),
    ): Int {
        if (saved.isNullOrBlank() || displayItems.isEmpty()) return -1
        val trimmed = saved.trim()
        val prompt = SpinnerAnswerRules.chooseAnswerPrompt(languageId)

        displayItems.indexOfFirst { it.equals(trimmed, ignoreCase = true) }
            .takeIf { it >= 0 }
            ?.let { return it }

        for ((i, item) in displayItems.withIndex()) {
            if (item == prompt) continue
            if (item.equals(trimmed, ignoreCase = true)) return i
        }

        for (key in optionKeys) {
            val raw = key.trim()
            val label = optionDisplayLabel(languageId, raw)
            if (trimmed.equals(raw, ignoreCase = true) || trimmed.equals(label, ignoreCase = true)) {
                displayItems.indexOfFirst { it.equals(label, ignoreCase = true) }
                    .takeIf { it >= 0 }
                    ?.let { return it }
            }
        }

        for ((i, item) in displayItems.withIndex()) {
            if (item == prompt) continue
            if (UiStrings.stripBrackets(item).equals(UiStrings.stripBrackets(trimmed), ignoreCase = true)) {
                return i
            }
        }
        return -1
    }
}
