import { watch } from 'vue'
import { useDark, useStorage } from '@vueuse/core'

export type Theme = 'dark' | 'light' | 'auto'

const theme = useStorage<Theme>('wgrplane-theme', 'auto')

const isDark = useDark({
  selector: 'html',
  attribute: 'class',
  valueDark: 'dark',
  valueLight: 'light'
})

watch(theme, (newTheme) => {
  if (newTheme === 'auto') {
    localStorage.removeItem('vueuse-color-scheme')
  } else {
    localStorage.setItem('vueuse-color-scheme', newTheme)
  }
  if (newTheme === 'dark') {
    isDark.value = true
  } else if (newTheme === 'light') {
    isDark.value = false
  }
})

export function useTheme() {
  return {
    theme,
    isDark,
    toggleTheme: (newTheme: Theme) => {
      theme.value = newTheme
    }
  }
}
