import { useState } from 'react';

type Props = {
  images: string[];
  alt: string;
};

export default function CoffeeDetailGallery({ images, alt }: Props) {
  const [index, setIndex] = useState(0);
  const safeImages = images.length > 0 ? images : [''];
  const current = safeImages[index] || '';

  return (
    <div className="space-y-3">
      <div className="relative h-72 sm:h-96 overflow-hidden rounded-2xl border border-slate-200 bg-slate-100">
        {current ? (
          <img src={current} alt={alt} className="h-full w-full object-cover" />
        ) : (
          <div className="h-full w-full flex items-center justify-center text-sm text-slate-400">No image available</div>
        )}
      </div>

      {safeImages.length > 1 && (
        <div className="grid grid-cols-4 sm:grid-cols-6 gap-2">
          {safeImages.map((img, i) => (
            <button
              key={`${img}-${i}`}
              type="button"
              onClick={() => setIndex(i)}
              className={`relative h-16 sm:h-20 overflow-hidden rounded-xl border transition ${
                i === index ? 'border-slate-900 ring-2 ring-slate-900/20' : 'border-slate-200 hover:border-slate-300'
              }`}
              aria-label={`Show gallery image ${i + 1}`}
            >
              <img src={img} alt={`${alt} ${i + 1}`} className="h-full w-full object-cover" />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
