package dev.kaizen.app.ui.theme

import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
import dev.kaizen.app.ui.theme.themes.AmberTheme
import dev.kaizen.app.ui.theme.themes.KaizenAccentScheme
import dev.kaizen.app.ui.theme.themes.KaizenThemeId
import dev.kaizen.app.ui.theme.themes.KaizenThemeSpec
import dev.kaizen.app.ui.theme.themes.ThemeRegistry

/**
 * CompositionLocal for the active Kaizen accent scheme.
 *
 * Use `LocalKaizenAccent.current` to access theme-specific colors (primary,
 * blobs, ring) that go beyond MaterialTheme.colorScheme. This is the bridge
 * between the four Kaizen themes and the Material3 color system.
 */
val LocalKaizenAccent = staticCompositionLocalOf { AmberTheme.dark }

private fun buildDarkScheme(accent: KaizenAccentScheme) = darkColorScheme(
    primary = accent.primary,
    onPrimary = accent.onPrimary,
    secondary = accent.primary,
    onSecondary = accent.onPrimary,
    background = Obsidian,
    onBackground = DarkText,
    surface = ObsidianElevated,
    onSurface = DarkText,
    surfaceVariant = ObsidianInput,
    onSurfaceVariant = DarkMuted,
    outline = DarkStroke,
)

private fun buildLightScheme(accent: KaizenAccentScheme) = lightColorScheme(
    primary = accent.primary,
    onPrimary = accent.onPrimary,
    secondary = accent.primary,
    onSecondary = accent.onPrimary,
    background = LightBackground,
    onBackground = LightText,
    surface = LightSurface,
    onSurface = LightText,
    surfaceVariant = LightSurfaceVariant,
    onSurfaceVariant = LightMuted,
    outline = LightStroke,
)

@Composable
fun KaizenTheme(
    themeId: KaizenThemeId = KaizenThemeId.AMBER,
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit,
) {
    val spec = ThemeRegistry.forId(themeId)
    val accent = if (darkTheme) spec.dark else spec.light
    val colorScheme = if (darkTheme) buildDarkScheme(accent) else buildLightScheme(accent)

    CompositionLocalProvider(LocalKaizenAccent provides accent) {
        MaterialTheme(
            colorScheme = colorScheme,
            typography = Typography,
            content = content,
        )
    }
}
