( function () {
	function loadScript( id, src, onLoad ) {
		var existing = document.getElementById( id );

		if ( existing ) {
			if ( typeof onLoad === 'function' && typeof window.grecaptcha !== 'undefined' ) {
				onLoad();
			}
			return;
		}

		var script = document.createElement( 'script' );
		script.id = id;
		script.src = src;
		script.async = true;
		script.defer = true;

		if ( typeof onLoad === 'function' ) {
			script.addEventListener( 'load', onLoad );
		}

		document.head.appendChild( script );
	}

	function renderRecaptchaV3( siteKey ) {
		if ( ! window.grecaptcha || ! siteKey ) {
			return;
		}

		window.grecaptcha.ready( function () {
			window.grecaptcha.execute( siteKey, { action: 'login' } ).then( function ( token ) {
				document.querySelectorAll( '#ultraguard-recaptcha-v3-response' ).forEach( function ( field ) {
					field.value = token;
				} );
			} );
		} );
	}

	function initConfig( config ) {
		if ( ! config || ! config.provider ) {
			return;
		}

		if ( config.provider === 'turnstile' ) {
			loadScript( 'ultraguard-turnstile-api', 'https://challenges.cloudflare.com/turnstile/v0/api.js' );
			return;
		}

		if ( config.provider === 'recaptcha_v2' ) {
			loadScript( 'ultraguard-recaptcha-v2-api', 'https://www.google.com/recaptcha/api.js' );
			return;
		}

		if ( config.provider === 'recaptcha_v3' && config.siteKey ) {
			loadScript(
				'ultraguard-recaptcha-v3-api',
				'https://www.google.com/recaptcha/api.js?render=' + encodeURIComponent( config.siteKey ),
				function () {
					renderRecaptchaV3( config.siteKey );
				}
			);
		}
	}

	function boot() {
		( window.ultraguardCaptchaConfigs || [] ).forEach( initConfig );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', boot );
	} else {
		boot();
	}

	document.addEventListener( 'ultraguard:captcha:refresh', boot );
}() );
