import { useState, useRef, useEffect, useCallback } from 'react';

interface ScreenshotCarouselProps {
  screenshots?: string[];
  placeholder?: string;
}

export default function ScreenshotCarousel({ screenshots }: ScreenshotCarouselProps) {
  const [active, setActive] = useState(0);
  const scrollRef = useRef<HTMLDivElement>(null);

  const scrollTo = useCallback((i: number) => {
    setActive(i);
    scrollRef.current?.children[i]?.scrollIntoView({
      behavior: 'smooth',
      block: 'nearest',
      inline: 'center',
    });
  }, []);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            const idx = Array.from(el.children).indexOf(e.target);
            if (idx >= 0) setActive(idx);
          }
        });
      },
      { root: el, threshold: 0.6 }
    );
    Array.from(el.children).forEach((c) => observer.observe(c));
    return () => observer.disconnect();
  }, []);

  if (!screenshots || screenshots.length === 0) {
    return null;
  }

  return (
    <div className="screenshot-carousel">
      <div className="screenshot-scroll" ref={scrollRef}>
        {screenshots.map((src, i) => (
          <div key={i} className="screenshot-slide">
            <img src={src} alt={`Screenshot ${i + 1}`} className="screenshot-image" />
          </div>
        ))}
      </div>
      {screenshots.length > 1 && (
        <div className="screenshot-dots">
          {screenshots.map((_, i) => (
            <button
              key={i}
              className={`screenshot-dot ${i === active ? 'active' : ''}`}
              onClick={() => scrollTo(i)}
            />
          ))}
        </div>
      )}
    </div>
  );
}
