/**
 * CanvasBackground Component
 *
 * Background image, video, and audio for the constructor canvas.
 * Handles blob URLs, Next.js Image optimization, and previous background overlay.
 */

import React from 'react';
import NextImage from 'next/image';

interface CanvasBackgroundProps {
  backgroundImageUrl?: string;
  backgroundVideoUrl?: string;
  backgroundAudioUrl?: string;
  previousBgImageUrl?: string;
  isSwitching?: boolean;
  isNewBgReady?: boolean;
  onBackgroundReady?: () => void;
}

const CanvasBackground: React.FC<CanvasBackgroundProps> = ({
  backgroundImageUrl,
  backgroundVideoUrl,
  backgroundAudioUrl,
  previousBgImageUrl,
  isSwitching = false,
  isNewBgReady = false,
  onBackgroundReady,
}) => {
  const handleLoad = () => {
    onBackgroundReady?.();
  };

  const handleError = () => {
    onBackgroundReady?.();
  };

  return (
    <>
      {/* Background image */}
      {backgroundImageUrl && (
        <div className='absolute inset-0 h-full w-full pointer-events-none select-none'>
          {backgroundImageUrl.startsWith('blob:') ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              key={`bg_image_${backgroundImageUrl}`}
              src={backgroundImageUrl}
              alt='Background'
              className='absolute inset-0 w-full h-full object-cover'
              draggable={false}
              onLoad={handleLoad}
              onError={handleError}
            />
          ) : (
            <NextImage
              key={`bg_image_${backgroundImageUrl}`}
              src={backgroundImageUrl}
              alt='Background'
              fill
              sizes='100vw'
              className='object-cover'
              draggable={false}
              unoptimized
              onLoad={handleLoad}
              onError={handleError}
            />
          )}
        </div>
      )}

      {/* Previous background overlay - shows during page switch until new bg is ready */}
      {previousBgImageUrl && isSwitching && !isNewBgReady && (
        <div
          className='absolute inset-0 pointer-events-none z-10'
          style={{
            backgroundImage: `url("${previousBgImageUrl}")`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
          }}
        />
      )}

      {/* Background video */}
      {backgroundVideoUrl && (
        <video
          key={`bg_video_${backgroundVideoUrl}`}
          className='absolute inset-0 w-full h-full object-cover'
          src={backgroundVideoUrl}
          autoPlay
          loop
          muted
          playsInline
        />
      )}

      {/* Background audio */}
      {backgroundAudioUrl && (
        <audio
          key={`bg_audio_${backgroundAudioUrl}`}
          src={backgroundAudioUrl}
          autoPlay
          loop
          hidden
        />
      )}
    </>
  );
};

export default CanvasBackground;
