var wawpInvisiblePendingForms = [];
function wawpInvisibleCallback(token) {
	while (wawpInvisiblePendingForms.length > 0) {
		var form  = wawpInvisiblePendingForms.shift();
		var input = form.querySelector( 'input[name="g-recaptcha-response"]' );
		if ( ! input) {
			input      = document.createElement( 'input' );
			input.type = 'hidden';
			input.name = 'g-recaptcha-response';
			form.appendChild( input );
		}
		input.value = token;

		// Disable the interceptor and submit
		form.setAttribute( 'data-recaptcha-verified', 'true' );

		// Try to find the submit button and click it to preserve AJAX/Handlers, or just submit the form.
		var submitBtn = form.querySelector( '[type="submit"], [id^="wawp_request_otp"], [id^="wawp_login_email_password"], [id^="wawp_signup_submit"]' );
		if (submitBtn) {
			submitBtn.click();
		} else {
			form.submit();
		}
	}
}
document.addEventListener(
	'submit',
	function (e) {
		var form = e.target;

		// 1. DON'T intercept Wawp-specific forms as they have their own AJAX handlers in wawp-otp-frontend.js / wawp-signup.js
		if (form.id === 'wawp-signup-form' || form.id === 'wawp-otp-form' ||
		form.id === 'wawp-otp-login-form-phone' ||
		form.id === 'wawp-otp-login-form-email-merged') {
			return;
		}

		// 2. Identify target forms
		var isWcCheckout = form.id === 'order_review' || form.classList.contains( 'woocommerce-checkout' ) || form.classList.contains( 'checkout' ) || form.classList.contains( 'wc-block-checkout__form' );
		var isTargetForm = isWcCheckout || form.id === 'loginform' || form.id === 'registerform' || form.id === 'lostpasswordform' ||
		form.classList.contains( 'woocommerce-form-login' ) ||
		form.classList.contains( 'woocommerce-form-register' );

		if ( ! isTargetForm) {
			// Fallback: check if it has a local recaptcha div
			if ( ! form.querySelector( '.g-recaptcha[data-size="invisible"]' )) {
				return;
			}
		}

		// 3. Skip if already verified
		if (form.getAttribute( 'data-recaptcha-verified' ) === 'true') {
			return;
		}

		// 4. Find the reCAPTCHA element (local or global/footer)
		var recaptchaDiv = form.querySelector( '.g-recaptcha[data-size="invisible"]' );
		if ( ! recaptchaDiv) {
			// Look globally (for cases like our new footer fallback or centralized containers)
			recaptchaDiv = document.querySelector( '.g-recaptcha[data-size="invisible"]' );
		}

		if (recaptchaDiv) {
			// If we have a token already, let it through (don't loop)
			var existingToken = form.querySelector( 'input[name="g-recaptcha-response"]' );
			if (existingToken && existingToken.value) {
				return;
			}

			e.preventDefault();
			wawpInvisiblePendingForms.push( form );
			try {
				// If v2 invisible is correctly loaded, this triggers the challenge/callback
				grecaptcha.execute();
			} catch (err) {
				console.warn( 'AWP reCAPTCHA: execute error', err );
				form.setAttribute( 'data-recaptcha-verified', 'true' );
				form.submit();
			}
		}
	},
	true
);

// Add support for WooCommerce Block Checkout "Place Order" button intercept
// Since Block Checkout might not fire standard 'submit' events on the form tag
document.addEventListener(
	'click',
	function (e) {
		var btn = e.target.closest( '.wc-block-components-checkout-place-order-button' );
		if (btn) {
			var form = btn.closest( 'form' ) || document.querySelector( '.wc-block-checkout__form' );
			if (form && form.getAttribute( 'data-recaptcha-verified' ) !== 'true') {
				// We can't easily prevent the React-based submit here without more complex logic,
				// but identifying the form and triggering recaptcha is the first step.
				// Standard WC blocks might require specific Store API integration.
				// For now, standard checkout is the priority FIX.
			}
		}
	}
);

// Fix for Old Checkout disappearing: Re-scan/init on WC update
if (typeof jQuery !== 'undefined') {
	jQuery( document.body ).on(
		'updated_checkout',
		function () {
			if (typeof grecaptcha !== 'undefined' && typeof grecaptcha.render === 'function') {
				jQuery( '.g-recaptcha[data-size="invisible"]' ).each(
					function () {
						if ( ! jQuery( this ).html().trim()) {
							try {
								grecaptcha.render( this );
							} catch (e) {
							}
						}
					}
				);
			}
		}
	);
}
