import React, { ImgHTMLAttributes } from "react";

import styles from "./Image.module.css";

export function Image(props: ImgHTMLAttributes<HTMLImageElement>) {
  const classes = props.className
    ? [props.className, styles.image]
    : [styles.image];

  if (props.src?.startsWith("http://") || props.src?.startsWith("https://")) {
    return <img {...props} className={classes.join(" ")} />;
  }

  const { src: relativeSrc = "" } = props;

  let absoluteSrc = process.env.NEXT_PUBLIC_BASE_PATH ?? "/";
  if (absoluteSrc.endsWith("/") && relativeSrc.startsWith("/")) {
    absoluteSrc += relativeSrc.slice(1);
  } else if (absoluteSrc.endsWith("/") || relativeSrc.startsWith("/")) {
    absoluteSrc += relativeSrc;
  } else {
    absoluteSrc += "/" + relativeSrc;
  }

  return <img {...props} src={absoluteSrc} className={classes.join(" ")} />;
}
