import { ref, onMounted } from 'vue'

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

const STORAGE_KEY = 'claudia-theme'

function getSystemPrefersDark(): boolean {
  return window.matchMedia('(prefers-color-scheme: dark)').matches
}

function getInitialTheme(): Theme {
  const stored = localStorage.getItem(STORAGE_KEY)
  if (stored === 'light' || stored === 'dark' || stored === 'system') {
    return stored
  }
  return 'system'
}

function resolveTheme(theme: Theme): 'light' | 'dark' {
  if (theme === 'system') {
    return getSystemPrefersDark() ? 'dark' : 'light'
  }
  return theme
}

const theme = ref<Theme>(getInitialTheme())
const resolvedTheme = ref<'light' | 'dark'>(resolveTheme(theme.value))

function applyTheme(resolved: 'light' | 'dark') {
  const root = document.documentElement
  if (resolved === 'dark') {
    root.classList.add('dark')
  } else {
    root.classList.remove('dark')
  }
}

function setTheme(newTheme: Theme) {
  theme.value = newTheme
  localStorage.setItem(STORAGE_KEY, newTheme)
  resolvedTheme.value = resolveTheme(newTheme)
  applyTheme(resolvedTheme.value)
}

function toggleTheme() {
  const current = resolvedTheme.value
  setTheme(current === 'dark' ? 'light' : 'dark')
}

function initTheme() {
  resolvedTheme.value = resolveTheme(theme.value)
  applyTheme(resolvedTheme.value)

  // Listen for system preference changes
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', () => {
    if (theme.value === 'system') {
      resolvedTheme.value = resolveTheme('system')
      applyTheme(resolvedTheme.value)
    }
  })
}

export function useTheme() {
  onMounted(() => {
    initTheme()
  })

  return {
    theme,
    resolvedTheme,
    setTheme,
    toggleTheme,
    initTheme
  }
}
