/* global pdtRecaptchaV3Comment, grecaptcha */
/**
 * reCAPTCHA Addon — v3 Comment Form Runtime
 *
 * Executes reCAPTCHA v3 on page load and refreshes the token just before
 * the comment form is submitted, ensuring a fresh token is always sent.
 *
 * Site key and action are passed via wp_localize_script() as `pdtRecaptchaV3Comment`.
 *
 * @package Polanger_Dashboard_Tools
 */
( function () {
	'use strict';

	if ( typeof pdtRecaptchaV3Comment === 'undefined' ) {
		return;
	}

	var siteKey = pdtRecaptchaV3Comment.siteKey;

	/**
	 * Execute reCAPTCHA v3 and fill a token field.
	 *
	 * @param {HTMLInputElement} field  The hidden token input element.
	 */
	function fillField( field ) {
		var action = field.getAttribute( 'data-action' ) || 'submit';

		grecaptcha.ready( function () {
			grecaptcha.execute( siteKey, { action: action } ).then( function ( token ) {
				field.value = token;
			} );
		} );
	}

	/**
	 * Fill all `.pdt-recaptcha-v3-token` fields on the current page.
	 */
	function fillAllFields() {
		var fields = document.querySelectorAll( '.pdt-recaptcha-v3-token' );
		fields.forEach( fillField );
	}

	/**
	 * Wire up submit handlers on comment forms so the token is refreshed
	 * if it has somehow become empty (e.g. long page idle).
	 */
	function bindFormSubmit() {
		var forms = document.querySelectorAll( '#commentform' );

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

					if ( field && '' === field.value ) {
						fillField( field );
					}
				},
				true /* capture phase — runs before default submit handlers */
			);
		} );
	}

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