/**
 * InPost Cart & Checkout UI
 * =========================
 * Extracted 2026-03-02 from inline PHP (inpost-parcel-locker-selector.php)
 *
 * Handles:
 *   COMMON (cart + checkout):
 *     - CustomerMatchedZone hide (cart) / move-to-top (checkout)
 *
 *   CART ONLY:
 *     - Remove "Shipping to" destination text & shipping calculator
 *     - Replace them with "Change address" link opening InPost map
 *
 *   CHECKOUT ONLY:
 *     - Show coupon form expanded + deduplicate
 *     - Hide shipping methods row when paczkomat selected
 *     - Faktura checkbox + compact address layout
 *     - Phone prefix visual span (auto-hide when value already has prefix)
 *     - Bidirectional data sync (WC <-> popup)
 *     - Clear paczkomat on customer data change (debounced)
 *     - InPostFieldSync public API
 *
 * Localized data (via wp_localize_script on handle 'inpost-cart-checkout-ui'):
 *   - inpost_cart_i18n          (cart only) — { lbl_change_address: string }
 *   - inpost_phone_prefixes     (checkout only) — { pl: '+48', ... }
 *   - inpost_checkout_data      (checkout only) — { country, faktura_label, debug }
 */

/* -----------------------------------------------
 * INPOST_DEBUG — JS-side debug gating
 * Reads from localized data (inpost_checkout_data.debug)
 * When '0': all console.log calls are suppressed
 * ----------------------------------------------- */
var INPOST_DEBUG = (function() {
	if (typeof inpost_checkout_data !== 'undefined' && inpost_checkout_data && inpost_checkout_data.debug === '1') return true;
	// Fallback: check if WP has SCRIPT_DEBUG or manual override
	if (typeof window.INPOST_DEBUG !== 'undefined') return !!window.INPOST_DEBUG;
	return true; // default ON during development
})();

function inpostLog() {
	if (!INPOST_DEBUG) return;
	var args = Array.prototype.slice.call(arguments);
	args.unshift('[InPost]');
	console.log.apply(console, args);
}

/* -----------------------------------------------
 * Page detection helpers (work with Classic + Blocks)
 * WC adds body classes via wc_body_class() filter:
 *   woocommerce-cart, woocommerce-checkout
 * Fallback: detect WC Blocks containers in DOM
 * ----------------------------------------------- */
function inpostIsCartPage() {
	var b = document.body;
	return b.classList.contains('woocommerce-cart')
		|| !!document.querySelector('.wp-block-woocommerce-cart')
		|| !!document.querySelector('.wc-block-cart');
}
function inpostIsCheckoutPage() {
	var b = document.body;
	return b.classList.contains('woocommerce-checkout')
		|| !!document.querySelector('.wp-block-woocommerce-checkout')
		|| !!document.querySelector('.wc-block-checkout');
}

/* =============================================
 * COMMON: CustomerMatchedZone (cart + checkout)
 * ============================================= */
(function($) {
	function inpostHideCustomerMatchedZone() {
		if (inpostIsCartPage()) {
			$('tr').each(function() {
				if ($(this).text().indexOf('Customer matched zone') >= 0)
					$(this).addClass('inpost-hide-customer-matched-zone');
			});
			$('div, p, span').each(function() {
				var t = ($(this).text() || '').trim();
				if (t.indexOf('Customer matched zone') >= 0 && t.length < 120) {
					$(this).addClass('inpost-hide-customer-matched-zone');
					$(this).closest('tr').addClass('inpost-hide-customer-matched-zone');
				}
			});
		}
	}

	function inpostMoveCustomerMatchedZoneToTop() {
		if (!inpostIsCheckoutPage()) return;
		var zone = $('tr:contains("Customer matched zone"), div:contains("Customer matched zone"), p:contains("Customer matched zone"), span:contains("Customer matched zone")')
			.filter(function() {
				var t = ($(this).text() || '').trim();
				return t.indexOf('Customer matched zone') >= 0 && t.length < 120;
			}).first();
		if (zone.length && !zone.closest('.inpost-moved-zone').length) {
			var form = $('form.checkout');
			if (form.length) {
				var wrapper = $('<div class="inpost-moved-zone" style="margin-bottom: 1em;"></div>');
				form.prepend(wrapper);
				var zoneParent = zone.closest('tr, div, p, table');
				if (zoneParent.length) {
					zoneParent.appendTo(wrapper);
				} else {
					zone.appendTo(wrapper);
				}
			}
		}
	}

	$(function() {
		inpostHideCustomerMatchedZone();
		inpostMoveCustomerMatchedZoneToTop();
	});

	$(document.body).on('updated_cart_totals updated_checkout', function() {
		inpostHideCustomerMatchedZone();
		inpostMoveCustomerMatchedZoneToTop();
	});
})(jQuery);

