jQuery(document).ready(function ($) {
    'use strict';
    let container = jQuery('#wacv-modal');
    container.on('renderReCaptcha', function () {
        if (wacv_recaptcha_params.enable_captcha == 1) {
            if (wacv_recaptcha_params.recaptcha_version == 'ver2') {
                wacv_reCaptchaV2Onload();
            } else {
                wacv_reCaptchaV3Onload();
                container.find('.wacv-recaptcha-field').hide();
            }
        }
    });

    window.addEventListener('load', function () {
        if (wacv_recaptcha_params.enable_captcha == 1) {
            if (wacv_recaptcha_params.recaptcha_version == 'ver2') {
                wacv_reCaptchaV2Onload();
            } else {
                wacv_reCaptchaV3Onload();
                container.find('.wacv-recaptcha-field').hide();
            }
        }
    });
});

function wacv_validateRecaptcha(response) {
    if (response) {
        jQuery('.wacv-recaptcha-field .wacv-g-validate-response').val(response);
    }
}

function wacv_expireRecaptcha() {
    // jQuery('.wacv-recaptcha-field .wacv-g-validate-response').val(null);
    // if (wacv_recaptcha_params.wacv_layout == 3) {
    //     let old_width = jQuery('.wacv-coupon-box-3 .wacv-recaptcha > div').width();
    //     let parent_width = jQuery('.wacv-coupon-box-3 .wacv-recaptcha').width();
    //     jQuery('.wacv-coupon-box-3 .wacv-recaptcha > div').css({transform: 'scale(' + parent_width / old_width + ',1)'});
    // }
}

function wacv_reCaptchaV3Onload() {
    if (typeof grecaptcha !== 'undefined') {
        grecaptcha.ready(function () {
            grecaptcha.execute(wacv_recaptcha_params.recaptcha_site_key, {action: 'homepage'}).then(function (token) {
                wacv_validateRecaptcha(token);
            })
        });
    }
}

function wacv_reCaptchaV2Onload() {
    if (jQuery('.wacv-recaptcha').length == 0 || jQuery.find('.wacv-recaptcha iframe').length || typeof grecaptcha == 'undefined') {
        return true;
    }
    for (let i = 0; i < jQuery('.wacv-recaptcha').length; i++) {
        grecaptcha.render(jQuery('.wacv-recaptcha')[i], {

            'sitekey': wacv_recaptcha_params.recaptcha_site_key,

            'callback': wacv_validateRecaptcha,

            'expired-callback': wacv_expireRecaptcha,

            'theme': wacv_recaptcha_params.recaptcha_secret_theme,

            'isolated': false
        });

    }
    // if (wacv_recaptcha_params.wacv_layout == 3) {
    //     let old_width = jQuery('.wacv-coupon-box-3 .wacv-recaptcha > div').width();
    //     let parent_width = jQuery('.wacv-coupon-box-3 .wacv-recaptcha-field > div').width();
    //     jQuery('.wacv-coupon-box-3 .wacv-recaptcha > div').css({transform: 'scale(' + parent_width / old_width + ',1)'});
    // }
}