// src/components/ImageCarousel.js
import clsx from 'clsx';
import React, { useState, useEffect, useCallback } from 'react';
import styles from './ImageCarousel.module.css';

export default function ImageCarousel({ images }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isOpen, setIsOpen] = useState(false);

  const currentImage = images[currentIndex];

  const closeLightbox = () => setIsOpen(false);

  const handleKeyDown = useCallback((e) => {
    if (!isOpen) return;

    switch (e.key) {
      case 'Escape':
        closeLightbox();
        break;
      case 'ArrowRight':
        setCurrentIndex((prev) => (prev + 1) % images.length);
        break;
      case 'ArrowLeft':
        setCurrentIndex((prev) => (prev - 1 + images.length) % images.length);
        break;
    }
  }, [isOpen, images.length]);

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  return (
    <>
      <div className={styles.carousel}>
        <img
          src={currentImage.src}
          alt={currentImage.caption}
          className={styles.mainImage}
          onClick={() => setIsOpen(true)}
        />
        <div className={styles.thumbnails}>
          {images.map((img, i) => (
            <img
              key={i}
              src={img.src}
              alt={img.caption}
              className={`${styles.thumbnail} ${i === currentIndex ? styles.active : ''}`}
              onClick={() => setCurrentIndex(i)}
            />
          ))}
        </div>
      </div>

      {isOpen && (
        <div className={styles.lightbox} onClick={closeLightbox}>
          <button className={styles.closeButton} onClick={closeLightbox}>&times;</button>
          <button
            className={`${styles.navButton} ${styles.left}`}
            onClick={(e) => { e.stopPropagation(); setCurrentIndex((prev) => (prev - 1 + images.length) % images.length); }}
          >
            &#10094;
          </button>
          <img src={currentImage.src} alt={currentImage.caption} className={styles.lightboxImage} />
          <button
            className={`${styles.navButton} ${styles.right}`}
            onClick={(e) => { e.stopPropagation(); setCurrentIndex((prev) => (prev + 1) % images.length); }}
          >
            &#10095;
          </button>
        </div>
      )}
    </>
  );
}