/* =============================================
 * CART ONLY: Shipping destination & calculator
 * ============================================= */
(function($) {
	/* Uruchom tylko na stronie koszyka */
	if (!inpostIsCartPage()) return;

	/* USUWAMY Shipping to + kalkulator (Change address). Tylko link do mapy INTRO. */
	function inpostShippingToAndChangeAddress() {
		if (!inpostIsCartPage()) return;
		var sel = $('#selected-paczkomat');
		var hasPaczkomat = sel.length && sel.text().trim().length > 0;
		var dest = $('.woocommerce-shipping-destination');
		var calc = $('.woocommerce-shipping-calculator');
		if (hasPaczkomat) {
			dest.remove();
			calc.remove();
			var wrap = $('.inpost-change-address-wrap');
			var tot = $('.woocommerce-shipping-totals');
			if (!wrap.length && tot.length) {
				var linkTxt = (typeof inpost_cart_i18n !== 'undefined' && inpost_cart_i18n && inpost_cart_i18n.lbl_change_address)
					? inpost_cart_i18n.lbl_change_address
					: 'Change address';
				wrap = $('<p class="inpost-change-address-wrap"><a href="#" class="inpost-change-address-map-link">' + linkTxt + '</a></p>');
				tot.find('td').append(wrap);
			}
		} else {
			$('.inpost-change-address-wrap').remove();
		}
	}

	$(document.body).on('click', '.inpost-change-address-map-link', function(e) {
		e.preventDefault();
		var intro = (typeof IntroPopup !== 'undefined') ? IntroPopup : (typeof window.IntroPopup !== 'undefined') ? window.IntroPopup : null;
		if (intro && typeof intro.open === 'function') { intro.open('pl'); return; }
		$('.select-paczkomat-button').first().trigger('click');
	});

	$(document.body).on('click', 'a.shipping-calculator-button', function(e) {
		if ($('#selected-paczkomat').length && $('#selected-paczkomat').text().trim()) {
			e.preventDefault();
			var i = (typeof IntroPopup !== 'undefined') ? IntroPopup : window.IntroPopup;
			if (i && i.open) i.open('pl'); else $('.select-paczkomat-button').first().trigger('click');
		}
	});

	$(function() {
		inpostShippingToAndChangeAddress();
		setTimeout(inpostShippingToAndChangeAddress, 300);
	});

	$(document.body).on('updated_cart_totals wc_fragments_refreshed', inpostShippingToAndChangeAddress);
})(jQuery);

/* =============================================
 * CHECKOUT ONLY: Coupon, shipping, faktura,
 *                phone prefix, bidirectional sync
 * ============================================= */
