"use client";

import { useState } from "react";
import { imageUrl } from "../utils/image";

interface ImageWithFallbackProps {
  src: string;
  alt: string;
  fallbackSrc?: string;
  className?: string;
  style?: React.CSSProperties;
}

export default function ImageWithFallback({
  src,
  alt,
  fallbackSrc = "_images/default.jpg",
  className,
  style,
}: ImageWithFallbackProps) {
  const [imgSrc, setImgSrc] = useState(imageUrl(src));
  const [hasError, setHasError] = useState(false);

  const handleError = () => {
    if (!hasError) {
      setHasError(true);
      setImgSrc(imageUrl(fallbackSrc));
    }
  };

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