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

	function readFields() {
		var root = document.getElementById('wpps-simple-captcha-woo-checkout');
		if (!root) {
			root = document.querySelector('.wpps-simple-captcha-wrap.wpps-captcha-woo-checkout');
		}
		if (!root) {
			return { key: '', answer: '' };
		}
		var keyEl = root.querySelector('input[name="wpps_simple_captcha_key"]');
		var ansEl = root.querySelector('input[name="wpps_simple_captcha_answer"]');
		return {
			key: keyEl && keyEl.value ? keyEl.value : '',
			answer: ansEl && ansEl.value ? ansEl.value : '',
		};
	}

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

	function sync() {
		setExtensionData(readFields());
	}

	document.addEventListener('DOMContentLoaded', function () {
		sync();
		document.body.addEventListener('input', function (e) {
			if (
				e.target &&
				(e.target.name === 'wpps_simple_captcha_answer' || e.target.name === 'wpps_simple_captcha_key')
			) {
				sync();
			}
		});
		if (typeof jQuery !== 'undefined' && wp && wp.data && wp.data.subscribe) {
			wp.data.subscribe(sync);
		}
	});
})();
