(function ($) {
    var vars = (typeof lknFsdwFraudScamDetectionVars !== 'undefined') ? lknFsdwFraudScamDetectionVars : {};

    // ── Blocks checkout: middleware wp.apiFetch ────────────────────────────
    // `wp-api-fetch` é declarado como dependência no PHP, então wp.apiFetch
    // está garantidamente disponível aqui (nível do módulo).
    // Imune ao ciclo de vida React (ex.: cleanup do gateway Rede).
    // O token é buscado de forma assíncrona dentro do middleware para garantir
    // que sempre será um token válido e recém-gerado no momento do envio.
    if (window.wp && window.wp.apiFetch) {
        window.wp.apiFetch.use(function (options, next) {
            var path = options.path || options.url || '';
            if (path.includes('/wc/store/v1/checkout') &&
                options.data && Array.isArray(options.data.payment_data)) {
                var hasToken = options.data.payment_data.some(function (d) {
                    return d.key === 'grecaptchav3response';
                });
                if (!hasToken) {
                    return new Promise(function (resolve, reject) {
                        grecaptcha.ready(function () {
                            grecaptcha.execute(vars.googleKey, { action: 'submit' }).then(function (token) {
                                options.data.payment_data.push({ key: 'grecaptchav3response', value: token });
                                resolve(next(options));
                            }).catch(reject);
                        });
                    });
                }
            }
            return next(options);
        });
    }

    $(window).load(function () {

        // Exibe texto de termos no rodapé do checkout
        var termsText = vars.termsText || vars.googleTermsText || '';
        if (termsText) {
            var formDesc = document.querySelector('.wc-block-checkout__terms.wc-block-checkout__terms--with-separator.wp-block-woocommerce-checkout-terms-block')
                || document.querySelector('.woocommerce-privacy-policy-text');
            if (formDesc) {
                var spanElement = document.createElement('span');
                spanElement.innerHTML = termsText;
                formDesc.appendChild(spanElement);
            }
        }

        // ── Reposiciona o badge acima dos gateways de pagamento ───────────
        var badgeContainer = document.createElement('div');
        badgeContainer.id = 'lkn-grecaptcha-badge-container';

        var paymentSection = document.querySelector('#payment.woocommerce-checkout-payment')
            || document.querySelector('fieldset.wc-block-checkout__payment-method');

        if (paymentSection) {
            paymentSection.parentNode.insertBefore(badgeContainer, paymentSection);

            // Injeta CSS para anular o posicionamento fixo do badge original
            var style = document.createElement('style');
            style.textContent = '#lkn-grecaptcha-badge-container .grecaptcha-badge {'
                + 'position:relative!important;bottom:auto!important;'
                + 'right:auto!important;box-shadow:none!important;'
                + 'display:block!important;margin-bottom:10px!important;}';
            document.head.appendChild(style);

            // Move o badge quando ele for adicionado ao DOM pelo script do Google
            var badgeObserver = new MutationObserver(function () {
                var badge = document.querySelector('.grecaptcha-badge');
                if (badge && badge.parentNode !== badgeContainer) {
                    badgeContainer.appendChild(badge);
                    badgeObserver.disconnect();
                }
            });
            badgeObserver.observe(document.body, { childList: true, subtree: true });
        }

        // ── Classic checkout (XHR) ─────────────────────────────────────────
        var legacyForm = document.querySelector('.checkout.woocommerce-checkout');
        if (legacyForm) {
            var originalXHROpen = XMLHttpRequest.prototype.open;
            var originalXHRSend = XMLHttpRequest.prototype.send;

            XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
                this._requestURL = url;
                originalXHROpen.apply(this, arguments);
            };

            XMLHttpRequest.prototype.send = function (body) {
                if (this._requestURL && this._requestURL.includes('?wc-ajax=checkout')) {
                    var xhr = this;
                    grecaptcha.ready(async function () {
                        var tokenButton = await grecaptcha.execute(vars.googleKey, { action: 'submit' });
                        var newBody = new URLSearchParams(body);
                        newBody.append('grecaptchav3response', tokenButton);
                        newBody.append('lknFraudNonce', vars.nonce);
                        originalXHRSend.call(xhr, newBody.toString());
                    });
                } else {
                    originalXHRSend.apply(this, arguments);
                }
            };
        }
    });
})(jQuery);