import React, { useMemo, useState } from 'react';

// Flexible image loader that tries extensions in order when an image fails.
// Usage: <ImageFlex base="/assets/hero" alt="..." className="..." />
// Optionally pass explicit candidates via srcCandidates=["/a.jpg","/a.png"].
export default function ImageFlex({
  base,
  exts = ['webp', 'jpg', 'jpeg', 'png'],
  srcCandidates,
  alt = '',
  className = '',
  style,
  ...rest
}) {
  const candidates = useMemo(() => {
    if (Array.isArray(srcCandidates) && srcCandidates.length > 0) return srcCandidates;
    if (typeof base === 'string') return exts.map((e) => `${base}.${e}`);
    return [];
  }, [base, exts, srcCandidates]);

  const [idx, setIdx] = useState(0);
  const src = candidates[idx];

  function handleError() {
    if (idx < candidates.length - 1) setIdx(idx + 1);
  }

  if (!src) return null;

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


