import { useCallback, useRef } from 'react';
import { useVisibility } from '@/site/hooks/use-in-view';
import { cx } from '@/site/lib/cx';
import { motionEnabled } from '@/site/lib/scroll-engine';
import type { Media } from '@/site/types';
import { Picture } from './picture';

type LazyVideoProps = {
    media: Media;
    /** Passed on to the poster image (see Picture). */
    priority?: boolean;
    className?: string;
};

/**
 * A silent, looping background video that costs nothing until it is seen:
 * nothing is downloaded before it scrolls into view, it pauses when it
 * leaves, and with "reduce motion" (or when the browser refuses autoplay)
 * only the poster image is shown.
 *
 * The poster is a normal image underneath the video, so it can be the LCP
 * element; the video fades in over it once it actually plays.
 */
export function LazyVideo({ media, priority, className }: LazyVideoProps) {
    const ref = useRef<HTMLVideoElement>(null);

    const onVisibility = useCallback((visible: boolean) => {
        const video = ref.current;

        if (!video) {
            return;
        }

        if (!visible) {
            video.pause();

            return;
        }

        if (motionEnabled()) {
            // Refused autoplay (data saver, low power) simply leaves the poster.
            video.play().catch(() => undefined);
        }
    }, []);

    useVisibility(ref, onVisibility);

    return (
        <div className="relative size-full">
            <Picture media={media} priority={priority} className={className} />
            <video
                ref={ref}
                muted
                loop
                playsInline
                preload="none"
                aria-label={media.alt || undefined}
                aria-hidden={media.alt ? undefined : true}
                width={media.width ?? undefined}
                height={media.height ?? undefined}
                onPlaying={(event) =>
                    event.currentTarget.setAttribute('data-playing', '')
                }
                className={cx(
                    'absolute inset-0 size-full object-cover opacity-0 transition-opacity duration-700 data-[playing]:opacity-100',
                    className,
                )}
            >
                {media.sources.map((source) => (
                    <source
                        key={source.src}
                        src={source.src}
                        type={source.type}
                    />
                ))}
            </video>
        </div>
    );
}
