import { ref, watch } from 'vue'

const isDark = ref(false)

export function useTheme() {
  function initTheme() {
    const stored = localStorage.getItem('admin-panel-theme')
    if (stored) {
      isDark.value = stored === 'dark'
    } else {
      // Check system preference
      isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    applyTheme()
  }

  function applyTheme() {
    if (isDark.value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  function toggleTheme() {
    isDark.value = !isDark.value
    localStorage.setItem('admin-panel-theme', isDark.value ? 'dark' : 'light')
    applyTheme()
  }

  function setTheme(dark) {
    isDark.value = dark
    localStorage.setItem('admin-panel-theme', dark ? 'dark' : 'light')
    applyTheme()
  }

  watch(isDark, applyTheme)

  return {
    isDark,
    initTheme,
    toggleTheme,
    setTheme,
  }
}
