import { useEffect, useRef } from 'react';
import { cx } from '@/site/lib/cx';
import { motionEnabled } from '@/site/lib/scroll-engine';

type Connection = { saveData?: boolean };

/**
 * Canvas of the "living contours" backdrop (lib/hero-field.ts). It renders
 * nothing on the server and stays transparent until the first frame is
 * drawn, so whatever sits underneath (the aurora) is what a visitor sees
 * first — and all they see without WebGL, with reduced motion or in
 * data-saver mode.
 *
 * `ground` (0–1) is how opaque the field is between its lines: below 1 the
 * photo underneath stays faintly visible.
 */
export function HeroField({
    ground = 1,
    className,
}: {
    ground?: number;
    className?: string;
}) {
    const ref = useRef<HTMLCanvasElement>(null);

    useEffect(() => {
        const canvas = ref.current;
        const connection = (
            navigator as Navigator & { connection?: Connection }
        ).connection;

        if (!canvas || !motionEnabled() || connection?.saveData) {
            return;
        }

        let stop: (() => void) | null = null;
        let cancelled = false;

        // How far the hero has scrolled out of view (read once per frame).
        const scroll = () =>
            Math.min(
                1,
                Math.max(0, window.scrollY / (window.innerHeight || 1)),
            );

        const begin = () => {
            void import('@/site/lib/hero-field').then(({ startHeroField }) => {
                if (!cancelled) {
                    stop = startHeroField(canvas, scroll, ground);
                }
            });
        };

        // Decoration waits until the page itself is done. (Safari has no
        // requestIdleCallback: a short timer stands in for it.)
        const idles = typeof window.requestIdleCallback === 'function';
        const waiting = idles
            ? window.requestIdleCallback(begin, { timeout: 2500 })
            : window.setTimeout(begin, 800);

        return () => {
            cancelled = true;

            if (idles) {
                window.cancelIdleCallback(waiting);
            } else {
                window.clearTimeout(waiting);
            }

            stop?.();
        };
    }, [ground]);

    return (
        <canvas
            ref={ref}
            aria-hidden="true"
            className={cx('hero-field absolute inset-0 size-full', className)}
        />
    );
}
