import { useEffect, useRef } from 'react';
import type { RefObject } from 'react';
import { cx } from '@/site/lib/cx';
import type { LineClock } from '@/site/lib/line-field';
import { motionEnabled } from '@/site/lib/scroll-engine';

type Connection = { saveData?: boolean };

/**
 * Canvas of the "morphing lines" (lib/line-field.ts): the drawing of the
 * home page's process scene. It renders nothing on the server and stays
 * transparent until its first frame is drawn — until then, and for good
 * with reduced motion, in data-saver mode or without a 2D canvas, the scene
 * shows the step drawings instead.
 *
 * The code is fetched only when the scene comes near, and then only once
 * the page is idle. `clock` is the scene's state, read once per frame.
 */
export function LineField({
    clock,
    className,
}: {
    clock: RefObject<LineClock>;
    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;
        let waiting = 0;

        const idles = typeof window.requestIdleCallback === 'function';

        const begin = () => {
            void import('@/site/lib/line-field').then(({ startLineField }) => {
                if (!cancelled) {
                    stop = startLineField(canvas, () => clock.current);
                }
            });
        };

        // A canvas that is not displayed (the static form of the scene)
        // never comes near: nothing is loaded for it.
        const observer = new IntersectionObserver(
            ([entry]) => {
                if (!entry.isIntersecting) {
                    return;
                }

                observer.disconnect();
                // (Safari has no requestIdleCallback: a short timer stands in for it.)
                waiting = idles
                    ? window.requestIdleCallback(begin, { timeout: 1500 })
                    : window.setTimeout(begin, 300);
            },
            { rootMargin: '150% 0px' },
        );

        observer.observe(canvas);

        return () => {
            cancelled = true;
            observer.disconnect();

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

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

    return (
        <canvas
            ref={ref}
            aria-hidden="true"
            className={cx('line-field', className)}
        />
    );
}
