'use client';

import Image from 'next/image';
import { useState, useEffect } from 'react';
import { getImageUrl } from '@/lib/imageUrl';

interface ProductGalleryProps {
  image: string;
  images?: string[];
  title: string;
}

export default function ProductGallery({ image, images, title }: ProductGalleryProps) {
  const rawList = images && images.length > 0 ? images : [image];
  const thumbnails = rawList.map((img) => getImageUrl(img));

  const [selected, setSelected] = useState<string>(thumbnails[0] || '/assets/home/lenses.png');

  useEffect(() => {
    if (thumbnails[0]) {
      setSelected(thumbnails[0]);
    }
  }, [thumbnails[0]]);

  return (
    <div className="w-full max-w-[598px]">

      <div className="relative h-[500px] w-full max-w-[598px] overflow-hidden">

        <Image
          src={selected}
          alt={title}
          fill
          unoptimized
          onError={() => setSelected('/assets/home/lenses.png')}
          className="object-contain py-12"
        />

      </div>

      <div className="flex h-[100px] w-full gap-3 overflow-x-auto">

        {thumbnails.map((thumb, index) => (
          <button
            key={`${thumb}-${index}`}
            onClick={() => setSelected(thumb)}
            className={`relative h-full w-[100px] shrink-0 overflow-hidden rounded-xl border transition ${
              selected === thumb ? 'border-blue-600' : 'border-[#E2E8F0]'
            }`}
          >
            <Image
              src={thumb}
              alt={title}
              fill
              unoptimized
              className="object-contain p-2"
            />
          </button>
        ))}

      </div>

    </div>
  );
}
