import React, { useEffect, useRef, useState } from 'react'

interface Testimonial { text: string; author: string }

const testimonials: Testimonial[] = [
  { text: 'Esta probablemente sea la plataforma de transmisión más fácil de usar que conozco...', author: 'Bomeca Trotter' },
  { text: 'Uso AvanzaCast desde hace mucho tiempo y sigo eligiéndolo...', author: 'Krissy Buck' },
  { text: 'Hace dos años que uso este sistema y me encanta!', author: 'Joy Ann Lajeret' },
  { text: 'La integración con múltiples plataformas es perfecta...', author: 'Carlos Mendoza' },
  { text: 'Como creadora de contenido, necesitaba una herramienta confiable...', author: 'María González' }
]

export default function TestimonialsSection() {
  const scrollRef = useRef<HTMLDivElement | null>(null)
  const [isAutoPlay, setIsAutoPlay] = useState(true)
  const multiplier = 12
  const duplicatedTestimonials = Array.from({ length: multiplier }, () => testimonials).flat()

  const scrollLeft = () => { if (scrollRef.current) scrollRef.current.scrollBy({ left: -400, behavior: 'smooth' }) }
  const scrollRight = () => { if (scrollRef.current) scrollRef.current.scrollBy({ left: 400, behavior: 'smooth' }) }

  useEffect(() => {
    if (scrollRef.current) {
      const singleSetWidth = testimonials.length * 400
      const middleStart = singleSetWidth * Math.floor(multiplier / 2)
      scrollRef.current.scrollLeft = middleStart
    }
  }, [])

  useEffect(() => {
    if (!isAutoPlay || !scrollRef.current) return
    const interval = setInterval(() => scrollRight(), 4000)
    return () => clearInterval(interval)
  }, [isAutoPlay])

  useEffect(() => {
    let scrollTimeout: any
    const container = scrollRef.current
    const handleScroll = () => {
      if (!container) return
      const singleSetWidth = testimonials.length * 400
      const totalWidth = singleSetWidth * multiplier
      const middleStart = singleSetWidth * Math.floor(multiplier / 2)
      const tolerance = 100
      requestAnimationFrame(() => {
        if (container.scrollLeft <= tolerance) container.scrollLeft = middleStart
        else if (container.scrollLeft >= totalWidth - container.clientWidth - tolerance) container.scrollLeft = middleStart
      })
    }

    if (container) {
      const debounced = () => { clearTimeout(scrollTimeout); scrollTimeout = setTimeout(handleScroll, 150) }
      container.addEventListener('scroll', debounced, { passive: true })
      return () => { container.removeEventListener('scroll', debounced as any); clearTimeout(scrollTimeout) }
    }
  }, [])

  return (
    <section className="bg-white py-20">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
        <h2 className="text-3xl lg:text-5xl font-black text-gray-900 mb-16">
          Ya se crearon más de 60 millones de transmisiones y grabaciones en AvanzaCast
        </h2>

        <div className="relative w-full">
          <button onClick={scrollLeft} className="absolute left-4 top-1/2 -translate-y-1/2 z-10 w-12 h-12 rounded-full bg-white shadow-lg border border-gray-200 flex items-center justify-center hover:bg-gray-50 cursor-pointer transition-all">
            <svg className="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7"/></svg>
          </button>

          <button onClick={scrollRight} className="absolute right-4 top-1/2 -translate-y-1/2 z-10 w-12 h-12 rounded-full bg-white shadow-lg border border-gray-200 flex items-center justify-center hover:bg-gray-50 cursor-pointer transition-all">
            <svg className="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7"/></svg>
          </button>

          <div ref={scrollRef} className="flex space-x-8 overflow-x-auto scrollbar-hide carousel-smooth pb-4 px-16" onMouseEnter={() => setIsAutoPlay(false)} onMouseLeave={() => setIsAutoPlay(true)}>
            {duplicatedTestimonials.map((testimonial, index) => {
              const setNumber = Math.floor(index / testimonials.length)
              const itemIndex = index % testimonials.length
              return (
                <div key={`testimonial-set-${setNumber}-item-${itemIndex}-${testimonial.author}`} className="flex-shrink-0 w-80">
                  <div className="bg-gray-50 p-8 rounded-2xl h-full">
                    <p className="text-gray-700 italic mb-6 leading-relaxed text-sm">&ldquo;{testimonial.text}&rdquo;</p>
                    <p className="font-semibold text-gray-900">{testimonial.author}</p>
                  </div>
                </div>
              )
            })}
          </div>
        </div>

        <div className="flex justify-center space-x-4 mt-8">
          <button onClick={() => setIsAutoPlay(!isAutoPlay)} className="text-sm text-gray-500 hover:text-gray-700 flex items-center space-x-1 transition-colors">
            {isAutoPlay ? (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 9v6m4-6v6"/></svg>
                <span>Pausar auto-scroll</span>
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.828 14.828a4 4 0 01-5.656 0M9 10h1m4 0h1m-6 4h.01M15 14h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                <span>Reanudar auto-scroll</span>
              </>
            )}
          </button>
        </div>
      </div>
    </section>
  )
}
