'use client'

import React, { useEffect, useRef, useState } from 'react'
import { motion, MotionValue, useScroll, useSpring, useTransform } from 'framer-motion'

export interface Props {
  children: React.ReactNode[]
  className?: string
  cardGap?: number
  onActiveIndexChange?: (idx: number) => void
}

interface StickyStackCardInnerProps {
  idx: number
  cardGap: number
  children: React.ReactNode
  innerRef?: (el: HTMLDivElement | null) => void
  isDimmed: boolean
}

export const StickyStackCards: React.FC<Props> = ({
  children,
  className = '',
  cardGap = 16,
  onActiveIndexChange,
}) => {
  const containerRef = useRef<HTMLDivElement>(null)

  const cardCount = React.Children.count(children)

  const { cardRefs, activeIdx } = useActiveCardIndex(cardCount)
  useEffect(() => {
    if (onActiveIndexChange) onActiveIndexChange(activeIdx)
  }, [activeIdx])

  return (
    <div
      ref={containerRef}
      className={`relative ${className || ''}`}
      style={{ minHeight: '100vh' }}
    >
      {React.Children.toArray(children).map((child, idx, arr) => {
        const total = arr.length
        return (
          <StickyStackCardInner
            key={idx}
            idx={idx}
            innerRef={(el) => (cardRefs.current[idx] = el)}
            isDimmed={idx < activeIdx}
            cardGap={cardGap}
          >
            {child}
          </StickyStackCardInner>
        )
      })}
    </div>
  )
}

// --- Хук для активного индекса ---
function useActiveCardIndex(cardCount: number) {
  const cardRefs = useRef<(HTMLDivElement | null)[]>([])
  const [activeIdx, setActiveIdx] = useState(0)

  useEffect(() => {
    function onScroll() {
      let foundIdx = 0
      for (let i = 0; i < cardRefs.current.length; i++) {
        const ref = cardRefs.current[i]
        if (!ref) continue
        const rect = ref.getBoundingClientRect()
        const triggerY = window.innerHeight * 0.35
        if (rect.top < triggerY) {
          foundIdx = i
        } else {
          break
        }
      }
      setActiveIdx(foundIdx)
    }
    window.addEventListener('scroll', onScroll, { passive: true })
    onScroll()
    return () => window.removeEventListener('scroll', onScroll)
  }, [])

  return { cardRefs, activeIdx }
}

const StickyStackCardInner: React.FC<StickyStackCardInnerProps> = ({
  idx,
  children,
  innerRef,
  isDimmed,
  cardGap,
}) => {
  const localRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    if (innerRef) innerRef(localRef.current)
  }, [innerRef])

  return (
    <motion.div
      ref={localRef}
      style={{
        transform: `translateY(${idx * cardGap}px)`,
      }}
      animate={{
        filter: isDimmed ? 'brightness(0.8)' : 'brightness(1)',
      }}
      transition={{
        duration: 0.5,
        ease: [0.4, 0, 0.2, 1],
      }}
      className={'flex justify-center items-start sticky top-[96px] '}
    >
      <div className="h-fit w-full">{children}</div>
    </motion.div>
  )
}

export default StickyStackCards
