import { ref, onMounted, watch } from 'vue'

type Theme = 'light' | 'dark'
type Accent = 'katlum'

const theme = ref<Theme>('light')
const accent = ref<Accent>('katlum')

const applyTheme = () => {
  document.documentElement.setAttribute('data-theme', theme.value)
  document.documentElement.setAttribute('data-accent', accent.value)
}

const setTheme = (value: Theme) => {
  theme.value = value
  localStorage.setItem('theme', value)
  applyTheme();
}

const setAccent = (value: Accent) => {
  accent.value = value
  localStorage.setItem('accent', value)
  applyTheme();
}

const setupTheme = () => {
  const savedTheme = localStorage.getItem('theme') as Theme | null
  const savedAccent = localStorage.getItem('accent') as Accent | null

  const media = window.matchMedia('(prefers-color-scheme: dark)')

  theme.value = savedTheme || (media.matches ? 'dark' : 'light')
  accent.value = savedAccent || 'katlum'

  applyTheme()

  media.addEventListener('change', (e) => {
    if (!localStorage.getItem('theme')) {
      theme.value = e.matches ? 'dark' : 'light'
      applyTheme()
    }
  })
};

watch([theme, accent], applyTheme)

export { theme, accent, setTheme, setAccent, setupTheme}