import NextImage, { type ImageProps as NextImageProps } from "next/image";
import styles from "./image.module.scss";

type ImageProps = NextImageProps & {
  attribution?: string | null;
  caption?: string | null;
  imageFormat?: string | null; // "original" | "bleed" | "fullWidth"
};

function isSvgSrc(src: NextImageProps["src"]): src is string {
  return typeof src === "string" && /\.svg(\?|#|$)/i.test(src);
}

function MaybeNextImage(props: NextImageProps) {
  if (isSvgSrc(props.src)) {
    const { src, alt, width, height, className, style } = props;
    return (
      <img // eslint-disable-line @next/next/no-img-element
        src={src}
        alt={alt}
        width={width}
        height={height}
        className={className}
        style={style}
      />
    );
  }
  return <NextImage {...props} />;
}

export function ImageFigure(props: ImageProps) {
  const { attribution, caption, imageFormat, ...imageProps } = props;
  return (
    <figure
      className={`${styles.image} ${imageFormat ? styles[imageFormat] : ""}`}
    >
      <div className={styles.imageWrapper}>
        <MaybeNextImage {...imageProps} />
        {attribution && <div className={styles.attribution}>{attribution}</div>}
      </div>
      {caption && <figcaption>{caption}</figcaption>}
    </figure>
  );
}

export function Image(props: NextImageProps) {
  return <MaybeNextImage {...props} />;
}
