import {
    useCallback,
    useEffect,
    useEffectEvent,
    useRef,
    useState,
} from 'react';
import { useOnEnter } from '@/site/hooks/use-in-view';
import { useShared } from '@/site/hooks/use-shared';
import { useT } from '@/site/i18n';
import { loadTurnstile } from '@/site/lib/turnstile';

type TurnstileProps = {
    /** Public key of the widget (App\Support\Turnstile). */
    siteKey: string;
    /** Receives the token once the check passes, and '' when it lapses. */
    onToken: (token: string) => void;
    error?: string;
    errorId: string;
    className?: string;
};

/**
 * Cloudflare Turnstile ("I am not a robot") inside a request form.
 *
 * Nothing is requested from Cloudflare until the form comes close to the
 * viewport, and the widget's height is reserved beforehand so the form
 * does not jump when it appears. A token is accepted once: to ask for a
 * new check, mount the component again (give it a new `key`).
 */
export function Turnstile({
    siteKey,
    onToken,
    error,
    errorId,
    className,
}: TurnstileProps) {
    const { locale } = useShared();
    const t = useT();
    const ref = useRef<HTMLDivElement>(null);
    const [near, setNear] = useState(false);
    const [unavailable, setUnavailable] = useState(false);

    const approach = useCallback(() => setNear(true), []);
    const emit = useEffectEvent((token: string) => onToken(token));

    useOnEnter(ref, approach, '0px 0px 30% 0px');

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

        if (!near || !container) {
            return;
        }

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

        loadTurnstile().then(
            (api) => {
                if (cancelled) {
                    return;
                }

                const id = api.render(container, {
                    sitekey: siteKey,
                    language: locale,
                    theme: 'light',
                    size: 'flexible',
                    callback: (token) => emit(token),
                    'expired-callback': () => emit(''),
                    'timeout-callback': () => emit(''),
                    // The widget shows the problem itself; no console noise.
                    'error-callback': () => {
                        emit('');

                        return true;
                    },
                });

                if (id) {
                    remove = () => api.remove(id);
                }
            },
            () => {
                if (!cancelled) {
                    setUnavailable(true);
                }
            },
        );

        return () => {
            cancelled = true;
            remove?.();
        };
    }, [near, siteKey, locale]);

    return (
        <div className={className}>
            {/* Turnstile draws into this box; React leaves it empty. Its frame
                is 65px tall; line-height 0 keeps the inline frame from adding
                a gap below it, so the reserved height is exact. */}
            <div
                ref={ref}
                role="group"
                aria-label={t.contact.form.robot}
                className="min-h-[65px] leading-[0]"
            />
            {unavailable ? (
                <p className="text-danger mt-2 text-sm">
                    {t.contact.form.robotUnavailable}
                </p>
            ) : null}
            {error ? (
                <p id={errorId} className="text-danger mt-2 text-sm">
                    {error}
                </p>
            ) : null}
        </div>
    );
}
