"use client";

import { useState } from "react";

interface TipProductImageProps {
  alt: string;
  className: string;
  priority?: boolean;
  sources: readonly string[];
}

export function TipProductImage({
  alt,
  className,
  priority = false,
  sources,
}: TipProductImageProps) {
  const [sourceIndex, setSourceIndex] = useState(0);
  const source = sources[sourceIndex] ?? sources[sources.length - 1];
  if (!source) return null;

  return (
    // Gift hosts are managed by the backend and cannot be safely enumerated in Next remotePatterns.
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={source}
      alt={alt}
      className={className}
      loading={priority ? "eager" : "lazy"}
      fetchPriority={priority ? "high" : "auto"}
      onError={() => {
        if (sourceIndex < sources.length - 1) {
          setSourceIndex((index) => index + 1);
        }
      }}
    />
  );
}
