import React, { useMemo, useState, useEffect } from 'react';
import { FaRegHeart, FaHeart } from 'react-icons/fa';

export default function ProductCard({
  product,
  onSelect,
  isFavorite,
  onToggleFavorite,
  count = 0,
  ringColor = "#22c55e", // Fallback
}) {
  const baseName = (product?.name || '').replace(/\s+/g, '').toLowerCase();

  // Fester Fallback (Datei MUSS in /public liegen und so heißen)
  const FALLBACK_IMG = '/no-image_img.jpg';

  // Letzter Fallback: eingebettetes SVG (funktioniert ohne Datei)
  const FALLBACK_SVG =
    'data:image/svg+xml;utf8,' +
    encodeURIComponent(
      `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="600">
         <rect width="100%" height="100%" fill="#111827"/>
         <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle"
               fill="#9CA3AF" font-family="sans-serif" font-size="28">
           Kein Bild
         </text>
       </svg>`
    );

  // Bild-Kandidaten (Reihenfolge = Priorität)
  const candidates = useMemo(
    () =>
      [
        product?.image_url,            // absolute oder /public-URL
        product?.image,                // alternative Feldquelle
        `/${baseName}_img.jpg`,        // z.B. /spezi_img.jpg (in /public)
        `/images/${baseName}.jpg`,     // z.B. /images/spezi.jpg (in /public/images)
      ].filter(Boolean),
    [product, baseName]
  );

  // Aktueller Kandidaten-Index + Quelle
  const [idx, setIdx] = useState(0);
  const current = candidates[idx] || FALLBACK_IMG;
  const [imgSrc, setImgSrc] = useState(current);

  // WICHTIG: Bei Kandidatenwechsel wieder von vorne anfangen
  useEffect(() => {
    setIdx(0);
    setImgSrc(candidates[0] || FALLBACK_IMG);
  }, [candidates]);

  const handleError = () => {
    const nextIdx = idx + 1;
    if (nextIdx < candidates.length) {
      setIdx(nextIdx);
      setImgSrc(candidates[nextIdx]);
    } else if (imgSrc !== FALLBACK_IMG) {
      setImgSrc(FALLBACK_IMG);
    } else {
      setImgSrc(FALLBACK_SVG);
    }
  };

  return (
     <div
       role="button"
       tabIndex={0}
       style={{ "--tw-ring-color": ringColor }}
       className="relative rounded-xl overflow-hidden bg-gray-800 cursor-pointer transform transition duration-150 hover:scale-95
              ring-0 hover:ring-4 ring-offset-0 ring-offset-gray-900
              focus-visible:outline-none focus-visible:ring-2"
      onClick={() => onSelect(product)}
      onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && onSelect(product)}
      >
      <img
        src={imgSrc}
        onError={handleError}
        alt={product?.name || 'Produktbild'}
        className="w-full h-40 object-cover select-none"
        draggable={false}
        loading="lazy"
      />

      <div className="p-2 bg-gray-950">
        <h3 className="text-white font-semibold text-lg truncate">{product?.name}</h3>
        <p className="text-gray-400 text-sm truncate">
          {product?.volume_ml ? `${(product.volume_ml / 1000).toFixed(1)}L • ` : ''}
          €{((product?.price_cents ?? 0) / 100).toFixed(2).replace('.', ',')}
        </p>
      </div>

      {/* Favoriten-Button */}
      <button
        type="button"
        onClick={(e) => { e.stopPropagation(); onToggleFavorite(product.id); }}
        className="absolute top-2 right-2 text-red-600 text-xl"
        aria-label={isFavorite ? 'Favorit entfernen' : 'Als Favorit markieren'}
      >
        {isFavorite ? <FaHeart /> : <FaRegHeart />}
      </button>

      {/* Mengen-Badge */}
      {count > 0 && (
        <div className="absolute top-2 left-2 bg-green-600 text-white text-xs font-bold px-2 py-1 rounded-full">
          x{count}
        </div>
      )}
    </div>
  );
}
