import { ref, watch } from 'vue'

// Initialize immediately from localStorage to prevent flash
function getInitialTheme() {
  if (typeof window === 'undefined') return false
  const stored = localStorage.getItem('admin-panel-theme')
  if (stored) return stored === 'dark'
  return window.matchMedia('(prefers-color-scheme: dark)').matches
}

const isDark = ref(getInitialTheme())

// Apply immediately (before Vue mounts)
if (typeof document !== 'undefined') {
  document.documentElement.setAttribute('data-theme', isDark.value ? 'dark' : 'light')
}

export function useTheme() {
  function initTheme() {
    applyTheme()
  }

  function applyTheme() {
    document.documentElement.setAttribute('data-theme', isDark.value ? 'dark' : 'light')
  }

  function toggleTheme() {
    isDark.value = !isDark.value
    localStorage.setItem('admin-panel-theme', isDark.value ? 'dark' : 'light')
    applyTheme()
  }

  function setTheme(dark) {
    isDark.value = dark
    localStorage.setItem('admin-panel-theme', dark ? 'dark' : 'light')
    applyTheme()
  }

  watch(isDark, applyTheme)

  return {
    isDark,
    initTheme,
    toggleTheme,
    setTheme,
  }
}
