import React, { useEffect, useState } from 'react'
import bgImage1 from '../assets/bg1-min.jpg'
import bgImage2 from '../assets/bg2-min.jpg'

const BackgroundContext = ({ children }) => {
  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 ? 'none' : `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
      }}
    >
      {loading ? '' : children}
      {/* Optionally add a loader while the background is being loaded */}
    </div>
  )
}

export default BackgroundContext
