import React, { useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'

interface Feature {
  icon: string
  title: string
  description: string
}

const features: Feature[] = [
  { icon: '/images/carousel_recording.svg', title: 'Recording', description: 'Graba contenido de alta calidad' },
  { icon: '/images/carousel_streaming.svg', title: 'Streaming', description: 'Transmite en vivo a múltiples plataformas' },
  { icon: '/images/carousel_guests.svg', title: 'Guests', description: 'Invita colaboradores fácilmente' },
  { icon: '/images/carousel_branding.svg', title: 'Branding', description: 'Personaliza tu transmisión' },
  { icon: '/images/carousel_engagement.svg', title: 'Engagement', description: 'Interactúa con tu audiencia' },
  { icon: '/images/carousel_podcasts.svg', title: 'Podcasts', description: 'Crea podcasts profesionales' },
  { icon: '/images/carousel_repurpose.svg', title: 'Repurpose', description: 'Reutiliza tu contenido' }
]

export default function FeaturesCarousel() {
  const scrollRef = useRef<HTMLDivElement | null>(null)
  const multiplier = 12
  const duplicatedFeatures = Array.from({ length: multiplier }, () => features).flat()

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

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

  useEffect(() => {
    let scrollTimeout: any
    const container = scrollRef.current
    const handleScroll = () => {
      if (!container) return
      const singleSetWidth = features.length * (288 + 24)
      const totalWidth = singleSetWidth * multiplier
      const middleStart = singleSetWidth * Math.floor(multiplier / 2)
      const tolerance = 50
      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-gray-50 py-16 w-full">
      <div className="w-full">
        <div className="text-center mb-12 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
          <p className="text-gray-600 mb-8">
            AvanzaCast es un estudio profesional para grabar y hacer transmisiones en vivo desde tu
            navegador. Graba contenido o transmite en vivo a Facebook, YouTube y otras plataformas.
          </p>
        </div>

        <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-6 overflow-x-auto scrollbar-hide carousel-smooth pb-4 px-16">
            {duplicatedFeatures.map((feature, index) => {
              const setNumber = Math.floor(index / features.length)
              const itemIndex = index % features.length
              return (
                <div key={`set-${setNumber}-item-${itemIndex}-${feature.title}`} className="flex-shrink-0 w-72">
                  <Link to="/auth/register" className="block group hover:scale-105 transition-transform duration-200">
                    <div className="bg-white rounded-2xl p-6 text-center shadow-sm hover:shadow-lg transition-all duration-200 border border-gray-100 hover:border-blue-200">
                      <div className="mb-6 overflow-hidden rounded-xl">
                        <img src={feature.icon} alt={feature.title} className="w-full h-40 object-cover group-hover:scale-110 transition-transform duration-300" />
                      </div>
                      <h5 className="font-bold text-gray-900 text-lg mb-2 group-hover:text-blue-600 transition-colors">{feature.title}</h5>
                    </div>
                  </Link>
                </div>
              )
            })}
          </div>
        </div>
      </div>
    </section>
  )
}
