'use client'

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

type Props = {
  children: React.ReactNode
  intervalMs?: number
  behavior?: ScrollBehavior
  inline?: 'start' | 'center'
  classNames?: string
}

export default function HorizontalAutoScroll({
  children,
  intervalMs = 3000,
  behavior = 'smooth',
  inline = 'start', // 'start' aligns to left edge, 'center' aligns to middle
  classNames
}: Props) {
  const containerRef = useRef<HTMLDivElement>(null)
  const intervalRef = useRef<number | undefined>(undefined)
  const isUserScrolling = useRef(false)
  const scrollTimeout = useRef<number | undefined>(undefined)

  useEffect(() => {
    const container = containerRef.current
    if (!container) return
    
    // --- START: FIX FOR NESTED CHILDREN ---
    // 1. Get the immediate wrapper child (e.g., the div with 'flex gap-6')
    const wrapper = container.firstElementChild
    if (!wrapper) return

    // 2. Get all card elements from the wrapper's children
    const cards = Array.from(wrapper.children) as HTMLElement[]
    if (!cards.length) return
    // --- END: FIX FOR NESTED CHILDREN ---

    const scrollNext = () => {
      if (isUserScrolling.current) return

      const containerRect = container.getBoundingClientRect()
      const containerCenter = containerRect.left + containerRect.width / 2

      // 1. Find the index of the card currently closest to the "focus point"
      let closestIndex = 0
      let minDistance = Number.MAX_VALUE

      cards.forEach((card, index) => {
        const cardRect = card.getBoundingClientRect()
        
        // If inline='start', check distance to left edge. 
        // If inline='center', check distance to center.
        let distance: number
        
        if (inline === 'center') {
          const cardCenter = cardRect.left + cardRect.width / 2
          distance = Math.abs(containerCenter - cardCenter)
        } else {
          // For 'start', we compare card left to container left
          distance = Math.abs(containerRect.left - cardRect.left)
        }

        if (distance < minDistance) {
          minDistance = distance
          closestIndex = index
        }
      })

      // 2. Determine next card index
      const nextIndex = (closestIndex + 1) % cards.length
      const nextCard = cards[nextIndex]
      if (!nextCard) return

      // 3. Calculate EXACT scroll position using getBoundingClientRect
      // This accounts for margins, padding, and variable widths automatically.
      const nextCardRect = nextCard.getBoundingClientRect()
      const currentScrollLeft = container.scrollLeft
      
      let scrollAmount = 0

      if (inline === 'center') {
        // Calculate difference between card center and container center
        const cardCenter = nextCardRect.left + nextCardRect.width / 2
        const diff = cardCenter - containerCenter
        scrollAmount = currentScrollLeft + diff
      } else {
        // 'start': Calculate difference between card left and container left
        // We subtract the container left to zero it out relative to viewport
        const diff = nextCardRect.left - containerRect.left
        scrollAmount = currentScrollLeft + diff
      }

      // 4. Scroll the container
      container.scrollTo({
        left: scrollAmount,
        behavior: behavior,
      })
    }

    const startScrolling = () => {
      if (intervalRef.current !== undefined) return
      intervalRef.current = window.setInterval(scrollNext, intervalMs)
    }

    const stopScrolling = () => {
      if (intervalRef.current !== undefined) {
        window.clearInterval(intervalRef.current)
        intervalRef.current = undefined
      }
    }

    const onUserScroll = () => {
      isUserScrolling.current = true
      if (scrollTimeout.current !== undefined) clearTimeout(scrollTimeout.current)
      scrollTimeout.current = window.setTimeout(() => {
        isUserScrolling.current = false
      }, 2000)
    }

    container.addEventListener('mouseenter', stopScrolling)
    container.addEventListener('mouseleave', startScrolling)
    container.addEventListener('wheel', onUserScroll, { passive: true })
    container.addEventListener('touchstart', onUserScroll, { passive: true })
    container.addEventListener('touchmove', onUserScroll, { passive: true })

    startScrolling()

    return () => {
      stopScrolling()
      container.removeEventListener('mouseenter', stopScrolling)
      container.removeEventListener('mouseleave', startScrolling)
      container.removeEventListener('wheel', onUserScroll)
      container.removeEventListener('touchstart', onUserScroll)
      container.removeEventListener('touchmove', onUserScroll)
    }
  }, [intervalMs, behavior, inline, children])

  return (
    <div
      ref={containerRef}
      className={classNames}
    >
      {children}
    </div>
  )
}