import React, { useEffect, useState } from 'react'
import { RouterProvider } from 'react-router-dom'
import Router from './Routes/Routes'
import { AuthContextProvider, useAuthContext } from './contexts/AuthContext'
import { ClipLoader } from 'react-spinners' // Import the loader
import preloader from './assets/preloader.jpg'
import { DataProvider } from './contexts/MoyenneDeClasseContext'

const App = () => {
  const [loading, setLoading] = useState(true)
  const { setToken } = useAuthContext()

  // Simulate loading (e.g., fetching some initial data or assets)
  useEffect(() => {
    const timer = setTimeout(() => {
      setLoading(false) // Set loading to false after the simulated loading time
    }, 3000) // 3 seconds delay to simulate loading

    return () => clearTimeout(timer) // Cleanup the timer
  }, [])

  // Show Preloader while loading, else show your content
  if (loading) {
    return (
      <div
        className="preloader-container"
        style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          backgroundImage: `url("${preloader}")`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          minHeight: '100vh'
        }}
      >
        <ClipLoader color="blue" loading={loading} size={50} />
      </div>
    )
  }

  /**
   * condition usign with the Tray icon on the bottom
   */
  if (window.Tray && typeof window.Tray.onNavigate === 'function') {
    window.Tray.onNavigate((route) => {
      if (route) {
        window.location.hash = route // Navigate by updating the hash
      }
    })
  }

  return (
    <AuthContextProvider>
      <DataProvider>
        <RouterProvider router={Router} />
      </DataProvider>
    </AuthContextProvider>
  )
}

export default App
