const isDark = ref(false)

export function useDarkMode() {
  const toggle = () => {
    isDark.value = !isDark.value
    applyTheme()
  }

  const applyTheme = () => {
    const theme = isDark.value ? 'mytheme-dark' : 'mytheme'
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('theme', theme)
  }

  const init = () => {
    const saved = localStorage.getItem('theme')
    if (saved === 'mytheme-dark') {
      isDark.value = true
    } else if (!saved && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      isDark.value = true
    }
    applyTheme()
  }

  return { isDark, toggle, init }
}
