import { useRef } from 'react';
import type { CSSProperties, ElementType, ReactNode } from 'react';
import { useReveal } from '@/site/hooks/use-in-view';

type RevealProps = {
    children: ReactNode;
    /** Element to render. Defaults to a div. */
    as?: ElementType;
    /** Delay in milliseconds — use it to stagger siblings. */
    delay?: number;
    /** Vertical travel, e.g. 40 or '2rem'. Defaults to 1.75rem. */
    y?: number | string;
    /** Horizontal travel. */
    x?: number | string;
    /** Starting scale, e.g. 0.96. */
    scale?: number;
    className?: string;
    style?: CSSProperties;
};

const length = (value: number | string): string =>
    typeof value === 'number' ? `${value}px` : value;

/**
 * Fades and slides its content in the first time it enters the viewport.
 * Without JavaScript or with reduced motion the content is simply visible.
 * Do not use it for the first screen of a page — use the `hero-rise` class
 * there so the content never waits for JavaScript.
 */
export function Reveal({
    children,
    as: Tag = 'div',
    delay,
    y,
    x,
    scale,
    className,
    style,
}: RevealProps) {
    const ref = useRef<HTMLElement>(null);

    useReveal(ref);

    return (
        <Tag
            ref={ref}
            data-reveal=""
            className={className}
            style={
                {
                    ...style,
                    ...(delay ? { '--reveal-delay': `${delay}ms` } : null),
                    ...(y !== undefined ? { '--reveal-y': length(y) } : null),
                    ...(x !== undefined ? { '--reveal-x': length(x) } : null),
                    ...(scale !== undefined
                        ? { '--reveal-scale': scale }
                        : null),
                } as CSSProperties
            }
        >
            {children}
        </Tag>
    );
}
