import { useEffect, useRef, useState } from 'react';
import { Picture } from '@/site/components/media/picture';
import { useVisibility } from '@/site/hooks/use-in-view';
import { motionEnabled } from '@/site/lib/scroll-engine';
import type { Media } from '@/site/types';

/** Seconds each photo stays before the next one fades in. */
const HOLD = 8;

/**
 * Faint photos of the clinic behind the home page hero artwork
 * (media/home/backdrop-*). They fade into one another while each drifts
 * slowly closer (`.hero-photo` in site.css: opacity and transform only).
 *
 * Only the first photo is in the server HTML and loads right away; the
 * others are added once the page is running, so they never compete with
 * the first screen. Without motion the first photo simply stays.
 */
export function HeroBackdrop({ photos }: { photos: Media[] }) {
    const ref = useRef<HTMLDivElement>(null);
    const visible = useRef(true);
    const [all, setAll] = useState(false);

    useVisibility(ref, (isVisible) => {
        visible.current = isVisible;
    });

    // The other photos join after the first screen has settled.
    useEffect(() => {
        if (photos.length < 2 || !motionEnabled()) {
            return;
        }

        const timer = window.setTimeout(() => setAll(true), 2500);

        return () => window.clearTimeout(timer);
    }, [photos.length]);

    useEffect(() => {
        const root = ref.current;

        if (!all || !root) {
            return;
        }

        let index = 0;

        const interval = window.setInterval(() => {
            if (!visible.current || document.hidden) {
                return;
            }

            index = (index + 1) % root.children.length;

            Array.from(root.children).forEach((child, position) =>
                child.toggleAttribute('data-active', position === index),
            );
        }, HOLD * 1000);

        return () => window.clearInterval(interval);
    }, [all]);

    if (photos.length === 0) {
        return null;
    }

    return (
        <div
            ref={ref}
            aria-hidden="true"
            className="hero-photos absolute inset-0 overflow-hidden"
        >
            {(all ? photos : photos.slice(0, 1)).map((photo, index) => (
                <div
                    key={photo.src ?? index}
                    data-active={index === 0 ? '' : undefined}
                    className="hero-photo absolute inset-0"
                >
                    {/* Decoration: it yields to what the first paint needs. */}
                    <Picture
                        media={photo}
                        priority={index === 0 ? 'low' : false}
                    />
                </div>
            ))}
        </div>
    );
}
