import { RefObject, useCallback, useEffect } from 'react'

export function useStickyHeader(
	scrollContainerRef: RefObject<HTMLDivElement | null>,
	headerRef: RefObject<HTMLTableSectionElement | null>
) {
	const handleScroll = useCallback(() => {
		const container = scrollContainerRef.current
		const header = headerRef.current

		if (!container || !header) return

		const scrollTop = container.scrollTop
		header.style.transform = `translateY(${scrollTop ? scrollTop - 1 : scrollTop}px)`
		header.style.position = 'relative'
		header.style.zIndex = '10'
	}, [scrollContainerRef, headerRef])

	useEffect(() => {
		const container = scrollContainerRef.current
		if (!container) return

		container.addEventListener('scroll', handleScroll, { passive: true })

		return () => {
			container.removeEventListener('scroll', handleScroll)
			const header = headerRef.current
			if (header) {
				header.style.transform = ''
				header.style.position = ''
				header.style.zIndex = ''
			}
		}
	}, [handleScroll, headerRef])
}