(function($) {
	/* Uruchom tylko na stronie checkout */
	if (!inpostIsCheckoutPage()) return;

	/* --- Coupon form: show expanded + deduplicate --- */
	$(function() {
		$('#woocommerce-checkout-form-coupon').show();
		$('.woocommerce-form-coupon-toggle .showcoupon').attr('aria-expanded', 'true');
	});

	$(document.body).on('init_checkout updated_checkout', function() {
		$('#woocommerce-checkout-form-coupon').show();
		$('.woocommerce-form-coupon-toggle .showcoupon').attr('aria-expanded', 'true');
	});

	function inpostHideDuplicateCoupon() {
		var forms = $('form.woocommerce-form-coupon, .woocommerce-form-coupon, form.checkout_coupon');
		if (forms.length > 1) {
			forms.each(function(idx) { if (idx > 0) $(this).hide(); });
		}
		var inputs = $('input[name="coupon_code"]');
		if (inputs.length > 1) {
			inputs.each(function(idx) {
				if (idx > 0) $(this).closest('form, .coupon, .woocommerce-form-coupon, p, div').hide();
			});
		}
		var toggles = $('.woocommerce-form-coupon-toggle, a.showcoupon, .showcoupon');
		if (toggles.length > 1) {
			toggles.each(function(idx) { if (idx > 0) $(this).hide(); });
		}
		$('.checkout_coupon').each(function(idx) { if (idx > 0) $(this).hide(); });
	}

	/* --- Hide shipping methods when paczkomat selected --- */
	function inpostHideShippingMethodsWhenPaczkomat() {
		if (!inpostIsCheckoutPage()) return;
		var sel = $('#selected-paczkomat');
		if (sel.length && sel.text().trim().length > 0) {
			$('#shipping_method, .woocommerce-shipping-methods, tr.shipping, th:contains("Shipping"), td:contains("Płaska stawka")')
				.closest('tr, table, .woocommerce-checkout-review-order-table')
				.addClass('inpost-hide-shipping-methods');
			$('tr.shipping, th:contains("Shipping"), td:contains("Płaska stawka")').addClass('inpost-hide-shipping-methods');
			$('.woocommerce-checkout-review-order-table tr').each(function() {
				var txt = $(this).text();
				if (txt.indexOf('Płaska stawka') >= 0 || txt.indexOf('Flat rate') >= 0) {
					$(this).addClass('inpost-hide-shipping-methods');
				}
			});
		}
	}

	$(function() {
		inpostHideDuplicateCoupon();
		inpostHideShippingMethodsWhenPaczkomat();
	});

	$(document.body).on('init_checkout updated_checkout wc_fragments_refreshed', function() {
		// Wywołaj z opóźnieniem żeby upewnić się że DOM jest gotowy
		setTimeout(function() {
			inpostHideDuplicateCoupon();
			inpostHideShippingMethodsWhenPaczkomat();
		}, 100);
	});

	/* --- Faktura checkbox toggle --- */
	$(document.body).on('change', '#inpost-need-faktura', function() {
		var c = $('.inpost-faktura-fields');
		if ($(this).is(':checked')) {
			c.addClass('inpost-show');
			$('#inpost-need-faktura-top').prop('checked', true);
		} else {
			c.removeClass('inpost-show');
			$('#inpost-need-faktura-top').prop('checked', false);
		}
	});

	$(document.body).on('change', '#inpost-need-faktura-top', function() {
		var main = $('#inpost-need-faktura');
		if ($(this).is(':checked')) {
			main.prop('checked', true);
			$('.inpost-faktura-fields').addClass('inpost-show');
		} else {
			main.prop('checked', false);
			$('.inpost-faktura-fields').removeClass('inpost-show');
		}
	});

	$(document.body).on('init_checkout updated_checkout', function() {
		if ($('#inpost-need-faktura').is(':checked')) {
			$('.inpost-faktura-fields').addClass('inpost-show');
			$('#inpost-need-faktura-top').prop('checked', true);
		}
	});

	/* --- Phone prefix visual span --- */
	function inpostApplyPhonePrefix() {
		var pf = (typeof inpost_phone_prefixes !== 'undefined' ? inpost_phone_prefixes : {});
		var cd = (typeof inpost_checkout_data !== 'undefined' ? inpost_checkout_data : {});
		var country = (cd.country || 'pl').toLowerCase();
		var prefix = (pf && pf[country]) ? pf[country] : '+48';
		var wr = $('#billing_phone_field .woocommerce-input-wrapper');
		if (wr.length && !wr.find('.inpost-phone-prefix').length) {
			wr.prepend('<span class="inpost-phone-prefix">' + prefix + '</span>');
			wr.addClass('inpost-phone-prefix-wrap');
		}
		// FIX 2026-03-02v2: Jesli wartosc inputa JUZ zawiera prefix (np. +48 123456789)
		// to UKRYJ wizualny span zeby nie bylo podwojnie wyswietlane
		// Popup wpisuje pelny numer z prefixem do wartosci pola
		var phoneInput = $('#billing_phone');
		if (phoneInput.length) {
			var val = phoneInput.val() || '';
			if (val.charAt(0) === '+') {
				wr.find('.inpost-phone-prefix').hide();
			} else {
				wr.find('.inpost-phone-prefix').show();
			}
		}
	}

	$(function() { inpostApplyPhonePrefix(); });
	$(document.body).on('init_checkout updated_checkout', inpostApplyPhonePrefix);

	// FIX 2026-03-02v2: Nasluchuj zmian w #billing_phone - auto-ukryj/pokaz prefix
	// Gdy popup wpisze +48 123456789 - ukryj wizualny span
	// Gdy klient wyczysc i wpisze bez + - pokaz wizualny span
	$(document).on('input change', '#billing_phone', function() {
		var val = $(this).val() || '';
		var prefixSpan = $(this).closest('.woocommerce-input-wrapper').find('.inpost-phone-prefix');
		if (val.charAt(0) === '+') {
			prefixSpan.hide();
		} else {
			prefixSpan.show();
		}
	});

	/* --- Faktura compact layout --- */
	function inpostWrapFakturaCompact() {
		if ($('.inpost-faktura-block').length) return;
		var co = $('#billing_company_field'), cy = $('#billing_country_field');
		var a1 = $('#billing_address_1_field'), a2 = $('#billing_address_2_field'), pc = $('#billing_postcode_field'), ct = $('#billing_city_field');
		if (!co.length || !cy.length || !a1.length || !pc.length || !ct.length) return;
		var cd = (typeof inpost_checkout_data !== 'undefined' ? inpost_checkout_data : {});
		var lbl = cd.faktura_label || 'Potrzebuję faktury';
		var block = $('<div class="inpost-faktura-block inpost-faktura-fields"></div>');
		co.before(block);
		var row1 = $('<div class="inpost-faktura-company-country inpost-faktura-fields"></div>');
		row1.append(co).append(cy);
		var row2 = $('<div class="inpost-address-compact-row inpost-faktura-fields"></div>');
		row2.append(a1);
		if (a2.length) row2.append(a2);
		row2.append(pc).append(ct);
		var topCb = $(
			'<p class="form-row form-row-wide inpost-faktura-top-checkbox inpost-faktura-fields">' +
			'<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">' +
			'<input type="checkbox" id="inpost-need-faktura-top" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" /> ' +
			'<span></span></label></p>'
		);
		topCb.find('span').text(lbl);
		block.append(topCb).append(row1).append(row2);
	}

	$(function() { inpostWrapFakturaCompact(); });
	$(document.body).on('init_checkout updated_checkout', function() { inpostWrapFakturaCompact(); });

	/* =================================================================
	 * FIX 2026-03-02: BIDIRECTIONAL DATA SYNC + CLEAR PACZKOMAT ON CHANGE
	 * =================================================================
	 * 1. Po wyborze paczkomatu dane z popup -> pola WC (robi intro-popup.js confirmAndSave)
	 * 2. Jeśli klient ZMIENI dane w WC po wyborze paczkomatu -> CLEAR paczkomat
	 *    (spójność danych: paczkomat był wybrany z innymi danymi klienta)
	 * 3. Opcja: klient może przywrócić dane z WC do popup (sync WC -> popup)
	 * ================================================================= */
	(function() {
		// Pola checkout które monitorujemy
		var watchedFields = [
			'#billing_first_name',
			'#billing_last_name',
			'#billing_email',
			'#billing_phone'
		];

		// Snapshot danych TUŻE PO wyborze paczkomatu
		var dataSnapshot = null;
		var paczkomat_was_selected = false;
		var ignoreChanges = false; // Flaga: ignoruj zmiany gdy to MY aktualizujemy pola

		// Zrób snapshot aktualnych wartości pól WC
		function takeSnapshot() {
			var snap = {};
			watchedFields.forEach(function(sel) {
				var el = $(sel);
				if (el.length) snap[sel] = el.val() || '';
			});
			return snap;
		}

		// Sprawdź czy paczkomat jest wybrany (jest w sesji / widoczny na stronie)
		function isPaczkomatSelected() {
			var sel = $('#selected-paczkomat');
			return sel.length > 0 && sel.text().trim().length > 0;
		}

		var clearDebounceTimer = null;

		// FIX 2026-03-02v3: Debounce 2s - daj czas na pauseWatching/resumeWatching
		// BEZ debounce: input events z updateWooCommerceCheckoutFields wyzwalaly clear
		// mimo pauseWatching, bo eventy mogly docierac z opoznieniem (async rendering)
		function clearPaczkomatSelection() {
			if (ignoreChanges) {
				inpostLog('[InPost Sync] 🛡️ clearPaczkomatSelection ZABLOKOWANE — ignoreChanges=true');
				return;
			}
			inpostLog('[InPost Sync] ⚠️ Dane klienta zmienione po wyborze paczkomatu — czyszczę paczkomat!');

			// 1. Wyczyść wizualnie
			$('#selected-paczkomat').remove();
			$('.inpost-cart-selected-paczkomat').remove();

			// 2. Wyczyść window globals
			if (window.inpostCustomerData) delete window.inpostCustomerData;

			// 3. AJAX: wyczyść sesję WC
			var ajaxVar = (typeof paczkomat_ajax !== 'undefined') ? paczkomat_ajax : null;
			var ajaxUrl = ajaxVar ? (ajaxVar.ajax_url || ajaxVar.ajaxurl) : '/wp-admin/admin-ajax.php';
			var nonce = ajaxVar ? (ajaxVar.nonce || '') : '';

			$.post(ajaxUrl, {
				action: 'clear_paczkomat_session',
				security: nonce,
				nonce: nonce
			}, function(response) {
				inpostLog('[InPost Sync] ✅ Sesja paczkomatu wyczyszczona:', response);
				// Odśwież checkout żeby odzwierciedlić zmianę
				$(document.body).trigger('update_checkout');
			});

			// 4. Reset stanu
			paczkomat_was_selected = false;
			dataSnapshot = null;
		}

		// Listener na zmiany w polach checkout (billing)
		// Używamy 'input' żeby łapać pisanie na żywo, nie tylko blur
		// FIX 2026-03-02v3: Debounced change detection
		// PROBLEM: input/change events z dispatchEvent w updateWooCommerceCheckoutFields
		// docieraly POMIEDZY pauseWatching() a resumeWatching() przez event loop
		// ROZWIAZANIE: debounce 2s + dodatkowy check ignoreChanges w clearPaczkomatSelection
		$(document).on('input change', watchedFields.join(','), function() {
			if (ignoreChanges) return; // Ignoruj gdy to MY ustawiamy pola

			// Sprawdz czy paczkomat jest wybrany
			if (!paczkomat_was_selected && !isPaczkomatSelected()) return;

			// Sprawdz czy dane FAKTYCZNIE sie zmienily (vs snapshot)
			if (!dataSnapshot) return;

			// Debounce: odczekaj 2s bez kolejnych zmian
			if (clearDebounceTimer) clearTimeout(clearDebounceTimer);
			clearDebounceTimer = setTimeout(function() {
				if (ignoreChanges) return; // Ponowny check po debounce
				var currentValues = takeSnapshot();
				var changed = false;
				for (var key in dataSnapshot) {
					if (currentValues[key] !== undefined && currentValues[key] !== dataSnapshot[key]) {
						inpostLog('[InPost Sync] Zmiana w polu', key, ':', dataSnapshot[key], '->', currentValues[key]);
						changed = true;
						break;
					}
				}
				if (changed) {
					clearPaczkomatSelection();
				}
			}, 2000);
		});

		// NASŁUCHUJ momentu wyboru paczkomatu (AJAX success)
		// intro-popup.js wysyła custom event po udanym AJAX
		// Ale też możemy monitorować pojawienie się #selected-paczkomat
		var paczkomatObserver = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				mutation.addedNodes.forEach(function(node) {
					if (node.nodeType !== 1) return;
					// Sprawdź czy dodano element #selected-paczkomat lub class
					if (node.id === 'selected-paczkomat' ||
						(node.classList && node.classList.contains('inpost-cart-selected-paczkomat')) ||
						(node.querySelector && node.querySelector('#selected-paczkomat'))) {
						inpostLog('[InPost Sync] Paczkomat wybrany - robimy snapshot pol checkout');
						paczkomat_was_selected = true;
						// FIX 2026-03-02v3: Zwieksz delay do 3s
						// 500ms bylo za malo - updateWooCommerceCheckoutFields() + WC update_checkout
						// mogly jeszcze nie skonczyc async rerendering pol
						ignoreChanges = true; // Blokuj clear na czas inicjalizacji
						setTimeout(function() {
							dataSnapshot = takeSnapshot();
							ignoreChanges = false;
							inpostLog('[InPost Sync] Snapshot gotowy:', JSON.stringify(dataSnapshot));
						}, 3000);
					}
				});
			});
		});

		// Obserwuj zmiany w checkout form
		$(function() {
			var form = $('form.checkout, .woocommerce-checkout');
			if (form.length) {
				paczkomatObserver.observe(form[0], { childList: true, subtree: true });
				inpostLog('[InPost Sync] ✅ MutationObserver na checkout zainstalowany');
			}

			// Jeśli paczkomat już był wybrany (reload strony)
			if (isPaczkomatSelected()) {
				paczkomat_was_selected = true;
				dataSnapshot = takeSnapshot();
				inpostLog('[InPost Sync] 📸 Paczkomat już wybrany — snapshot z page load');
			}
		});

		// PUBLIC API: Pozwól intro-popup.js ustawić flagę ignoreChanges
		window.InPostFieldSync = {
			// Wywołaj PRZED programowym ustawianiem pól (żeby nie triggerować clear)
			pauseWatching: function() { ignoreChanges = true; },
			// Wywołaj PO programowym ustawianiu pól
			resumeWatching: function() {
				ignoreChanges = false;
				// Nowy snapshot po aktualizacji
				setTimeout(function() {
					dataSnapshot = takeSnapshot();
				}, 100);
			},
			// Ręczne ustawienie snapshotu
			takeSnapshot: function() { dataSnapshot = takeSnapshot(); },
			// Sync danych z WC -> popup (odwrotny kierunek)
			// FIX 2026-03-02v2: billing_phone MOZE zawierac prefix w wartosci (po wyborze z popup)
			// lub NIE zawierac (reczne wpisanie). Obslugujemy OBA przypadki.
			syncToPopup: function() {
				var snap = takeSnapshot();
				var rawPhone = snap['#billing_phone'] || '';
				var fullPhone = rawPhone;
				// Jesli phone NIE zaczyna sie od + -- dodaj prefix z wizualnego elementu
				if (rawPhone && rawPhone.charAt(0) !== '+') {
					var prefixEl = $('.inpost-phone-prefix');
					var prefix = prefixEl.length ? prefixEl.text().trim() : '+48';
					fullPhone = prefix + ' ' + rawPhone;
				}
				// Else: phone już ma prefix — użyj as-is
				window.inpostUserData = {
					firstName: snap['#billing_first_name'] || '',
					lastName: snap['#billing_last_name'] || '',
					email: snap['#billing_email'] || '',
					phone: fullPhone
				};
				inpostLog('[InPost Sync] 🔄 WC → popup sync:', window.inpostUserData);
				return window.inpostUserData;
			}
		};

		inpostLog('[InPost Sync] ✅ Bidirectional sync zainstalowany');
		inpostLog('[InPost Sync] 💡 API: window.InPostFieldSync.pauseWatching() / .resumeWatching() / .syncToPopup()');
	})();

})(jQuery);
