import React, { useMemo } from 'react'

function BackgroundImage({ url, transitionDuration }: { url: string, transitionDuration?: number }) {
    const bgRef = React.useRef<HTMLDivElement>(null)
    React.useEffect(() => {
        if (bgRef.current) {
            if (bgRef.current.style.backgroundImage !== `url(${url})`) {
                bgRef.current.style.backgroundImage = `url(${url})`
            }
        }
    }, [url])
    React.useEffect(() => {
        if (bgRef.current && transitionDuration) {
            const duration = Math.max(transitionDuration, 800)
            bgRef.current.style.transition = `background-image ${transitionDuration-800}ms 300ms ease, opacity ${transitionDuration}ms ease-in-out, blur ${duration}ms ease-in-out`
        }
    }, [transitionDuration])
    const element = useMemo(() => <div ref={bgRef} className="background-image" style={{ backgroundImage: `url(${url})`, transition: transitionDuration ? `background-image ${transitionDuration} ease, opacity ${transitionDuration} ease` : '' }} />, [])
    return element
} 

export default React.memo(BackgroundImage)