(function () {
	var data = window.kramarBackInStock || {};

	function init() {
		var form = document.getElementById('kramar-bis-form');
		if (!form) {
			return;
		}

		var btn = document.getElementById('kramar-bis-submit');
		var msg = document.getElementById('kramar-bis-message');
		var emailEl = document.getElementById('kramar-bis-email');
		var consentEl = document.getElementById('kramar-bis-consent');
		var captchaEl = document.getElementById('kramar-bis-captcha');
		var captchaTokenEl = document.getElementById('kramar-bis-captcha-token');

		if (!btn || !emailEl || !consentEl) {
			return;
		}

		var productId = form.getAttribute('data-product-id') || '0';
		var variationId = form.getAttribute('data-variation-id') || '0';

		btn.addEventListener('click', function () {
			var email = emailEl.value.trim();
			var consent = consentEl.checked;

			if (msg) {
				msg.textContent = '';
				msg.className = 'kramar-bis-message';
			}

			if (!email) {
				showMessage(msg, data.i18nNoEmail || '', false);
				return;
			}

			if (!consent) {
				showMessage(msg, data.i18nNoConsent || '', false);
				return;
			}

			if (captchaEl && !captchaEl.value.trim()) {
				showMessage(msg, data.i18nNoCaptcha || '', false);
				return;
			}

			btn.disabled = true;

			var body = new URLSearchParams();
			body.append('action', 'kramar_bis_subscribe');
			body.append('nonce', data.nonce || '');
			body.append('email', email);
			body.append('product_id', productId);
			body.append('variation_id', variationId);
			body.append('consent', '1');
			if (captchaEl && captchaTokenEl) {
				body.append('captcha', captchaEl.value.trim());
				body.append('captcha_token', captchaTokenEl.value);
			}

			fetch(data.ajaxUrl || '', {
				method: 'POST',
				body: body,
				headers: { 'X-Requested-With': 'XMLHttpRequest' }
			})
				.then(function (r) {
					return r.json();
				})
				.then(function (d) {
					var text = d.data && d.data.message ? d.data.message : '';
					showMessage(msg, text, !!d.success);
					if (d.success) {
						btn.style.display = 'none';
					}
				})
				.catch(function () {
					showMessage(msg, data.i18nError || '', false);
				})
				.finally(function () {
					btn.disabled = false;
				});
		});
	}

	function showMessage(msg, text, ok) {
		if (!msg) {
			return;
		}
		msg.textContent = text;
		msg.classList.add(ok ? 'kramar-bis-message--ok' : 'kramar-bis-message--err');
	}

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