"use client";

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

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

const LOGO_PLACEHOLDER = "/logo.png";

export default function SafeImage({
  fallbackSrc = LOGO_PLACEHOLDER,
  src,
  alt,
  ...props
}: SafeImageProps) {
  const [imgSrc, setImgSrc] = useState<ImageProps["src"]>(src);

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

  const resolvedSrc =
    typeof imgSrc === "string" && imgSrc.trim() === "" ? fallbackSrc : imgSrc;

  /* Only the logo placeholder is dimmed. A caller that supplies a real picture
     as `fallbackSrc` wants it shown, not faded to 20%. */
  const isPlaceholder = resolvedSrc === LOGO_PLACEHOLDER;
  const mergedStyle = {
    ...props.style,
    objectFit: isPlaceholder ? "contain" : props.style?.objectFit,
    opacity: isPlaceholder ? 0.2 : props.style?.opacity,
  } as React.CSSProperties;

  return (
    <Image
      {...props}
      src={resolvedSrc}
      alt={alt}
      style={mergedStyle}
      onError={() => {
        // A custom fallback can fail too; the logo is the last resort.
        setImgSrc((current) => (current === fallbackSrc ? LOGO_PLACEHOLDER : fallbackSrc));
      }}
    />
  );
}
