/* eslint-disable @next/next/no-img-element */

interface CreatorSquareBlurOgImageProps {
  imageUrl: string | null;
  imageWidth?: number | null;
  imageHeight?: number | null;
  canvasWidth: number;
  canvasHeight: number;
}

function clamp(value: number, min: number, max: number): number {
  return Math.min(max, Math.max(min, value));
}

export default function CreatorSquareBlurOgImage({
  imageUrl,
  imageWidth,
  imageHeight,
  canvasWidth,
  canvasHeight,
}: CreatorSquareBlurOgImageProps) {
  if (!imageUrl) {
    return (
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          backgroundColor: '#000000',
        }}
      />
    );
  }

  const ratio =
    imageWidth && imageHeight && imageWidth > 0 && imageHeight > 0 ? imageWidth / imageHeight : 1;

  // This renderer is used for near-square images:
  // keep full image height and fill horizontal side space with blur.
  const normalizedRatio = clamp(ratio, 0.8, 1.2);

  const foregroundWidth = Math.min(canvasWidth, Math.round(canvasHeight * normalizedRatio));

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        position: 'relative',
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden',
        backgroundColor: '#000000',
      }}
    >
      <img
        src={imageUrl}
        alt=""
        style={{
          position: 'absolute',
          inset: 0,
          width: '100%',
          height: '100%',
          objectFit: 'cover',
          filter: 'blur(42px)',
          transform: 'scale(1.18)',
          opacity: 0.88,
        }}
      />

      <div
        style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          background:
            'linear-gradient(90deg, rgba(0,0,0,0.40), rgba(0,0,0,0.10) 20%, rgba(0,0,0,0.10) 80%, rgba(0,0,0,0.40))',
        }}
      />

      <img
        src={imageUrl}
        alt=""
        style={{
          position: 'relative',
          width: foregroundWidth,
          height: canvasHeight,
          objectFit: 'cover',
        }}
      />
    </div>
  );
}
