import { ref, onMounted } from 'vue';
import { usePage } from '@inertiajs/vue3';

/**
 * Composable for Google reCAPTCHA v3
 * 
 * Usage:
 * const { executeRecaptcha, isLoading, isEnabled } = useRecaptcha();
 * 
 * // In form submit:
 * const token = await executeRecaptcha('login');
 * form.recaptcha_token = token;
 * form.post('/login');
 */
export function useRecaptcha() {
    const page = usePage();
    const isLoading = ref(true);
    const isReady = ref(false);
    
    const isEnabled = computed(() => page.props.recaptcha?.enabled || false);
    const siteKey = computed(() => page.props.recaptcha?.siteKey || '');

    onMounted(() => {
        if (!isEnabled.value || !siteKey.value) {
            isLoading.value = false;
            return;
        }

        // Check if script already loaded
        if (window.grecaptcha) {
            isReady.value = true;
            isLoading.value = false;
            return;
        }

        // Load the reCAPTCHA script
        const script = document.createElement('script');
        script.src = `https://www.google.com/recaptcha/api.js?render=${siteKey.value}`;
        script.async = true;
        script.defer = true;
        
        script.onload = () => {
            window.grecaptcha.ready(() => {
                isReady.value = true;
                isLoading.value = false;
            });
        };
        
        script.onerror = () => {
            isLoading.value = false;
        };

        document.head.appendChild(script);
    });

    /**
     * Execute reCAPTCHA and get token
     * @param {string} action - The action name (e.g., 'login', 'register')
     * @returns {Promise<string|null>} The reCAPTCHA token or null if not enabled
     */
    const executeRecaptcha = async (action = 'submit') => {
        if (!isEnabled.value) {
            return null;
        }

        if (!isReady.value || !window.grecaptcha) {
            return null;
        }

        try {
            const token = await window.grecaptcha.execute(siteKey.value, { action });
            return token;
        } catch (error) {
            return null;
        }
    };

    return {
        isEnabled,
        isLoading,
        isReady,
        executeRecaptcha,
    };
}

import { computed } from 'vue';
export default useRecaptcha;
