import { useEffect } from 'react'
import { RouterProvider } from 'react-router-dom'
import { router } from '@/router'
import { useAuthStore } from '@/store/authStore'
import { useThemeStore } from '@/store/themeStore'

function App() {
  const { isAuthenticated, fetchUser, setLoading } = useAuthStore()
  const { theme, setTheme } = useThemeStore()

  useEffect(() => {
    // On app load, check if we have a token and fetch user data
    const token = localStorage.getItem('access_token')
    if (token && isAuthenticated) {
      fetchUser().catch(() => {
        // Token is invalid, will be handled by interceptor
      })
    } else {
      setLoading(false)
    }
  }, [])

  // Listen for system theme changes
  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    const handleChange = () => {
      if (theme === 'system') {
        setTheme('system') // Re-apply to update resolvedTheme
      }
    }

    mediaQuery.addEventListener('change', handleChange)
    return () => mediaQuery.removeEventListener('change', handleChange)
  }, [theme, setTheme])

  return <RouterProvider router={router} />
}

export default App
