import { getImageProps } from 'next/image'

interface BannerMediaProps {
  imageUrl: string
  mobileImageUrl: string | null
  alt: string
  // `sizes` for the desktop image; the mobile crop is always full-width.
  sizes: string
  // Above-the-fold hero image: fetch eagerly with high priority. (Next 16
  // deprecates `priority`; `preload` would pick one source and can preload
  // the wrong one when a mobile crop exists — see the next/image docs.)
  eager?: boolean
  className?: string
}

// Banner image with optional art direction: a separate portrait crop below
// the `md` breakpoint when the admin uploaded one (banner_images.mobile_image).
// Fills its (relatively positioned) parent. Works in server and client
// components — getImageProps doesn't use hooks.
export default function BannerMedia({ imageUrl, mobileImageUrl, alt, sizes, eager = false, className = '' }: BannerMediaProps) {
  const loading = eager ? ('eager' as const) : ('lazy' as const)
  const fetchPriority = eager ? ('high' as const) : undefined
  const {
    props: { srcSet: desktopSrcSet, ...rest },
  } = getImageProps({ src: imageUrl, alt, fill: true, sizes, loading, fetchPriority })

  const imgClass = `object-cover ${className}`

  if (!mobileImageUrl) {
    // eslint-disable-next-line jsx-a11y/alt-text, @next/next/no-img-element -- getImageProps output (optimized srcSet; alt included)
    return <img {...rest} srcSet={desktopSrcSet} className={imgClass} />
  }

  const {
    props: { srcSet: mobileSrcSet },
  } = getImageProps({ src: mobileImageUrl, alt, fill: true, sizes: '100vw', loading, fetchPriority })

  return (
    <picture>
      <source media="(min-width: 768px)" srcSet={desktopSrcSet} sizes={sizes} />
      <source srcSet={mobileSrcSet} sizes="100vw" />
      {/* eslint-disable-next-line jsx-a11y/alt-text -- getImageProps art direction (see next/image docs); alt included */}
      <img {...rest} className={imgClass} />
    </picture>
  )
}
