"use client";

import Image from "next/image";
import React, { useEffect, useState } from "react";

// global cache
const imageCache = new Map();

export default function SafeImage({
  src,
  alt,
  fallbackSrc = "/images/no-image.svg",
  getIsError,
  ...props
}) {
  const [imgSrc, setImgSrc] = useState(src);
  const [hasError, setHasError] = useState(false);
  const handleError = () => {
    if (!hasError) {
      setHasError(true);
      if (getIsError && typeof getIsError === "function") getIsError(true);
      if (imageCache.has(src)) {
        setImgSrc(imageCache.get(src));
      } else {
        setImgSrc(fallbackSrc);
      }
    }
  };

  useEffect(() => {
    setImgSrc(src);
    setHasError(false);
  }, [src]);

  return (
    <Image
      {...props}
      src={imgSrc}
      alt={alt}
      onError={handleError}
      style={{
        objectPosition: "center",
        objectFit: hasError ? "contain" : "cover",
        ...(props.style || {}),
        ...(hasError ? props.notfoundstyle || {} : {}),
      }}
    />
  );
}
