import { useState, useEffect } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import './ImageSlider.css'

const ImageSlider = ({ images }) => {
  const [currentIndex, setCurrentIndex] = useState(0)
  const [imageErrors, setImageErrors] = useState({})

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % images.length)
    }, 3000)

    return () => clearInterval(interval)
  }, [images.length])

  const goToPrevious = () => {
    setCurrentIndex((prev) => (prev - 1 + images.length) % images.length)
  }

  const goToNext = () => {
    setCurrentIndex((prev) => (prev + 1) % images.length)
  }

  const goToSlide = (index) => {
    setCurrentIndex(index)
  }

  return (
    <div className="slider-container">
      <div className="slider-wrapper">
        {images.map((img, index) => (
          <div
            key={index}
            className={`slide ${index === currentIndex ? 'active' : ''}`}
            style={{ 
              backgroundImage: imageErrors[index]
                ? 'linear-gradient(135deg, #D2691E 0%, #CD853F 100%)'
                : `url(${img}), linear-gradient(135deg, #D2691E 0%, #CD853F 100%)`,
              backgroundSize: 'cover',
              backgroundPosition: 'center'
            }}
          >
            <img 
              src={img} 
              alt={`Slide ${index + 1}`}
              style={{ display: 'none' }}
              onError={() => setImageErrors(prev => ({ ...prev, [index]: true }))}
            />
          </div>
        ))}
      </div>
      <button className="slider-btn prev" onClick={goToPrevious}>
        <ChevronLeft className="slider-icon" size={24} />
      </button>
      <button className="slider-btn next" onClick={goToNext}>
        <ChevronRight className="slider-icon" size={24} />
      </button>
      <div className="slider-dots">
        {images.map((_, index) => (
          <button
            key={index}
            className={`dot ${index === currentIndex ? 'active' : ''}`}
            onClick={() => goToSlide(index)}
          />
        ))}
      </div>
    </div>
  )
}

export default ImageSlider

