import { ref, watch } from 'vue'

const STORAGE_KEY = 'shopdb-theme'

// Get initial theme from localStorage or system preference
function getInitialTheme() {
  const stored = localStorage.getItem(STORAGE_KEY)
  if (stored) return stored

  // Fall back to system preference
  if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return 'dark'
  }
  return 'light'
}

export const currentTheme = ref(getInitialTheme())

// Apply theme to document
function applyTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme)
  localStorage.setItem(STORAGE_KEY, theme)
}

// Initialize on load
applyTheme(currentTheme.value)

// Watch for changes
watch(currentTheme, (newTheme) => {
  applyTheme(newTheme)
})

export function toggleTheme() {
  currentTheme.value = currentTheme.value === 'dark' ? 'light' : 'dark'
}

export function setTheme(theme) {
  currentTheme.value = theme
}
