"use client";

import { useState } from "react";
import Image, { type ImageProps } from "next/image";
import { IMAGES } from "@/branding";
import { cn, isPlaceholderImage } from "@/lib/utils";

type SafeImageProps = Omit<ImageProps, "src" | "onError"> & {
  /** API-sourced image URL — may be missing or the backend's generic "no image" placeholder */
  src?: string | null;
};

/**
 * Drop-in replacement for next/image for any API-sourced image field.
 * Renders the app icon instead of the backend's generic placeholder image,
 * and also falls back to it if a real image URL fails to load.
 */
export default function SafeImage({ src, alt, className, ...rest }: SafeImageProps) {
  const [failed, setFailed] = useState(false);

  if (failed || isPlaceholderImage(src)) {
    return <Image src={IMAGES.appLogo} alt={alt} className={cn(className, "object-contain p-[18%]")} {...rest} />;
  }

  return (
    <Image
      src={src as string}
      alt={alt}
      className={className}
      onError={() => setFailed(true)}
      {...rest}
    />
  );
}