"use client"
import React, { useId } from "react"
import { classNames } from "../../utils"

export type MeshGradientProps = {
  imageUrl: string | undefined
  className?: string
  innerClassName?: string
}

/**
 * Generates a mesh gradient fron an image. Useful for cases where we want to derive a banner image from a profile image.
 */
export const MeshGradient = ({
  className,
  innerClassName,
  imageUrl,
}: MeshGradientProps) => {
  const id = useId()

  return (
    <div className={classNames("relative overflow-hidden", className)}>
      <svg
        className={classNames(
          "absolute inset-0 z-0 size-full scale-[2.5] bg-black blur-3xl saturate-200",
          innerClassName,
        )}
        xmlns="http://www.w3.org/2000/svg"
      >
        <image
          className="object-fill"
          height="100%"
          href={imageUrl}
          preserveAspectRatio="none"
          width="100%"
        />
        <image
          className="object-fill"
          height="100%"
          href={imageUrl}
          preserveAspectRatio="none"
          style={{ filter: `url(#${id})` }}
          width="100%"
        />
        <defs>
          <filter
            colorInterpolationFilters="sRGB"
            height="100%"
            id={id}
            overflow="visible"
            width="100%"
            x="0"
            y="0"
          >
            <feTurbulence
              baseFrequency="0.01"
              numOctaves="10"
              result="turbulence"
              seed="1"
              type="fractalNoise"
            />
            <feDisplacementMap
              in="SourceGraphic"
              in2="turbulence"
              scale="500"
              xChannelSelector="R"
              yChannelSelector="G"
            ></feDisplacementMap>
          </filter>
        </defs>
      </svg>
    </div>
  )
}
