import { create } from 'zustand'
import { applyThemeColors, getThemeByName } from '@/lib/themes'

type Mode = 'light' | 'dark' | 'system'

interface ThemeState {
  mode: Mode
  colorTheme: string
  setMode: (mode: Mode) => void
  setColorTheme: (name: string) => void
}

function isDarkMode(mode: Mode): boolean {
  return mode === 'dark' || (mode === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
}

function apply(mode: Mode, colorTheme: string) {
  const dark = isDarkMode(mode)
  document.documentElement.classList.toggle('dark', dark)
  const theme = getThemeByName(colorTheme)
  applyThemeColors(dark ? theme.dark : theme.light)
}

export const useThemeStore = create<ThemeState>((set) => {
  const initialMode = (typeof window !== 'undefined' ? localStorage.getItem('lunarfront-mode') as Mode : null) ?? 'system'
  const initialColor = (typeof window !== 'undefined' ? localStorage.getItem('lunarfront-color-theme') : null) ?? 'slate'

  if (typeof window !== 'undefined') {
    apply(initialMode, initialColor)
  }

  return {
    mode: initialMode,
    colorTheme: initialColor,

    setMode: (mode) => {
      localStorage.setItem('lunarfront-mode', mode)
      const colorTheme = useThemeStore.getState().colorTheme
      apply(mode, colorTheme)
      set({ mode })
    },

    setColorTheme: (name) => {
      localStorage.setItem('lunarfront-color-theme', name)
      const mode = useThemeStore.getState().mode
      apply(mode, name)
      set({ colorTheme: name })
    },
  }
})
