import React, { useEffect, useState } from 'react'
import { Outlet, Navigate } from 'react-router-dom'
import { useAuthContext } from '../contexts/AuthContext'
import Navbar from '../components/Navbar'
import bgImage1 from '../assets/bg1-min.jpg'
import bgImage2 from '../assets/bg2-min.jpg'

const LoginLayout = () => {
  const { token } = useAuthContext()

  if (token) {
    return <Navigate to={'/'} />
  }

  const [backgroundImage, setBackgroundImage] = useState('') // Background image URL
  const [loading, setLoading] = useState(true) // To manage loading state

  // useEffect(() => {
  const images = [bgImage1, bgImage2]

  // Select a random image
  const randomImage = images[Math.floor(Math.random() * images.length)]

  // Preload the image
  const img = new Image()
  img.src = randomImage

  img.onload = () => {
    setBackgroundImage(randomImage) // Set the background image once loaded
    setLoading(false) // Stop loading
  }
  // }, []);

  return (
    <div
      style={{
        backgroundImage: loading ? `url(${bgImage1})` : `url(${backgroundImage})`, // Don't set background image until loaded
        backgroundColor: loading ? 'transparent' : 'transparent', // Fallback background while loading
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        minHeight: '100vh' // Full-screen height for the background
      }}
    >
      <Outlet />
      {/* Optionally add a loader while the background is being loaded */}
    </div>
  )
}

export default LoginLayout
