'use client'

import { useEffect } from 'react'

export function ScrollReveal() {
  useEffect(() => {
    const items = Array.from(document.querySelectorAll<HTMLElement>('[data-reveal]'))
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches

    if (prefersReducedMotion) {
      items.forEach((item) => item.classList.add('is-visible'))
      return
    }

    document.querySelectorAll<HTMLElement>('[data-reveal-group]').forEach((group) => {
      const children = Array.from(group.querySelectorAll<HTMLElement>('[data-reveal]'))
      children.forEach((child, index) => {
        if (!child.style.transitionDelay) child.style.transitionDelay = `${Math.min(index * 80, 320)}ms`
      })
    })

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('is-visible')
            observer.unobserve(entry.target)
          }
        })
      },
      { rootMargin: '0px 0px -12% 0px', threshold: 0.12 },
    )

    items.forEach((item) => observer.observe(item))
    return () => observer.disconnect()
  }, [])

  return null
}
