'use client'

import NextImage, { ImageProps as NextImageProps } from 'next/image'

import ImageFallback from '../ImageFallback'

import type { CSSProperties } from 'react'
import { imageLoader } from './imageLoader'

type FocalPoint = {
  x: number
  y: number
}

export type ImageProps = NextImageProps & {
  focalPoint?: FocalPoint
  dimensions?: { width: number; height: number }
}

// Next/Image adds & instead of ? before the params
export default function Image({
  focalPoint,
  dimensions,
  style,
  ...props
}: ImageProps) {
  const styles: CSSProperties = focalPoint
    ? {
        objectFit: 'cover',
        objectPosition: `${focalPoint.x}% ${focalPoint.y}%`,
        ...style,
      }
    : { ...style }

  if (!props.src) {
    return <ImageFallback />
  }

  return (
    <NextImage
      {...props}
      style={styles}
      loader={imageLoader({ dimensions, focalPoint })}
    />
  )
}
