'use client'

import { useState, useRef, useEffect } from 'react'
import * as motion from 'framer-motion/m'
import { ChevronLeft, ChevronRight, Sparkles, TrendingUp } from 'lucide-react'
import Link from 'next/link'
import type { HomeCategory } from '@/lib/db/queries/getHomeCategories'

const GRADIENTS = [
  'from-emerald-600 to-teal-700',
  'from-rose-600 to-red-700',
  'from-amber-700 to-orange-800',
  'from-orange-600 to-amber-800',
  'from-sky-600 to-blue-700',
  'from-purple-600 to-indigo-700',
  'from-amber-600 to-yellow-700',
]

interface CategoryCarouselClientProps {
  categories: HomeCategory[]
  // Pre-rendered per-category, not a function — functions can't cross the
  // Server -> Client Component boundary (not serializable as RSC props;
  // hit this exact bug building the hero carousel too).
  itemsCountLabels: string[]
  labels: {
    badge: string
    titlePrefix: string
    titleHighlight: string
    subtitle: string
    shopNow: string
    previous: string
    next: string
    scrollForMore: string
  }
}

// Client-only for the scroll/hover interactivity and framer-motion
// animations — data (categories, translated copy) is fetched server-side
// by CategoryCarousel.tsx, see DATA_FETCHING_PATTERN.md.
export default function CategoryCarouselClient({ categories, itemsCountLabels, labels }: CategoryCarouselClientProps) {
  const [scrollPosition, setScrollPosition] = useState(0)
  const [maxScroll, setMaxScroll] = useState(0)
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)
  const scrollContainerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const container = scrollContainerRef.current
    if (container) {
      const maxScrollValue = container.scrollWidth - container.clientWidth
      setMaxScroll(maxScrollValue)

      const handleWheel = (e: WheelEvent) => {
        if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
          e.preventDefault()
          container.scrollLeft += e.deltaY
        }
      }

      container.addEventListener('wheel', handleWheel, { passive: false })
      return () => container.removeEventListener('wheel', handleWheel)
    }
  }, [categories.length])

  if (categories.length === 0) return null

  const scroll = (direction: 'left' | 'right') => {
    if (scrollContainerRef.current) {
      const scrollAmount = 280
      const newPosition = direction === 'left'
        ? scrollPosition - scrollAmount
        : scrollPosition + scrollAmount

      scrollContainerRef.current.scrollTo({
        left: newPosition,
        behavior: 'smooth'
      })
      setScrollPosition(newPosition)
    }
  }

  const handleScroll = () => {
    if (scrollContainerRef.current) {
      setScrollPosition(scrollContainerRef.current.scrollLeft)
    }
  }

  return (
    <div className="my-16">
      {/* Header Section */}
      <div className="text-center mb-10">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          className="inline-flex items-center gap-2 bg-primary/10 px-4 py-2 rounded-full mb-4"
        >
          <Sparkles className="w-4 h-4 text-primary" />
          <span className="text-primary font-semibold text-sm uppercase tracking-wide">{labels.badge}</span>
        </motion.div>

        <motion.h2
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.1 }}
          className="text-3xl md:text-4xl font-bold text-gray-800 mb-2"
        >
          {labels.titlePrefix} <span className="text-primary bg-clip-text">{labels.titleHighlight}</span>
        </motion.h2>

        <motion.p
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2 }}
          className="text-gray-500 text-sm max-w-xl mx-auto"
        >
          {labels.subtitle}
        </motion.p>
      </div>

      {/* Carousel Container with Navigation */}
      <div className="relative group">
        {scrollPosition > 20 && (
          <button
            onClick={() => scroll('left')}
            className="absolute left-0 top-1/2 -translate-y-1/2 z-20 p-2 bg-white rounded-full shadow-lg hover:bg-primary hover:text-white transition-all duration-300 -translate-x-3 opacity-0 group-hover:opacity-100"
            aria-label={labels.previous}
          >
            <ChevronLeft size={20} />
          </button>
        )}

        {scrollPosition < maxScroll - 20 && (
          <button
            onClick={() => scroll('right')}
            className="absolute right-0 top-1/2 -translate-y-1/2 z-20 p-2 bg-white rounded-full shadow-lg hover:bg-primary hover:text-white transition-all duration-300 translate-x-3 opacity-0 group-hover:opacity-100"
            aria-label={labels.next}
          >
            <ChevronRight size={20} />
          </button>
        )}

        {/* Scrollable Container */}
        <div
          ref={scrollContainerRef}
          onScroll={handleScroll}
          className="overflow-x-auto scrollbar-hide scroll-smooth cursor-grab active:cursor-grabbing"
          style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
        >
          <div className="flex gap-5 pb-4 min-w-max px-1">
            {categories.map((category, index) => (
              <motion.div
                key={category.id}
                initial={{ opacity: 0, scale: 0.95 }}
                whileInView={{ opacity: 1, scale: 1 }}
                viewport={{ once: true }}
                transition={{ delay: index * 0.05 }}
                onHoverStart={() => setHoveredIndex(index)}
                onHoverEnd={() => setHoveredIndex(null)}
                className="w-50 md:w-55 shrink-0"
              >
                <Link href={`/category/${category.slug}`} className="block h-full">
                  <div className="relative h-full rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 group/card">
                    {/* Background Image with Gradient Overlay */}
                    <div className="absolute inset-0">
                      {category.imageUrl && (
                        <div
                          role="img"
                          aria-label={category.alt}
                          className="absolute inset-0 bg-cover bg-center transition-transform duration-500 group-hover/card:scale-110"
                          style={{
                            backgroundImage: `url(${category.imageUrl})`,
                            backgroundSize: 'cover',
                            backgroundPosition: 'center'
                          }}
                        />
                      )}
                      <div className={`absolute inset-0 bg-linear-to-br ${GRADIENTS[index % GRADIENTS.length]} opacity-75`} />
                    </div>

                    {/* Content */}
                    <div className="relative z-10 p-5 text-center min-h-65 flex flex-col justify-center">
                      <div>
                        <h3 className="text-xl font-bold text-white mb-3">
                          {category.name}
                        </h3>

                        <div className="w-12 h-px bg-white/30 mx-auto my-3" />

                        <div className="flex items-center justify-center gap-1 mb-4">
                          <TrendingUp size={12} className="text-white/70" />
                          <span className="text-xs text-white/90">{itemsCountLabels[index]}</span>
                        </div>

                        <motion.div
                          initial={{ opacity: 0, y: 10 }}
                          animate={{
                            opacity: hoveredIndex === index ? 1 : 0,
                            y: hoveredIndex === index ? 0 : 10
                          }}
                          transition={{ duration: 0.2 }}
                          className="inline-flex items-center gap-1 px-3 py-1.5 bg-white/20 backdrop-blur-sm rounded-full text-white text-xs font-semibold hover:bg-white/30 transition-all duration-300"
                        >
                          {labels.shopNow}
                          <ChevronRight size={12} />
                        </motion.div>
                      </div>
                    </div>
                  </div>
                </Link>
              </motion.div>
            ))}
          </div>
        </div>
      </div>

      {/* Scroll Indicator for Mobile */}
      {maxScroll > 0 && scrollPosition < maxScroll - 50 && (
        <div className="flex justify-center mt-6 md:hidden">
          <button
            onClick={() => scroll('right')}
            className="px-5 py-2 bg-primary/10 text-primary rounded-full text-sm font-medium flex items-center gap-2 hover:bg-primary hover:text-white transition-all duration-300"
          >
            {labels.scrollForMore} <ChevronRight size={14} />
          </button>
        </div>
      )}
    </div>
  )
}
