import { StrictMode, Suspense, useEffect } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter, useRoutes } from 'react-router-dom'
import { Providers } from './providers'
import RootLayout from './layout'
import routes from '~react-pages'

export function App() {
  useEffect(() => {
    const storedTheme = localStorage.getItem('theme')
    const systemPrefersDark = window.matchMedia(
      '(prefers-color-scheme: dark)',
    ).matches
    const theme =
      storedTheme === 'dark' || storedTheme === 'light'
        ? storedTheme
        : systemPrefersDark
          ? 'dark'
          : 'light'

    document.documentElement.classList.remove('light', 'dark')
    document.documentElement.classList.add(theme)
    document.documentElement.setAttribute('data-theme', theme)
  }, [])

  return <Suspense fallback={<p>Loading...</p>}>{useRoutes(routes)}</Suspense>
}

const app = createRoot(document.getElementById('root')!)

app.render(
  <StrictMode>
    <BrowserRouter>
      <Providers>
        <RootLayout>
          <App />
        </RootLayout>
      </Providers>
    </BrowserRouter>
  </StrictMode>,
)
