package com.ponzischeme89.memby.ui

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.platform.LocalContext
import androidx.core.graphics.get
import androidx.core.graphics.drawable.toBitmap
import coil.imageLoader
import coil.request.ImageRequest
import coil.request.SuccessResult

/**
 * Whether a title's logo artwork should be replaced by its plain-text name.
 *
 * Transparent Emby logos are commonly black. They disappear over a dark backdrop, so a
 * small decoded copy is inspected and the text title retained when the visible pixels are
 * overwhelmingly dark. Until the image has been inspected, text is the safe default — a
 * title that arrives a frame late is better than a title that never appears.
 *
 * Shared by the screensaver and the detail hero: both draw a title over a near-black scrim,
 * and a logo that is invisible on one is invisible on the other.
 */
@Composable
internal fun useTextTitleForLogo(logoUrl: String?): Boolean {
    if (logoUrl == null) return true
    val context = LocalContext.current
    val isDark by produceState(initialValue = true, logoUrl) {
        value = runCatching {
            val result = context.imageLoader.execute(
                ImageRequest.Builder(context)
                    .data(logoUrl)
                    .allowHardware(false)
                    .size(64, 64)
                    .build(),
            ) as? SuccessResult ?: return@runCatching true
            isPredominantlyDarkLogo(result.drawable.toBitmap(width = 64, height = 64))
        }.getOrDefault(true)
    }
    return isDark
}

private fun isPredominantlyDarkLogo(bitmap: android.graphics.Bitmap): Boolean {
    var opaquePixels = 0
    var darkPixels = 0
    for (y in 0 until bitmap.height step 2) {
        for (x in 0 until bitmap.width step 2) {
            val pixel = bitmap[x, y]
            if (android.graphics.Color.alpha(pixel) < 48) continue
            opaquePixels++
            val luminance = (
                android.graphics.Color.red(pixel) * 0.2126f +
                    android.graphics.Color.green(pixel) * 0.7152f +
                    android.graphics.Color.blue(pixel) * 0.0722f
                )
            if (luminance < 58f) darkPixels++
        }
    }
    return opaquePixels < 12 || darkPixels.toFloat() / opaquePixels > 0.82f
}
