package dev.kaizen.app

import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.compose.runtime.collectAsState
import androidx.activity.enableEdgeToEdge
import dev.kaizen.app.auth.LoginScreen
import dev.kaizen.app.chat.ChatScreen
import dev.kaizen.app.chat.ChatViewModel
import dev.kaizen.app.net.SecureStore
import dev.kaizen.app.net.SessionViewModel
import dev.kaizen.app.settings.SettingsViewModel
import dev.kaizen.app.settings.AppAppearance
import dev.kaizen.app.ui.theme.KaizenTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Enable High Dynamic Range (HDR) window color mode on Android 14+ (API 34+)
        // and Wide Color Gamut (Display P3) on Android 8.0+ (API 26+)
        // This leverages the hardware capabilities of high-end AMOLED/OLED displays (S25 Ultra, Pixel 10).
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            window.colorMode = ActivityInfo.COLOR_MODE_HDR
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            window.colorMode = ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT
        }

        val secureStore = SecureStore(applicationContext)
        val settingsViewModel = SettingsViewModel(secureStore)
        val sessionViewModel = SessionViewModel(secureStore)
        val chatViewModel = ChatViewModel(applicationContext)

        // auto() picks light/dark system-bar icons based on the system theme
        enableEdgeToEdge(
            statusBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT),
            navigationBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT),
        )
        setContent {
            val themeId = settingsViewModel.selectedTheme.collectAsState()
            val appearance = settingsViewModel.appearanceMode.collectAsState()
            val darkOverride = when (appearance.value) {
                AppAppearance.Light -> false
                AppAppearance.Dark -> true
                AppAppearance.System -> androidx.compose.foundation.isSystemInDarkTheme()
            }
            KaizenTheme(themeId = themeId.value, darkTheme = darkOverride) {
                // Snapshot-state routing: logging in/out flips session.config and
                // recomposes this branch — no NavHost needed for two top-level states.
                if (sessionViewModel.isLoggedIn) {
                    ChatScreen(settingsViewModel = settingsViewModel, session = sessionViewModel, chat = chatViewModel)
                } else {
                    LoginScreen(session = sessionViewModel)
                }
            }
        }
    }
}
