export default defineNuxtPlugin((nuxtApp) => {
  const nuxt = useNuxtApp()
  const $q = nuxt.vueApp.config.globalProperties.$q



  // ฟังก์ชันสลับโหมดและ Sync กับ Quasar
  const updateTheme = (isDark: boolean) => {
    if (isDark) {
      document.documentElement.classList.add('dark')
      if ($q) $q.dark.set(true)
    } else {
      document.documentElement.classList.remove('dark')
      if ($q) $q.dark.set(false)
    }
  }

  // ตอนเริ่มทำงานบน Client
  if (process.client) {
    const { set } = useThemeMode()
    const savedTheme = localStorage.getItem('theme')
    const isDark = savedTheme === 'dark' || (!savedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches)
    
    set(isDark)
    // Also explicitly force updateTheme initially since watcher might not fire if state matches default
    updateTheme(isDark)
  }
})
