/**
 * Guard Dog reCAPTCHA v3 JavaScript
 * 
 * Official Google v3 Implementation
 * Based on: https://developers.google.com/recaptcha/docs/v3
 * 
 * @package GuardDog
 * @since 1.2.2
 */

(function() {
    'use strict';

    // Wait for reCAPTCHA to be available
    function waitForRecaptcha() {
        if (typeof grecaptcha !== 'undefined' && grecaptcha.ready) {
            log('reCAPTCHA already available');
            init();
        } else {
            // Check again in 100ms
            setTimeout(waitForRecaptcha, 100);
        }
    }

    // Initialize when DOM is ready
    function init() {
        if (typeof guard_dog_captcha === 'undefined') {
            console.error('Guard Dog: reCAPTCHA configuration not found');
            return;
        }

        log('Initializing reCAPTCHA v3');

        // Wait for reCAPTCHA to be ready (Google's recommended approach)
        grecaptcha.ready(function() {
            log('reCAPTCHA ready');
            setupForms();
        });
    }

    // Setup form handlers
    function setupForms() {
        const forms = document.querySelectorAll('form');
        
        forms.forEach(function(form) {
            if (shouldProtectForm(form)) {
                log('Setting up reCAPTCHA protection');
                setupFormProtection(form);
            }
        });
    }

    // Determine if a form should be protected
    function shouldProtectForm(form) {
        // Protect login forms
        if (form.querySelector('input[type="password"]')) {
            return true;
        }
        
        // Protect forms with specific classes or IDs
        const protectedSelectors = [
            '#loginform',
            '#registerform', 
            '#lostpasswordform',
            '.wp-block-loginout',
            'form[name="loginform"]'
        ];
        
        for (let selector of protectedSelectors) {
            if (form.matches(selector)) {
                return true;
            }
        }
        
        return false;
    }

    // Setup reCAPTCHA protection for a form
    function setupFormProtection(form) {
        // Remove any existing reCAPTCHA token input
        const existingToken = form.querySelector('input[name="g-recaptcha-response"]');
        if (existingToken) {
            existingToken.remove();
        }

        // Add hidden input for token
        const tokenInput = document.createElement('input');
        tokenInput.type = 'hidden';
        tokenInput.name = 'g-recaptcha-response';
        tokenInput.value = '';
        form.appendChild(tokenInput);

        // Intercept form submission
        function submitHandler(e) {
            e.preventDefault();
            log('Executing reCAPTCHA verification');
            
            // Execute reCAPTCHA (Google's recommended approach)
            grecaptcha.execute(guard_dog_captcha.sitekey, {
                action: guard_dog_captcha.action || 'submit'
            }).then(function(token) {
                log('Verification successful');
                
                // Add token to form and submit
                tokenInput.value = token;
                form.removeEventListener('submit', submitHandler);
                form.submit();
                
            }).catch(function(error) {
                console.error('Guard Dog reCAPTCHA error:', error);
                
                // Allow form submission even if reCAPTCHA fails
                // (to prevent blocking legitimate users)
                form.removeEventListener('submit', submitHandler);
                form.submit();
            });
        }
        
        form.addEventListener('submit', submitHandler);
    }

    // Start waiting for reCAPTCHA when page loads
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', waitForRecaptcha);
    } else {
        waitForRecaptcha();
    }

})(); 