/**
 * WooCommerce reCAPTCHA v3 runtime.
 *
 * Ensures WooCommerce account forms receive a fresh token on page load and
 * immediately before submit.
 *
 * @package Polanger_Dashboard_Tools
 */
( function () {
	'use strict';

	/**
	 * Execute reCAPTCHA for a field and populate the token.
	 *
	 * @param {HTMLInputElement} field The token field.
	 * @param {Function} callback Completion callback.
	 */
	function executeToken( field, callback ) {
		var siteKey = field.getAttribute( 'data-site-key' );
		var action = field.getAttribute( 'data-action' ) || 'submit';

		if ( ! siteKey || typeof window.grecaptcha === 'undefined' ) {
			callback( false );
			return;
		}

		window.grecaptcha.ready( function () {
			window.grecaptcha.execute( siteKey, { action: action } ).then(
				function ( token ) {
					field.value = token || '';
					callback( true );
				},
				function () {
					callback( false );
				}
			);
		} );
	}

	/**
	 * Refresh all visible Polanger reCAPTCHA v3 fields on the page.
	 */
	function fillAllFields() {
		var fields = document.querySelectorAll( '.pdt-recaptcha-v3-token' );

		fields.forEach( function ( field ) {
			executeToken( field, function () {} );
		} );
	}

	/**
	 * Bind submit handlers so WooCommerce forms submit with a fresh token.
	 */
	function bindFormSubmits() {
		var forms = document.querySelectorAll( 'form' );

		forms.forEach( function ( form ) {
			var field = form.querySelector( '.pdt-recaptcha-v3-token' );

			if ( ! field ) {
				return;
			}

			form.addEventListener(
				'submit',
				function ( event ) {
					if ( '1' === form.getAttribute( 'data-pdt-recaptcha-submitting' ) ) {
						form.removeAttribute( 'data-pdt-recaptcha-submitting' );
						return;
					}

					if ( typeof window.grecaptcha === 'undefined' ) {
						return;
					}

					event.preventDefault();
					executeToken(
						field,
						function () {
							form.setAttribute( 'data-pdt-recaptcha-submitting', '1' );

							if ( typeof form.requestSubmit === 'function' ) {
								form.requestSubmit();
							} else {
								form.submit();
							}
						}
					);
				},
				true
			);
		} );
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		fillAllFields();
		bindFormSubmits();
	} );
}() );
