(function () {
	'use strict';

	function closestBuy(el) {
		while (el && el !== document) {
			if (el.classList && el.classList.contains('wpdude-dc-buy-now')) {
				return el;
			}
			el = el.parentNode;
		}
		return null;
	}

	function showMessage(root, text, isError) {
		var msg = root.querySelector('.wpdude-dc-buy-message');
		if (!msg) {
			return;
		}
		msg.hidden = false;
		msg.textContent = text;
		msg.style.color = isError ? '#b32d2e' : '';
	}

	document.addEventListener('click', function (e) {
		var btn = e.target.closest ? e.target.closest('.wpdude-dc-buy-button') : null;
		if (!btn) {
			return;
		}
		e.preventDefault();
		var root = closestBuy(btn);
		if (!root || !window.wpdudeDcBuyNow) {
			return;
		}

		var productId = parseInt(root.getAttribute('data-product-id') || '0', 10);
		var qtyInput = root.querySelector('.wpdude-dc-qty');
		var qty = qtyInput ? parseInt(qtyInput.value || '1', 10) : 1;
		if (!qty || qty < 1) {
			qty = 1;
		}

		var options = {};
		var selects = root.querySelectorAll('.wpdude-dc-option-select');
		for (var i = 0; i < selects.length; i++) {
			var sel = selects[i];
			if (!sel.value) {
				showMessage(
					root,
					(wpdudeDcBuyNow.i18n && wpdudeDcBuyNow.i18n.chooseOptions) || 'Please choose all options.',
					true
				);
				return;
			}
			options[sel.getAttribute('name')] = sel.value;
		}

		// Prefer nonce rendered with the form (same request as the page HTML).
		var nonce = root.getAttribute('data-nonce') || wpdudeDcBuyNow.nonce || '';
		if (!nonce) {
			showMessage(
				root,
				(wpdudeDcBuyNow.i18n && wpdudeDcBuyNow.i18n.error) || 'Error',
				true
			);
			return;
		}

		btn.disabled = true;
		showMessage(root, (wpdudeDcBuyNow.i18n && wpdudeDcBuyNow.i18n.loading) || 'Redirecting…', false);

		var headers = { 'Content-Type': 'application/json' };
		if (wpdudeDcBuyNow.restNonce) {
			headers['X-WP-Nonce'] = wpdudeDcBuyNow.restNonce;
		}

		var returnUrl = window.location.href;
		try {
			var u = new URL(window.location.href);
			u.searchParams.delete('wpdude_dc_checkout');
			u.searchParams.delete('transaction');
			u.searchParams.delete('order');
			u.searchParams.delete('error');
			returnUrl = u.toString();
		} catch (err) {
			// Keep href.
		}

		fetch(wpdudeDcBuyNow.restUrl, {
			method: 'POST',
			headers: headers,
			credentials: 'same-origin',
			body: JSON.stringify({
				product_id: productId,
				qty: qty,
				options: options,
				nonce: nonce,
				return_url: returnUrl
			})
		})
			.then(function (res) {
				return res.json().then(function (data) {
					return { ok: res.ok, data: data };
				});
			})
			.then(function (result) {
				if (result.ok && result.data && result.data.url) {
					window.location.href = result.data.url;
					return;
				}
				var err =
					(result.data && result.data.message) ||
					(wpdudeDcBuyNow.i18n && wpdudeDcBuyNow.i18n.error) ||
					'Error';
				showMessage(root, err, true);
				btn.disabled = false;
			})
			.catch(function () {
				showMessage(
					root,
					(wpdudeDcBuyNow.i18n && wpdudeDcBuyNow.i18n.error) || 'Error',
					true
				);
				btn.disabled = false;
			});
	});
})();
