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

/**
 * Hook that detects when an element is partially visible in the viewport
 * @param elementRef - Reference to the DOM element to observe
 * @returns boolean indicating if the element is partially visible in the viewport
 */
export const usePartiallyVisible = (elementRef: RefObject<HTMLElement | null>): boolean => {
    const [isPartiallyVisible, setIsPartiallyVisible] = useState<boolean>(false)

    useEffect(() => {
        const element = elementRef.current
        if (!element) return

        const observer = new IntersectionObserver(
            ([entry]) => {
                // Element is partially visible if it's intersecting but not completely visible
                const isPartial = entry.isIntersecting && entry.intersectionRatio < 1.0
                setIsPartiallyVisible(isPartial)
            },
            {
                root: null, // Use the viewport as the root
                threshold: [0, 1.0], // Check at these thresholds to determine partial visibility
            }
        )

        observer.observe(element)

        return () => {
            if (element) observer.unobserve(element)
        }
    }, [elementRef])

    return isPartiallyVisible
}
