export type AppTheme = 'light' | 'dark'

const THEME_STORAGE_KEY = 'mdm-theme'

function isAppTheme(value: string | null): value is AppTheme {
  return value === 'light' || value === 'dark'
}

export function getPreferredTheme(): AppTheme {
  if (typeof window === 'undefined') return 'light'

  const storedTheme = window.localStorage.getItem(THEME_STORAGE_KEY)
  if (isAppTheme(storedTheme)) return storedTheme

  return window.matchMedia('(prefers-color-scheme: dark)').matches
    ? 'dark'
    : 'light'
}

export function applyTheme(theme: AppTheme) {
  if (typeof document === 'undefined') return

  document.documentElement.dataset.theme = theme
}

export function saveTheme(theme: AppTheme) {
  if (typeof window === 'undefined') return

  window.localStorage.setItem(THEME_STORAGE_KEY, theme)
}

export function initTheme() {
  applyTheme(getPreferredTheme())
}

export function getThemeStorageKey() {
  return THEME_STORAGE_KEY
}
