import { useRef, useState } from "react";

interface Props {
  /** Style candidates in priority order — the top style has been observed 404ing, so this falls through on load error. */
  candidates: string[];
  className?: string;
}

/*
|--------------------------------------------------------------------------
| Tarot Card Back (shared, self-healing artwork)
|--------------------------------------------------------------------------
|
| Each instance tracks its own fallback position, so many of these
| rendered at once (a 24-card fan, a row of spread slots) never race
| each other the way a single shared fallback index would when they
| all fail on the same broken style at the same time.
|
*/

export default function TarotCardBack({ candidates, className }: Props) {
  const [index, setIndex] = useState(0);

  const advancedFromRef = useRef(-1);

  const url = candidates[index];

  if (!url) {
    return <span className="tarot-card-symbol">✦</span>;
  }

  return (
    <img
      src={url}
      alt=""
      className={className}
      onError={() =>
        setIndex((current) => {
          if (advancedFromRef.current === current) return current;
          advancedFromRef.current = current;
          return current + 1 < candidates.length ? current + 1 : current;
        })
      }
    />
  );
}
