'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'

interface ScrollRowProps {
  // Server-rendered items; each should size itself (e.g. w-36 shrink-0).
  children: React.ReactNode
  labels: { previous: string; next: string }
  className?: string
}

// One horizontal row that scrolls (touch swipe / trackpad / arrow buttons),
// with scroll-snap. The arrows only show when there's more to scroll that
// way, and flip in RTL (scrollLeft is negative there).
export default function ScrollRow({ children, labels, className = '' }: ScrollRowProps) {
  const trackRef = useRef<HTMLDivElement>(null)
  const [canPrev, setCanPrev] = useState(false)
  const [canNext, setCanNext] = useState(false)

  const update = useCallback(() => {
    const el = trackRef.current
    if (!el) return
    const max = el.scrollWidth - el.clientWidth
    const pos = Math.abs(el.scrollLeft)
    setCanPrev(pos > 4)
    setCanNext(pos < max - 4)
  }, [])

  useEffect(() => {
    const el = trackRef.current
    if (!el) return
    update()
    el.addEventListener('scroll', update, { passive: true })
    const observer = new ResizeObserver(update)
    observer.observe(el)
    return () => {
      el.removeEventListener('scroll', update)
      observer.disconnect()
    }
  }, [update])

  const scrollBy = (direction: 1 | -1) => {
    const el = trackRef.current
    if (!el) return
    const rtl = getComputedStyle(el).direction === 'rtl'
    el.scrollBy({ left: direction * el.clientWidth * 0.85 * (rtl ? -1 : 1), behavior: 'smooth' })
  }

  const arrow =
    'absolute top-1/2 -translate-y-1/2 z-10 hidden sm:flex h-11 w-11 items-center justify-center rounded-full bg-white text-dark shadow-lg ring-1 ring-black/5 transition-all hover:scale-105 hover:text-primary disabled:opacity-0 disabled:pointer-events-none'

  return (
    <div className={`relative ${className}`}>
      <div
        ref={trackRef}
        className="-mx-4 px-4 sm:mx-0 sm:px-0 flex gap-3 sm:gap-4 overflow-x-auto snap-x snap-mandatory scroll-smooth py-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
      >
        {children}
      </div>
      <button type="button" onClick={() => scrollBy(-1)} disabled={!canPrev} aria-label={labels.previous} className={`${arrow} -start-5`}>
        <ChevronLeft size={20} className="rtl:rotate-180" />
      </button>
      <button type="button" onClick={() => scrollBy(1)} disabled={!canNext} aria-label={labels.next} className={`${arrow} -end-5`}>
        <ChevronRight size={20} className="rtl:rotate-180" />
      </button>
    </div>
  )
}
