(function () {
	'use strict';

	function combinationKey(options) {
		var names = Object.keys(options).sort();
		var parts = [];
		for (var i = 0; i < names.length; i++) {
			var name = names[i];
			parts.push(String(name).toLowerCase() + '=' + String(options[name]).toLowerCase());
		}
		return parts.join('|');
	}

	function readCombinations(el) {
		var raw = el.getAttribute('data-combinations') || '{}';
		try {
			return JSON.parse(raw);
		} catch (e) {
			return {};
		}
	}

	function selectedOptions(productId) {
		var options = {};
		var roots = document.querySelectorAll('.wpdude-dc-buy-now[data-product-id="' + productId + '"]');
		for (var r = 0; r < roots.length; r++) {
			var selects = roots[r].querySelectorAll('.wpdude-dc-option-select');
			for (var i = 0; i < selects.length; i++) {
				var sel = selects[i];
				var name = sel.getAttribute('name');
				if (name && sel.value) {
					options[name] = sel.value;
				}
			}
			if (Object.keys(options).length) {
				return options;
			}
		}
		return options;
	}

	function setMainImage(root, url) {
		if (!url) {
			return;
		}
		var main = root.querySelector('.wpdude-dc-images__main');
		if (!main) {
			return;
		}
		var img = main.querySelector('.wpdude-dc-images__main-img');
		if (!img) {
			var placeholder = main.querySelector('.wpdude-dc-images__placeholder');
			if (placeholder) {
				placeholder.remove();
			}
			img = document.createElement('img');
			img.className = 'wpdude-dc-images__main-img';
			img.alt = '';
			main.appendChild(img);
		}
		img.src = url;
	}

	function selectThumbForUrl(root, url) {
		var thumbs = root.querySelectorAll('.wpdude-dc-images__thumb');
		var matched = false;
		for (var i = 0; i < thumbs.length; i++) {
			var thumb = thumbs[i];
			var isMatch = url && thumb.getAttribute('data-full') === url;
			thumb.classList.toggle('is-selected', !!isMatch);
			if (isMatch) {
				thumb.setAttribute('aria-current', 'true');
				matched = true;
			} else {
				thumb.removeAttribute('aria-current');
			}
		}
		return matched;
	}

	function syncProduct(productId) {
		var options = selectedOptions(productId);
		var namesNeeded = 0;
		var buy = document.querySelector('.wpdude-dc-buy-now[data-product-id="' + productId + '"]');
		if (buy) {
			namesNeeded = buy.querySelectorAll('.wpdude-dc-option-select').length;
		}
		var complete = namesNeeded === 0 || Object.keys(options).length === namesNeeded;
		var key = complete && Object.keys(options).length ? combinationKey(options) : '';

		var priceNodes = document.querySelectorAll('.wpdude-dc-price[data-product-id="' + productId + '"]');
		for (var p = 0; p < priceNodes.length; p++) {
			var priceEl = priceNodes[p];
			var map = readCombinations(priceEl);
			var valueEl = priceEl.querySelector('.wpdude-dc-price__value');
			var saleEl = priceEl.querySelector('.wpdude-dc-price__sale');
			var text = priceEl.getAttribute('data-default-price') || '';
			var onSale = priceEl.getAttribute('data-any-on-sale') === '1';
			if (key && map[key] && map[key].price_formatted) {
				text = map[key].price_formatted;
				onSale = !!map[key].on_sale;
				priceEl.classList.remove('wpdude-dc-price--from');
			} else if (priceEl.getAttribute('data-price-mode') === 'from') {
				priceEl.classList.add('wpdude-dc-price--from');
			}
			if (valueEl) {
				valueEl.textContent = text;
			} else {
				priceEl.textContent = text;
			}
			if (saleEl) {
				if (onSale) {
					saleEl.removeAttribute('hidden');
				} else {
					saleEl.setAttribute('hidden', 'hidden');
				}
			}
		}

		var imageRoots = document.querySelectorAll('.wpdude-dc-images[data-product-id="' + productId + '"]');
		for (var i = 0; i < imageRoots.length; i++) {
			var root = imageRoots[i];
			var cmap = readCombinations(root);
			var url = root.getAttribute('data-default-image') || '';
			if (key && cmap[key] && cmap[key].image_url) {
				url = cmap[key].image_url;
			}
			if (url) {
				setMainImage(root, url);
				selectThumbForUrl(root, url);
			}
		}
	}

	document.addEventListener('change', function (e) {
		var t = e.target;
		if (!t || !t.classList) {
			return;
		}
		if (t.classList.contains('wpdude-dc-option-select')) {
			var buy = t.closest ? t.closest('.wpdude-dc-buy-now') : null;
			var productId = buy ? buy.getAttribute('data-product-id') : '';
			if (productId) {
				syncProduct(productId);
			}
		}
	});

	document.addEventListener('click', function (e) {
		var btn = e.target.closest ? e.target.closest('.wpdude-dc-images__thumb') : null;
		if (!btn) {
			return;
		}
		e.preventDefault();
		var root = btn.closest('.wpdude-dc-images');
		var full = btn.getAttribute('data-full');
		if (root && full) {
			setMainImage(root, full);
			selectThumbForUrl(root, full);
		}
	});

	function cfg() {
		return window.wpdudeDc || {};
	}

	function i18n(key, fallback) {
		var map = cfg().i18n || {};
		return map[key] || fallback;
	}

	function hideBuyForProduct(productId) {
		if (!productId) {
			return;
		}
		var products = document.querySelectorAll('.wpdude-dc-product[data-product-id="' + productId + '"]');
		for (var i = 0; i < products.length; i++) {
			products[i].classList.add('wpdude-dc-product--post-purchase');
		}
		var buys = document.querySelectorAll('.wpdude-dc-buy-now[data-product-id="' + productId + '"]');
		for (var b = 0; b < buys.length; b++) {
			buys[b].hidden = true;
		}
		var prices = document.querySelectorAll('.wpdude-dc-price[data-product-id="' + productId + '"]');
		for (var p = 0; p < prices.length; p++) {
			prices[p].hidden = true;
		}
	}

	function renderSummary(box, data) {
		var host = box.querySelector('[data-wpdude-dc-summary]');
		if (!host) {
			host = document.createElement('div');
			host.className = 'wpdude-dc-return__summary';
			host.setAttribute('data-wpdude-dc-summary', '');
			var msg = box.querySelector('.wpdude-dc-return__message');
			if (msg && msg.parentNode) {
				msg.parentNode.insertBefore(host, msg.nextSibling);
			} else {
				box.appendChild(host);
			}
		}
		host.hidden = false;
		if (data.summary_html) {
			host.innerHTML = data.summary_html;
		} else if (data.summary_text) {
			host.textContent = data.summary_text;
		}
	}

	function markPaid(box, data) {
		box.classList.add('wpdude-dc-return--paid');
		var pending = box.querySelector('[data-wpdude-dc-pending]');
		if (pending) {
			pending.removeAttribute('data-wpdude-dc-pending');
			pending.textContent =
				data.success_message || 'Thank you! Your payment was successful. We will process your order shortly.';
		} else {
			var msg = box.querySelector('.wpdude-dc-return__message');
			if (msg && data.success_message) {
				msg.textContent = data.success_message;
			}
		}
		renderSummary(box, data || {});
		var actions = box.querySelector('.wpdude-dc-return__actions');
		var local = box.querySelector('.wpdude-dc-return__local');
		if (actions) {
			actions.hidden = true;
		}
		if (local) {
			local.hidden = true;
		}
		hideBuyForProduct(box.getAttribute('data-product-id') || (data && data.product_id) || '');
	}

	function pollStatus(box) {
		var uuid = box.getAttribute('data-uuid');
		var nonce = box.getAttribute('data-confirm-nonce') || '';
		var token = box.getAttribute('data-return-token') || '';
		var pending = box.querySelector('[data-wpdude-dc-pending]');
		var statusEl = box.querySelector('.wpdude-dc-return__status');
		if (!uuid || !nonce || !token) {
			return;
		}
		// Already paid — nothing to poll.
		if (box.classList.contains('wpdude-dc-return--paid') || !pending) {
			return;
		}

		var base = cfg().restBase || '';
		var attempts = 0;
		var maxAttempts = 40;

		if (statusEl) {
			statusEl.textContent = i18n('waiting', 'Confirming your payment…');
		}

		var timer = setInterval(function () {
			attempts += 1;
			if (attempts > maxAttempts) {
				clearInterval(timer);
				return;
			}

			fetch(base + 'order-status/' + encodeURIComponent(uuid) + '?token=' + encodeURIComponent(token), {
				credentials: 'same-origin',
				headers: { Accept: 'application/json' }
			})
				.then(function (response) {
					if (!response.ok) {
						return null;
					}
					return response.json();
				})
				.then(function (data) {
					if (!data) {
						return;
					}
					if (data.status === 'new') {
						clearInterval(timer);
						markPaid(box, data);
					} else if (data.status === 'failed' || data.status === 'expired') {
						clearInterval(timer);
						if (pending) {
							pending.textContent =
								data.success_message || i18n('notCompleted', 'Payment was not completed.');
						}
					}
				})
				.catch(function () {
					// Keep polling (webhook may still arrive).
				});
		}, 1500);
	}

	function confirmLocalPayment(button) {
		var box = button.closest('[data-wpdude-dc-return]');
		if (!box) {
			return;
		}
		var uuid = box.getAttribute('data-uuid');
		var nonce = box.getAttribute('data-confirm-nonce');
		var token = box.getAttribute('data-return-token') || '';
		var msg = box.querySelector('.wpdude-dc-return__confirm-message');
		var url = cfg().confirmUrl || '';
		var restNonce = cfg().restNonce || '';

		button.disabled = true;
		if (msg) {
			msg.hidden = false;
			msg.textContent = i18n('checkingStripe', 'Checking with Stripe…');
		}

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

		fetch(url, {
			method: 'POST',
			credentials: 'same-origin',
			headers: headers,
			body: JSON.stringify({
				order: uuid,
				transaction: uuid,
				nonce: nonce,
				token: token
			})
		})
			.then(function (response) {
				return response.json().then(function (data) {
					return { ok: response.ok, data: data };
				});
			})
			.then(function (result) {
				if (result.ok && result.data && result.data.status === 'new') {
					markPaid(box, result.data);
					return;
				}
				var err =
					(result.data && result.data.message) ||
					i18n('confirmFailed', 'Could not confirm payment yet.');
				if (msg) {
					msg.textContent = err;
				}
				button.disabled = false;
			})
			.catch(function () {
				if (msg) {
					msg.textContent = i18n('confirmFailed', 'Could not confirm payment yet.');
				}
				button.disabled = false;
			});
	}

	document.addEventListener('click', function (e) {
		var confirmBtn = e.target.closest ? e.target.closest('[data-wpdude-dc-confirm-payment]') : null;
		if (confirmBtn) {
			e.preventDefault();
			confirmLocalPayment(confirmBtn);
		}
	});

	function bindReturn() {
		var boxes = document.querySelectorAll('[data-wpdude-dc-return]');
		for (var i = 0; i < boxes.length; i++) {
			var box = boxes[i];
			var productId = box.getAttribute('data-product-id');
			var status = box.getAttribute('data-status') || box.getAttribute('data-wpdude-dc-return');

			if (status === 'cancel') {
				continue;
			}

			if (status === 'success') {
				hideBuyForProduct(productId);
			}

			if (box.classList.contains('wpdude-dc-return--paid')) {
				hideBuyForProduct(productId);
				continue;
			}

			// Always poll for webhook completion (Downloads / Paywall).
			// Local still shows the confirm button when webhooks cannot reach the site.
			pollStatus(box);
		}

		// Ensure long pages land on the product / confirmation section.
		scrollToReturnTarget();
	}

	function scrollToReturnTarget() {
		var hash = window.location.hash;
		if (!hash || hash.indexOf('wpdude-dc-product-') !== 1) {
			return;
		}
		var el = document.getElementById(hash.slice(1));
		if (!el) {
			return;
		}
		window.setTimeout(function () {
			el.scrollIntoView({ behavior: 'smooth', block: 'start' });
		}, 50);
	}

	document.addEventListener('DOMContentLoaded', bindReturn);
})();
