export type Theme = 'dark' | 'light'

const THEME_KEY = 'osolit-theme'

export function useTheme() {
  const theme = useState<Theme>('theme', () => 'light')

  function setTheme(newTheme: Theme) {
    theme.value = newTheme
    if (import.meta.client) {
      document.documentElement.setAttribute('data-theme', newTheme)
      localStorage.setItem(THEME_KEY, newTheme)
    }
  }

  function toggleTheme() {
    const newTheme = theme.value === 'dark' ? 'light' : 'dark'
    setTheme(newTheme)
  }

  function initTheme() {
    if (import.meta.client) {
      const saved = localStorage.getItem(THEME_KEY) as Theme | null
      const initial = saved || 'light'
      setTheme(initial)
    }
  }

  return {
    theme,
    setTheme,
    toggleTheme,
    initTheme
  }
}
