import { create } from 'zustand'
import type { SystemThemeInfo } from '@shared/ipc'
import { isPreview as PREVIEW } from '../isPreview'
import { useSettings } from './settings'

const prefersDark =
  typeof window !== 'undefined' && window.matchMedia
    ? window.matchMedia('(prefers-color-scheme: dark)')
    : null

export const useSystemTheme = create<SystemThemeInfo>(() => ({
  shouldUseDarkColors: prefersDark?.matches ?? false,
  shouldUseHighContrastColors: false
}))

if (!PREVIEW) {
  window.api.getSystemTheme().then((info) => useSystemTheme.setState(info))
  window.api.onSystemThemeUpdate((info) => useSystemTheme.setState(info))
} else {
  // Browser preview has no nativeTheme bridge — approximate dark-mode
  // follow with matchMedia so flipping the OS/devtools preference still works.
  prefersDark?.addEventListener('change', (e) =>
    useSystemTheme.setState({ shouldUseDarkColors: e.matches })
  )
}

/**
 * Whether the app is currently rendering in dark mode. Resolves the 'system'
 * preference against the live OS signal, so a component never has to special-case
 * it (the bug where a raw `theme === 'dark'` check left thumbnails light under
 * Auto + a dark OS). The single source of truth for light/dark — used by App for
 * the FluentProvider and by anything that needs theme-aware colors (thumbColors).
 */
export function useResolvedDark(): boolean {
  const theme = useSettings((s) => s.theme)
  const systemPrefersDark = useSystemTheme((s) => s.shouldUseDarkColors)
  return theme === 'system' ? systemPrefersDark : theme === 'dark'
}
