/* global wp, grecaptcha, jQuery */
(function () {
	function ns() {
		return typeof wpPsGrecaptchaWoo !== 'undefined' && wpPsGrecaptchaWoo.ns ? wpPsGrecaptchaWoo.ns : 'wp-powersuite-recaptcha';
	}

	function cfg() {
		return typeof wpPsGrecaptchaWoo !== 'undefined' ? wpPsGrecaptchaWoo : {};
	}

	function setRecaptchaExtensionData(token) {
		if (typeof wp === 'undefined' || !wp.data) {
			return;
		}
		var dispatch = wp.data.dispatch('wc/store/checkout');
		var payload = { token: token || '' };
		if (typeof dispatch.setExtensionData === 'function') {
			dispatch.setExtensionData(ns(), payload);
		} else if (typeof dispatch.__internalSetExtensionData === 'function') {
			dispatch.__internalSetExtensionData(ns(), payload);
		}
	}

	function resetV2Widget() {
		var el = document.getElementById('wpps-grecaptcha-woo-checkout');
		if (!el || !window.grecaptcha || typeof grecaptcha.reset !== 'function') {
			return;
		}
		var wid = el.getAttribute('data-wpps-widget-id');
		if (wid !== null && wid !== '') {
			try {
				grecaptcha.reset(parseInt(wid, 10));
			} catch (e) {}
		}
		setRecaptchaExtensionData('');
	}

	function renderV2BlockWidget() {
		var c = cfg();
		var el = document.getElementById('wpps-grecaptcha-woo-checkout');
		if (!el || !window.grecaptcha || typeof grecaptcha.render !== 'function') {
			return;
		}
		if (el.getAttribute('data-wpps-rendered') === '1') {
			return;
		}
		var sk = c.siteKey || el.getAttribute('data-sitekey');
		if (!sk) {
			return;
		}
		grecaptcha.ready(function () {
			try {
				var id = grecaptcha.render(el, {
					sitekey: sk,
					theme: c.theme || 'light',
					size: c.size || 'normal',
					callback: function (tok) {
						setRecaptchaExtensionData(tok);
					},
					'expired-callback': function () {
						setRecaptchaExtensionData('');
					},
				});
				el.setAttribute('data-wpps-widget-id', String(id));
				el.setAttribute('data-wpps-rendered', '1');
			} catch (e) {}
		});
	}

	function registerV3Validation() {
		var c = cfg();
		if (c.version !== 'v3') {
			return;
		}
		if (typeof wc === 'undefined' || !wc.blocksCheckoutEvents || typeof wc.blocksCheckoutEvents.onCheckoutValidation !== 'function') {
			return;
		}
		if (!c.siteKey) {
			return;
		}
		wc.blocksCheckoutEvents.onCheckoutValidation(function () {
			return new Promise(function (resolve) {
				if (typeof grecaptcha === 'undefined' || !grecaptcha.execute) {
					resolve({
						errorMessage:
							typeof wpPsGrecaptchaWoo !== 'undefined' && wpPsGrecaptchaWoo.v3UnavailableMessage
								? wpPsGrecaptchaWoo.v3UnavailableMessage
								: 'reCAPTCHA is unavailable.',
					});
					return;
				}
				grecaptcha.ready(function () {
					grecaptcha
						.execute(c.siteKey, { action: 'woo_checkout' })
						.then(function (tok) {
							setRecaptchaExtensionData(tok);
							resolve(true);
						})
						.catch(function () {
							resolve({
								errorMessage:
									typeof wpPsGrecaptchaWoo !== 'undefined' && wpPsGrecaptchaWoo.v3FailedMessage
										? wpPsGrecaptchaWoo.v3FailedMessage
										: 'reCAPTCHA verification failed.',
							});
						});
				});
			});
		}, 5);
	}

	jQuery(document.body).on('checkout_error', function () {
		setTimeout(resetV2Widget, 500);
	});

	jQuery(document.body).on('updated_checkout', function () {
		var $w = jQuery('#wpps-grecaptcha-woo-checkout');
		if ($w.length && cfg().version === 'v2' && (!$w.attr('data-wpps-rendered') || $w.attr('data-wpps-rendered') !== '1')) {
			setTimeout(renderV2BlockWidget, 300);
		}
	});

	document.addEventListener('DOMContentLoaded', function () {
		registerV3Validation();
		if (typeof wp === 'undefined' || !wp.data || cfg().version !== 'v2') {
			return;
		}
		wp.data.subscribe(function () {
			var item = document.getElementById('wpps-grecaptcha-woo-checkout');
			if (item && item.getAttribute('data-wpps-rendered') !== '1') {
				renderV2BlockWidget();
			}
		}, 'wc/store/cart');
	});
})();
