import { useEffect, useRef, useState } from "react";

interface ImageWithFallbackProps {
  src: string;
  alt: string;
  className?: string;
}

export function ImageWithFallback({ src, alt, className }: ImageWithFallbackProps) {
  const imgRef = useRef<HTMLImageElement>(null);
  const [imgSrc, setImgSrc] = useState(src);
  const [error, setError] = useState(false);

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

  const handleError = () => {
    if (!error && imgSrc.startsWith('/')) {
      setError(true);
      // Try with explicit origin if relative URL
      const baseURL = import.meta.env.MODE === "development"
        ? "http://127.0.0.1:8000"
        : window.location.origin;
      setImgSrc(`${baseURL}${imgSrc}`);
    }
  };

  return (
    <img
      ref={imgRef}
      src={imgSrc}
      alt={alt}
      className={className}
      onError={handleError}
    />
  );
}