import { useEffect, useRef } from 'react';

const SITE_KEY = import.meta.env.VITE_TURNSTILE_SITE_KEY as string | undefined;

/**
 * TurnstileWidget — drop-in component untuk form yang tidak expose onSubmit.
 *
 * Render <div> widget + <input type="hidden" name="cf_turnstile_response">.
 * Inertia <Form> otomatis include hidden input saat POST.
 *
 * Tidak render apapun jika VITE_TURNSTILE_SITE_KEY kosong (dev bypass).
 */
export function TurnstileWidget({ className }: { className?: string }) {
    const containerRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);
    const widgetId = useRef<string | null>(null);

    useEffect(() => {
        if (!SITE_KEY) return;

        const SCRIPT_ID = 'cf-turnstile-script';
        if (!document.getElementById(SCRIPT_ID)) {
            const script = document.createElement('script');
            script.id = SCRIPT_ID;
            script.src =
                'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
            script.async = true;
            document.head.appendChild(script);
        }

        const render = () => {
            if (!containerRef.current || widgetId.current) return;
            if (typeof (window as any).turnstile === 'undefined') return;

            widgetId.current = (window as any).turnstile.render(
                containerRef.current,
                {
                    sitekey: SITE_KEY,
                    theme: 'light',
                    size: 'normal',
                    callback: (token: string) => {
                        if (inputRef.current) inputRef.current.value = token;
                    },
                    'expired-callback': () => {
                        if (inputRef.current) inputRef.current.value = '';
                    },
                    'error-callback': () => {
                        if (inputRef.current) inputRef.current.value = '';
                    },
                },
            );
        };

        const interval = setInterval(() => {
            if (typeof (window as any).turnstile !== 'undefined') {
                clearInterval(interval);
                render();
            }
        }, 100);

        return () => {
            clearInterval(interval);
            if (
                widgetId.current !== null &&
                typeof (window as any).turnstile !== 'undefined'
            ) {
                (window as any).turnstile.remove(widgetId.current);
                widgetId.current = null;
            }
        };
    }, []);

    if (!SITE_KEY) return null;

    return (
        <div className={className}>
            <div ref={containerRef} />
            <input
                ref={inputRef}
                type="hidden"
                name="cf_turnstile_response"
                defaultValue=""
            />
        </div>
    );
}
