/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.ui.theme

import androidx.compose.ui.graphics.Color

/**
 * Parses a brand accent hex string (`#RGB`, `#RRGGBB`, or `#AARRGGBB`, with or
 * without the leading `#`) into a Compose [Color]. Returns null for anything
 * unparseable so the theme falls back to its default scheme (PLAN.md §3, §5).
 * Pure logic — covered by JVM unit tests.
 *
 * Also the parser for every color token in the shard's resolved theme map
 * ([ShardPalette.resolve], M12): the server validates those as `#RGB` or
 * `#RRGGBB` on write, and a null here is what makes a token that slipped
 * through anyway cost only itself.
 */
fun parseBrandColor(hex: String?): Color? {
    if (hex.isNullOrBlank()) return null
    val cleaned = hex.trim().removePrefix("#")
    val normalized = when (cleaned.length) {
        3 -> cleaned.map { "$it$it" }.joinToString("") // #abc -> aabbcc
        6, 8 -> cleaned
        else -> return null
    }
    if (!normalized.all { it.isHexDigit() }) return null
    val rgb = normalized.takeLast(6)
    val alpha = if (normalized.length == 8) normalized.take(2) else "ff"
    return try {
        Color((alpha + rgb).toLong(16))
    } catch (_: NumberFormatException) {
        null
    }
}

private fun Char.isHexDigit(): Boolean =
    this in '0'..'9' || this in 'a'..'f' || this in 'A'..'F'
