// Theme management:
// Defaults to 'light' mode across all routes (including /login).
// If a user explicitly toggles theme via the theme toggle, the choice is saved
// in 'portal-user-theme' (or 'nuxt-color-mode') and respected.
export default defineNuxtPlugin((nuxtApp) => {
  const route = useRoute()
  const colorMode = useColorMode()

  const sync = () => {
    if (!import.meta.client) return

    try {
      const savedPortalTheme = localStorage.getItem('portal-user-theme')
      const targetTheme = (savedPortalTheme === 'dark' || savedPortalTheme === 'light')
        ? savedPortalTheme
        : 'light'

      if (colorMode.preference !== targetTheme) {
        colorMode.preference = targetTheme
      }

      const isDark = targetTheme === 'dark'
      document.documentElement.classList.toggle('dark', isDark)
      document.documentElement.classList.toggle('light', !isDark)
    } catch {
      document.documentElement.classList.remove('dark')
      document.documentElement.classList.add('light')
    }
  }

  sync()
  nuxtApp.hook('page:finish', sync)
  nuxtApp.hook('app:mounted', sync)
  watch(() => route.path, sync, { immediate: true })
})
