(function () {
	function bindRefresh(root) {
		if (!root || root.dataset.wppsScRefreshBound === '1') {
			return;
		}
		var wrap = root.querySelector('.wpps-captcha-image-wrap');
		if (!wrap) {
			return;
		}
		var btn = wrap.querySelector('.wpps-captcha-refresh');
		var img = wrap.querySelector('img');
		var keyInput = root.querySelector('input[name="wpps_simple_captcha_key"]');
		var answerInput = root.querySelector('input[name="wpps_simple_captcha_answer"]');
		if (!btn || !img || !keyInput) {
			return;
		}
		root.dataset.wppsScRefreshBound = '1';
		btn.addEventListener('click', function () {
			var cfg = window.wppsSimpleCaptchaRefresh || {};
			if (!cfg.ajaxUrl || !cfg.nonce) {
				return;
			}
			var xhr = new XMLHttpRequest();
			xhr.open('POST', cfg.ajaxUrl, true);
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xhr.onload = function () {
				try {
					var r = JSON.parse(xhr.responseText);
					if (r.success && r.data && r.data.key && r.data.img_url) {
						keyInput.value = r.data.key;
						img.src = r.data.img_url;
						if (answerInput) {
							answerInput.value = '';
						}
					}
				} catch (e) {}
			};
			xhr.send('action=wpps_simple_captcha_refresh&_wpnonce=' + encodeURIComponent(cfg.nonce));
		});
	}

	function scan() {
		document.querySelectorAll('.wpps-simple-captcha.wpps-captcha-image').forEach(bindRefresh);
	}

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