import { useState } from 'react'
import { useColorScheme } from 'react-native'
import { useMMKVListener } from 'react-native-mmkv'
import { appStorage, uiKeys, VALID_THEMES } from 'src/state/storage'

// Resolve the user-chosen theme, listening for changes to `ui.theme` in MMKV
// so selections in settings/appearance propagate instantly. `system` defers
// to the OS scheme (which also updates via useColorScheme).
export function useStoredTheme(): 'light' | 'dark' {
  const [stored, setStored] = useState<string>(
    () => appStorage.getString(uiKeys.theme) ?? 'system'
  )
  useMMKVListener((key) => {
    if (key === uiKeys.theme) {
      setStored(appStorage.getString(uiKeys.theme) ?? 'system')
    }
  }, appStorage)
  const systemScheme = useColorScheme() ?? 'light'
  const effective =
    !VALID_THEMES.has(stored) || stored === 'system' ? systemScheme : stored
  return effective === 'dark' ? 'dark' : 'light'
}
