import type { CSSProperties, ImgHTMLAttributes } from 'react'

type ImageSource = string | { src: string }

export type ImageProps = Omit<
  ImgHTMLAttributes<HTMLImageElement>,
  'src' | 'width' | 'height'
> & {
  src: ImageSource
  width?: number
  height?: number
  fill?: boolean
  priority?: boolean
  placeholder?: string
}

const resolveSource = (src: ImageSource) => {
  return typeof src === 'string' ? src : src.src
}

export default function Image({
  src,
  fill,
  priority,
  style,
  width,
  height,
  ...rest
}: ImageProps) {
  const resolvedStyle: CSSProperties = fill
    ? {
        position: 'absolute',
        inset: 0,
        width: '100%',
        height: '100%',
        ...style,
      }
    : { ...style }

  return (
    <img
      src={resolveSource(src)}
      width={width}
      height={height}
      loading={priority ? 'eager' : rest.loading}
      {...rest}
      style={resolvedStyle}
    />
  )
}
