import { ref, watchEffect } from 'vue'

const THEME_KEY = 'theme-mode'

export function useTheme() {
  const theme = ref<'light' | 'dark'>(getInitialTheme())

  function getInitialTheme() {
    if (typeof window === 'undefined') return 'light'
    const persisted = localStorage.getItem(THEME_KEY)
    if (persisted === 'dark' || persisted === 'light') return persisted
    // fallback: system preference
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }

  function setTheme(newTheme: 'light' | 'dark') {
    theme.value = newTheme
    localStorage.setItem(THEME_KEY, newTheme)
    document.documentElement.classList.toggle('dark', newTheme === 'dark')
  }

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

  watchEffect(() => {
    setTheme(theme.value)
  })

  return { theme, toggleTheme }
}
