'use client'

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

interface HeroSliderProps {
  // Server-rendered slides (see HeroSlide.tsx). All stay in the DOM and
  // crossfade, so the first slide is in the initial HTML (LCP) and every
  // slide's text is indexable.
  children: React.ReactNode
  labels: {
    previous: string
    next: string
    // "Slide 2 of 4", pre-rendered per slide (functions can't cross the
    // server -> client boundary)
    slide: string[]
    carousel: string
  }
  className?: string
  autoplayMs?: number
  // Visual style of the controls, per homepage design
  controls?: 'bars' | 'dots' | 'numbers'
  // Where the controls sit
  controlsPosition?: 'bottom-start' | 'bottom-center' | 'bottom-end'
}

export default function HeroSlider({
  children,
  labels,
  className = '',
  autoplayMs = 6500,
  controls = 'bars',
  controlsPosition = 'bottom-start',
}: HeroSliderProps) {
  const slides = Children.toArray(children)
  const count = slides.length
  const [index, setIndex] = useState(0)
  const [paused, setPaused] = useState(false)
  const [reducedMotion, setReducedMotion] = useState(false)
  const pointerStart = useRef<{ x: number; y: number } | null>(null)
  const rootRef = useRef<HTMLDivElement>(null)

  const go = useCallback((next: number) => setIndex(((next % count) + count) % count), [count])
  const next = useCallback(() => go(index + 1), [go, index])
  const prev = useCallback(() => go(index - 1), [go, index])

  useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)')
    const update = () => setReducedMotion(mq.matches)
    update()
    mq.addEventListener('change', update)
    return () => mq.removeEventListener('change', update)
  }, [])

  // Don't advance while the tab is in the background.
  useEffect(() => {
    const onVisibility = () => setPaused(document.hidden)
    document.addEventListener('visibilitychange', onVisibility)
    return () => document.removeEventListener('visibilitychange', onVisibility)
  }, [])

  const autoplay = count > 1 && !paused && !reducedMotion
  useEffect(() => {
    if (!autoplay) return
    const timer = window.setTimeout(next, autoplayMs)
    return () => window.clearTimeout(timer)
  }, [autoplay, autoplayMs, next, index])

  const isRtl = () => rootRef.current?.closest('[dir]')?.getAttribute('dir') === 'rtl'

  const onKeyDown = (e: React.KeyboardEvent) => {
    if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return
    e.preventDefault()
    const forward = (e.key === 'ArrowRight') !== isRtl()
    if (forward) next()
    else prev()
  }

  const onPointerDown = (e: React.PointerEvent) => {
    pointerStart.current = { x: e.clientX, y: e.clientY }
  }
  const onPointerUp = (e: React.PointerEvent) => {
    const start = pointerStart.current
    pointerStart.current = null
    if (!start) return
    const dx = e.clientX - start.x
    const dy = e.clientY - start.y
    if (Math.abs(dx) < 50 || Math.abs(dx) < Math.abs(dy)) return
    // Swiping toward the reading direction's start goes forward.
    const forward = dx < 0 !== isRtl()
    if (forward) next()
    else prev()
  }

  const controlsAlign =
    controlsPosition === 'bottom-center' ? 'justify-center' : controlsPosition === 'bottom-end' ? 'justify-end' : 'justify-start'

  if (count === 0) return null

  return (
    <div
      ref={rootRef}
      role="region"
      aria-roledescription="carousel"
      aria-label={labels.carousel}
      tabIndex={count > 1 ? 0 : -1}
      onKeyDown={count > 1 ? onKeyDown : undefined}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)}
      onBlur={(e) => {
        if (!e.currentTarget.contains(e.relatedTarget as Node)) setPaused(false)
      }}
      onPointerDown={count > 1 ? onPointerDown : undefined}
      onPointerUp={count > 1 ? onPointerUp : undefined}
      className={`group/slider relative overflow-hidden outline-none focus-visible:ring-2 focus-visible:ring-primary touch-pan-y ${className}`}
    >
      {slides.map((slide, i) => {
        const active = i === index
        return (
          <div
            key={i}
            role="group"
            aria-roledescription="slide"
            aria-label={labels.slide[i]}
            aria-hidden={!active}
            inert={!active}
            data-active={active}
            className={`home-slide absolute inset-0 transition-opacity duration-1000 ease-out ${
              active ? 'opacity-100 z-10' : 'opacity-0 z-0'
            }`}
          >
            {slide}
          </div>
        )
      })}

      {count > 1 && (
        <>
          <button
            type="button"
            onClick={prev}
            aria-label={labels.previous}
            className="absolute start-3 sm:start-5 top-1/2 -translate-y-1/2 z-20 hidden sm:flex h-11 w-11 items-center justify-center rounded-full bg-white/85 text-gray-900 shadow-lg backdrop-blur transition-all duration-300 opacity-0 group-hover/slider:opacity-100 focus-visible:opacity-100 hover:bg-white hover:scale-105"
          >
            <ChevronLeft size={22} className="rtl:rotate-180" />
          </button>
          <button
            type="button"
            onClick={next}
            aria-label={labels.next}
            className="absolute end-3 sm:end-5 top-1/2 -translate-y-1/2 z-20 hidden sm:flex h-11 w-11 items-center justify-center rounded-full bg-white/85 text-gray-900 shadow-lg backdrop-blur transition-all duration-300 opacity-0 group-hover/slider:opacity-100 focus-visible:opacity-100 hover:bg-white hover:scale-105"
          >
            <ChevronRight size={22} className="rtl:rotate-180" />
          </button>

          <div className={`absolute inset-x-0 bottom-4 sm:bottom-6 z-20 flex ${controlsAlign} px-6 sm:px-10 lg:px-16`}>
            <div className="flex items-center gap-2">
              {slides.map((_, i) => {
                const active = i === index
                if (controls === 'dots') {
                  return (
                    <button
                      key={i}
                      type="button"
                      onClick={() => go(i)}
                      aria-label={labels.slide[i]}
                      aria-current={active}
                      className={`h-2 rounded-full transition-all duration-500 ${active ? 'w-8 bg-white' : 'w-2 bg-white/50 hover:bg-white/80'}`}
                    />
                  )
                }
                if (controls === 'numbers') {
                  return (
                    <button
                      key={i}
                      type="button"
                      onClick={() => go(i)}
                      aria-label={labels.slide[i]}
                      aria-current={active}
                      className={`group/num flex items-center gap-2 text-xs font-semibold tabular-nums transition-colors ${active ? 'text-white' : 'text-white/55 hover:text-white'}`}
                    >
                      {String(i + 1).padStart(2, '0')}
                      <span className="relative block h-px w-10 overflow-hidden bg-white/30">
                        {active && (
                          <span
                            key={`${index}-${paused}`}
                            className="home-progress absolute inset-0 bg-white"
                            style={{ animationDuration: `${autoplayMs}ms`, animationPlayState: autoplay ? 'running' : 'paused' }}
                          />
                        )}
                      </span>
                    </button>
                  )
                }
                return (
                  <button
                    key={i}
                    type="button"
                    onClick={() => go(i)}
                    aria-label={labels.slide[i]}
                    aria-current={active}
                    className="relative h-1.5 w-10 sm:w-14 overflow-hidden rounded-full bg-white/35 backdrop-blur transition-colors hover:bg-white/60"
                  >
                    {active && (
                      <span
                        key={`${index}-${paused}`}
                        className="home-progress absolute inset-0 rounded-full bg-white"
                        style={{ animationDuration: `${autoplayMs}ms`, animationPlayState: autoplay ? 'running' : 'paused' }}
                      />
                    )}
                  </button>
                )
              })}
            </div>
          </div>
        </>
      )}
    </div>
  )
}
