"use client";

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

interface MediaImageProps extends Omit<ImageProps, "src" | "onError" | "alt"> {
  /** Ordered candidate URLs — first one that loads wins. */
  srcs: (string | null | undefined)[];
  alt: string;
  /** Rendered once every candidate has failed (or none were provided). */
  fallback?: React.ReactNode;
}

/**
 * R2 conversion URLs aren't guaranteed to exist even when Spatie's
 * `generated_conversions` metadata says they do (conversion jobs can fail
 * silently). This tries each candidate in order and falls through on 404 /
 * load error instead of rendering a broken image.
 */
export default function MediaImage({ srcs, alt, fallback = null, ...rest }: MediaImageProps) {
  const candidates = srcs.filter((s): s is string => !!s);
  const [index, setIndex] = useState(0);

  if (index >= candidates.length) return <>{fallback}</>;

  return (
    <Image
      key={candidates[index]}
      src={candidates[index]}
      alt={alt}
      onError={() => setIndex((i) => i + 1)}
      {...rest}
    />
  );
}
