"use client";

import Image, { type ImageProps } from "next/image";
import { useEffect, useState } from "react";
import { FALLBACK_IMAGE } from "@/data/product-images";

type SafeImageProps = Omit<ImageProps, "src" | "onError"> & {
  src: string;
  fallbackSrc?: string;
};

/** next/image wrapper that swaps to a working fallback if the source 404s. */
export function SafeImage({
  src,
  fallbackSrc = FALLBACK_IMAGE,
  alt,
  ...props
}: SafeImageProps) {
  const [current, setCurrent] = useState(src || fallbackSrc);
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    setCurrent(src || fallbackSrc);
    setFailed(false);
  }, [src, fallbackSrc]);

  const localOrPicsum =
    typeof current === "string" &&
    (current.startsWith("/uploads/") ||
      current.includes("picsum.photos") ||
      current.includes("fastly.picsum"));

  return (
    <Image
      {...props}
      src={failed ? fallbackSrc : current}
      alt={alt}
      unoptimized={props.unoptimized ?? (localOrPicsum || failed)}
      onError={() => {
        if (!failed) setFailed(true);
      }}
    />
  );
}
