'use client'

import { useLayoutEffect, useRef, type ReactNode } from 'react'
import { usePathname } from 'next/navigation'
import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { ScrollSmoother } from 'gsap/ScrollSmoother'

export function SmoothScroll({ children }: { children: ReactNode }) {
  const wrapperRef = useRef<HTMLDivElement>(null)
  const contentRef = useRef<HTMLDivElement>(null)
  const pathname = usePathname()

  useLayoutEffect(() => {
    gsap.registerPlugin(ScrollTrigger, ScrollSmoother)
    const wrapper = wrapperRef.current
    const content = contentRef.current
    if (!wrapper || !content) return

    const media = gsap.matchMedia()
    media.add('(min-width: 1024px) and (prefers-reduced-motion: no-preference)', () => {
      const smoother = ScrollSmoother.create({
        wrapper,
        content,
        smooth: 0.7,
        smoothTouch: false,
        effects: false,
      })

      ScrollTrigger.refresh()
      return () => {
        smoother.kill()
      }
    })
    return () => media.revert()
  }, [pathname])

  return (
    <div ref={wrapperRef} id='smooth-wrapper'>
      <div ref={contentRef} id='smooth-content'>
        {children}
      </div>
    </div>
  )
}