import { useEffect, useRef, useState } from 'react';
import type { ComponentProps } from 'react';
import { cn } from '@/lib/utils';

type Props = ComponentProps<'div'> & {
    /** Delay before the element animates in, in milliseconds. */
    delay?: number;
};

/**
 * Fades and slides its children up the first time they scroll into view.
 * Users who prefer reduced motion see the content immediately.
 */
export default function Reveal({
    delay = 0,
    className,
    style,
    children,
    ...props
}: Props) {
    const elementRef = useRef<HTMLDivElement>(null);
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const element = elementRef.current;

        if (!element) {
            return;
        }

        const prefersReducedMotion = window.matchMedia(
            '(prefers-reduced-motion: reduce)',
        ).matches;

        if (prefersReducedMotion || !('IntersectionObserver' in window)) {
            setIsVisible(true);

            return;
        }

        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    setIsVisible(true);
                    observer.disconnect();
                }
            },
            { rootMargin: '0px 0px -10% 0px', threshold: 0.1 },
        );

        observer.observe(element);

        return () => observer.disconnect();
    }, []);

    return (
        <div
            ref={elementRef}
            className={cn(
                'transition-[opacity,translate] duration-700 ease-out motion-reduce:transition-none',
                isVisible
                    ? 'translate-y-0 opacity-100'
                    : 'translate-y-6 opacity-0',
                className,
            )}
            style={{ transitionDelay: `${delay}ms`, ...style }}
            {...props}
        >
            {children}
        </div>
    );
}
