/**
 * WooCommerce Blocks Checkout - EMT Helper (reliable)
 */
(function () {
	if (typeof window === 'undefined') return;

	function setPaymentAndRefresh(method) {
		if (!window.wc_emt_params || !wc_emt_params.ajax_url) return;

		fetch(wc_emt_params.ajax_url, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			body: new URLSearchParams({
				action: 'wc_emt_set_payment_method',
				nonce: wc_emt_params.nonce,
				payment_method: method || '',
			}),
		})
			.then((r) => r.json())
			.then(function (res) {
				// refresh cart totals so fee/discount line shows immediately
				try {
					var cartDispatch = window.wp?.data?.dispatch?.('wc/store/cart');
					if (cartDispatch && typeof cartDispatch.invalidateResolution === 'function') {
						cartDispatch.invalidateResolution('getCartData');
					}
					if (cartDispatch && typeof cartDispatch.refreshCart === 'function') {
						cartDispatch.refreshCart();
					}
				} catch (e) {}
			})
			.catch(function () {});
	}

	function boot() {
		if (!window.wp?.data) return;

		// Find a store that exposes getActivePaymentMethod()
		var storeKeys = Object.keys(window.wp.data.stores || {});
		var paymentStore = null;
		for (var i = 0; i < storeKeys.length; i++) {
			try {
				var key = storeKeys[i];
				var s = window.wp.data.select(key);
				if (s && typeof s.getActivePaymentMethod === 'function') {
					paymentStore = key;
					break;
				}
			} catch (e) {
				// ignore
			}
		}
		if (!paymentStore) return;

		var last = null;
		window.wp.data.subscribe(function () {
			try {
				var store = window.wp.data.select(paymentStore);
				if (!store || typeof store.getActivePaymentMethod !== 'function') return;

				var active = store.getActivePaymentMethod();
				if (active === last) return;

				last = active;
				setPaymentAndRefresh(active);
			} catch (e) {}
		});
	}

	// give blocks stores a moment to init
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', boot);
	} else {
		boot();
	}
})();
