import { useEffect, useState } from 'react';

import ImageWithFallback from '@/components/image/ImageWithFallback';

import { VIDEO_FALLBACK_TIMEOUT } from './constants';

const LivingRadioBackgroundVideo = () => {
  // Video fallback state
  const [videoFallback, setVideoFallback] = useState<boolean>(false);
  const [videoLoaded, setVideoLoaded] = useState<boolean>(false);

  // Video fallback timeout
  useEffect(() => {
    // Only set timeout if video hasn't loaded and no fallback yet
    if (!videoLoaded && !videoFallback) {
      const timeout = setTimeout(() => {
        setVideoFallback(true);
      }, VIDEO_FALLBACK_TIMEOUT);

      return () => clearTimeout(timeout);
    }
  }, [videoLoaded, videoFallback]);

  return (
    <>
      {!videoFallback ? (
        <video
          className='fixed inset-0 h-[calc(100dvh-50px-env(safe-area-inset-bottom,0px))] w-full object-cover md:absolute md:h-full'
          autoPlay
          loop
          muted
          playsInline
          poster='https://cdn-o.suno.com/suno-living-radio-poster.webp'
          onError={() => setVideoFallback(true)}
          onCanPlayThrough={() => setVideoLoaded(true)}
        >
          <source
            src='https://cdn-o.suno.com/Suno_LivingRadio_Visualiser.webm'
            type='video/webm'
          />
        </video>
      ) : (
        <div className='fixed inset-0 h-[calc(100dvh-50px-env(safe-area-inset-bottom,0px))] w-full object-cover md:absolute md:h-full'>
          <ImageWithFallback
            fill={true}
            src='https://cdn-o.suno.com/suno-living-radio-poster.webp'
            alt='Living Radio background'
            className='absolute inset-0 h-full w-full object-cover'
          />
        </div>
      )}
    </>
  );
};

export default LivingRadioBackgroundVideo;
