import React from 'react';

import { getImageFromField } from '../utils';

/**
 * CDN Image tag
 * @param {import('../../types').ImgComponentProps & React.ComponentProps<'img'>} props
 * @returns {React.FunctionComponentElement}
 */
export const Img = (props) => {
  const {
    alt = '',
    image = null,
    transform = {},
    imgRef = null,
    getImageUrl,
    ...restProps
  } = props;

  const url = getImageFromField(image);

  if (!url) {
    return null;
  }

  const masterImageUrl = getImageUrl(url, transform);
  const width = transform?.w;

  return (
    <img
      alt={alt}
      src={masterImageUrl}
      {...(imgRef ? { ref: imgRef } : {})}
      {...(width ? { width } : {})}
      {...restProps}
    />
  );
};
