"use client";

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

export const ImageWithFallBack = (props: ImageProps) => {
  const { src, loader, unoptimized, placeholder, blurDataURL, ...rest } = props;
  const [isError, setIsError] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const fallback = "/img/image-load-failed.png";
  const resolvedSrc =
    !src ||
    src === "" ||
    (typeof src === "string" &&
      !src.startsWith("/") &&
      !src.startsWith("http://") &&
      !src.startsWith("https://") &&
      !src.startsWith("data:"))
      ? fallback
      : src;

  // همه تصاویر بدون بهینه‌ساز Next — فقط فایل لوکال/URL مستقیم
  return (
    <Image
      {...rest}
      loader={isError ? undefined : loader}
      src={isError ? fallback : resolvedSrc}
      unoptimized
      // placeholder فقط بعد از mount تا SSR/CSR یکی بماند
      {...(mounted && placeholder ? { placeholder, blurDataURL } : {})}
      onError={() => {
        setIsError(true);
      }}
    />
  );
};
