
/* ============================================================
 * PS_LOG — F12 telemetria FLOW (zawsze widoczna, bez debug gate)
 * Wstawiony 2026-05-14, plugin v4.4.1
 * ============================================================ */
window.PS_LOG = window.PS_LOG || function(stage, msg, data){
    try {
        var ts = new Date().toISOString().substring(11,23);
        var hdr = '%c[PS-FLOW ' + ts + ']%c ' + stage + (msg ? ' %c' + msg : '');
        var s1 = 'background:#1e40af;color:#fff;padding:2px 6px;border-radius:3px;font-weight:bold';
        var s2 = 'color:#1e40af;font-weight:bold;padding-left:4px';
        var s3 = 'color:#374151';
        if (data !== undefined) {
            console.groupCollapsed(hdr, s1, s2, s3);
            try { console.log('data:', data); } catch(_){}
            try { console.log('href:', location.pathname); } catch(_){}
            console.groupEnd();
        } else {
            console.log(hdr, s1, s2, s3);
        }
    } catch(_){}
};
/* Parcel Selector — Label Stepper UI JS.
 * Auto-extracted from PHP for WP.org compliance. NONCE + ORDER_ID injected via wp_add_inline_script. */

		(function(){
			var AJAX = (typeof ajaxurl !== 'undefined') ? ajaxurl : '/wp-admin/admin-ajax.php';
			// NONCE set by wp_add_inline_script (before)
			// ORDER_ID set by wp_add_inline_script (before)

			// ── Stage 1: consent ──
			var cb1 = document.getElementById('psle-cb-service');
			var btn1 = document.getElementById('psle-btn-service');
			if (cb1 && btn1) {
				btn1.disabled = !cb1.checked;
				btn1.style.opacity = cb1.checked ? '1' : '.55';
				cb1.addEventListener('change', function(){
					btn1.disabled = !cb1.checked;
					btn1.style.opacity = cb1.checked ? '1' : '.55';
				});
				btn1.addEventListener('click', function(){
					if (!cb1.checked) return;
					window.PS_LOG && window.PS_LOG('STAGE1_CONSENT', 'POST parcselect_label_accept_consent', {order_id: ORDER_ID});
					btn1.disabled = true; btn1.textContent = 'Zapisuję…';
					var fd = new FormData();
					fd.append('action', 'parcselect_label_accept_consent');
					fd.append('nonce', NONCE);
					fd.append('order_id', ORDER_ID);
					fd.append('step', 'service');
					fetch(AJAX, {method:'POST', body:fd, credentials:'same-origin'})
						.then(function(r){return r.json();})
						.then(function(j){
							window.PS_LOG && window.PS_LOG('STAGE1_RESPONSE', j && j.success ? 'success - reload' : 'fail', j);
							if (j && j.success) {
								// Visual: stage1 → done, stage2 → active, reload to show live state
								var s1 = document.getElementById('psle-stage1');
								var s2 = document.getElementById('psle-stage2');
								if (s1) { s1.classList.remove('active'); s1.classList.add('done'); }
								if (s2) { s2.classList.remove('pending'); s2.classList.add('active'); }
								setTimeout(function(){ window.location.reload(); }, 400);
							} else {
								btn1.disabled = false;
								btn1.textContent = 'Akceptuję i przechodzę dalej →';
								alert('Błąd: ' + ((j && j.data && j.data.message) || 'nieznany'));
							}
						})
						.catch(function(e){
							btn1.disabled = false;
							btn1.textContent = 'Akceptuję i przechodzę dalej →';
							alert('Błąd sieci: ' + (e && e.message ? e.message : 'unknown'));
						});
				});
			}

			// ── Stage 2: sender form ──
			var cb2 = document.getElementById('psle-cb-sender');
			var btn2 = document.getElementById('psle-btn-sender');
			var errBox = document.getElementById('psle-sender-error');
			function showErr(msg){ if(errBox){errBox.textContent=msg;errBox.style.display='block';} }
			if (cb2 && btn2) {
				btn2.disabled = !cb2.checked;
				btn2.style.opacity = cb2.checked ? '1' : '.55';
				cb2.addEventListener('change', function(){
					btn2.disabled = !cb2.checked;
					btn2.style.opacity = cb2.checked ? '1' : '.55';
				});
				btn2.addEventListener('click', function(){
					if (!cb2.checked) return;
					if (errBox) errBox.style.display = 'none';
					var name = document.getElementById('psf-name').value.trim();
					var street = document.getElementById('psf-street').value.trim();
					var postcode = document.getElementById('psf-postcode').value.trim();
					var city = document.getElementById('psf-city').value.trim();
					var phone = document.getElementById('psf-phone').value.trim();
					var email = (document.getElementById('psf-email').value || '').trim();
					var lockerId = ((document.getElementById('psf-locker-id') || {value:''}).value || '').trim().toUpperCase();

					// NS-63 2026-04-30: PEŁNA WALIDACJA wszystkich pól Furgonetka.
					// Każde pole musi spełniać konkretny regex — błędne = czerwone tło + adnotacja + focus.
					function markErr(elId, errId, msg) {
						var inp = document.getElementById(elId);
						var err = document.getElementById(errId);
						if (inp) { inp.style.borderColor = '#dc2626'; inp.style.background = '#fef2f2'; inp.focus(); }
						if (err) { err.textContent = '⚠️ ' + msg; err.style.display = 'block'; }
						showErr(msg);
					}
					function clearErr(elId, errId) {
						var inp = document.getElementById(elId);
						var err = document.getElementById(errId);
						if (inp) { inp.style.borderColor = ''; inp.style.background = ''; }
						if (err) { err.style.display = 'none'; }
					}

					// Real-time clear: jak user poprawi pole, czerwone tlo znika od razu (przed kolejnym submit).
					if (!btn2._psRealtimeBound) {
						btn2._psRealtimeBound = true;
						var _psFieldCheckers = {
							'psf-name':     function(v){ return /^[\p{L}\s\-]+\s+[\p{L}\s\-]+$/u.test(v.trim()); },
							'psf-street':   function(v){ v = v.trim(); return v.length >= 3 && /[\p{L}]/u.test(v); },
							'psf-postcode': function(v){ return /^\d{2}-\d{3}$/.test(v.trim()); },
							'psf-city':     function(v){ return /^[\p{L}\s\-]+$/u.test(v.trim()); },
							'psf-phone':    function(v){
								var d = v.replace(/\D/g,'');
								if (d.length === 11 && d.indexOf('48') === 0) d = d.substring(2);
								return d.length === 9;
							},
							'psf-email':    function(v){ v = v.trim(); return !v || /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v); },
							'psf-locker-id':function(v){ v = v.trim().toUpperCase(); return !v || /^[A-Z]{3}\d{2}[A-Z]?$/.test(v); }
						};
						Object.keys(_psFieldCheckers).forEach(function(id){
							var el = document.getElementById(id);
							if (!el) return;
							var handler = function(){
								try {
									if (_psFieldCheckers[id](el.value)) {
										clearErr(id, id + '-error');
										if (errBox) errBox.style.display = 'none';
									}
								} catch(e){}
							};
							el.addEventListener('input', handler);
							el.addEventListener('change', handler);
						});
					}

					// 1. Imię + Nazwisko (≥2 słowa, tylko litery + spacje + myślniki)
					if (!/^[\p{L}\s\-]+\s+[\p{L}\s\-]+$/u.test(name)) {
						markErr('psf-name','psf-name-error','Wymagane IMIĘ i NAZWISKO — min. 2 słowa, tylko litery (np. "Jan Kowalski")');
						return;
					}
					clearErr('psf-name','psf-name-error');
					// 2. Ulica (min 3 znaki, dozwolone litery+cyfry+spacje+./,/-)
					if (street.length < 3 || !/[\p{L}]/u.test(street)) {
						markErr('psf-street','psf-street-error','Podaj poprawną ulicę z numerem (np. "Warszawska 15")');
						return;
					}
					clearErr('psf-street','psf-street-error');
					// 3. Kod pocztowy XX-XXX
					if (!/^\d{2}-\d{3}$/.test(postcode)) {
						markErr('psf-postcode','psf-postcode-error','Format kodu: XX-XXX (np. "00-001")');
						return;
					}
					clearErr('psf-postcode','psf-postcode-error');
					// 4. Miasto (tylko litery, spacje, myślniki — Furgonetka notAlpha regex)
					if (!/^[\p{L}\s\-]+$/u.test(city)) {
						markErr('psf-city','psf-city-error','Miasto — tylko litery, bez cyfr i znaków specjalnych (np. "Warszawa")');
						return;
					}
					clearErr('psf-city','psf-city-error');
					// 5. Telefon - FREE = tylko PL, prefix +48 osobny element UI
					var phoneDigits = phone.replace(/\D/g, '');
					if (phoneDigits.length === 11 && phoneDigits.indexOf('48') === 0) {
						phoneDigits = phoneDigits.substring(2);
					}
					if (phoneDigits.length !== 9) {
						markErr('psf-phone','psf-phone-error','Wpisz dokladnie 9 cyfr numeru telefonu (np. 500 365 249)');
						return;
					}
					phone = '+48' + phoneDigits;
					clearErr('psf-phone','psf-phone-error');
					// 6. Email (jeśli wpisany — format email)
					if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) {
						markErr('psf-email','psf-email-error','Niepoprawny format email');
						return;
					}
					clearErr('psf-email','psf-email-error');
					// 7. Paczkomat nadawczy (opcjonalny, jeśli wpisany — format InPost LUK01M)
					if (lockerId && !/^[A-Z]{3}\d{2}[A-Z]?$/.test(lockerId)) {
						markErr('psf-locker-id','psf-locker-id-error','Format paczkomatu: 3 litery + 2 cyfry + opcjonalna litera (np. WAW01M, LUK01M)');
						return;
					}
					clearErr('psf-locker-id','psf-locker-id-error');
					window.PS_LOG && window.PS_LOG('STAGE2_VALIDATION_PASS', 'wszystkie pola OK', {name: name, street: street, postcode: postcode, city: city, phone: phone, email: email, lockerId: lockerId});
					// NS-63: define _doSave inline — uruchamiane natychmiast (gdy brak locker)
					// LUB po pomyślnej walidacji paczkomatu w InPost API.
					function _doSave() {
						window.PS_LOG && window.PS_LOG('STAGE2_SAVE_REQUEST', 'POST parcselect_label_save_sender', {order_id: ORDER_ID});
						btn2.disabled = true; btn2.textContent = 'Zapisuję…';
						var fd = new FormData();
						fd.append('action', 'parcselect_label_save_sender');
						fd.append('nonce', NONCE);
						fd.append('order_id', ORDER_ID);
						fd.append('sender_name', name);
						fd.append('sender_company', document.getElementById('psf-company').value.trim());
						fd.append('sender_street', street);
						fd.append('sender_postcode', postcode);
						fd.append('sender_city', city);
						fd.append('sender_phone', phone);
						fd.append('sender_email', email);
						if (lockerId) fd.append('sender_locker_id', lockerId);
						var saveDefEl = document.getElementById('psle-cb-save-default');
						if (saveDefEl) fd.append('save_as_default', saveDefEl.checked ? '1' : '0');
						fetch(AJAX, {method:'POST', body:fd, credentials:'same-origin'})
							.then(function(r){return r.json();})
							.then(function(j){
								window.PS_LOG && window.PS_LOG('STAGE2_SAVE_RESPONSE', j && j.success ? 'success - reload' : 'fail', j);
								if (j && j.success) {
									var s2 = document.getElementById('psle-stage2');
									if (s2) { s2.classList.remove('active'); s2.classList.add('done'); }
									setTimeout(function(){ window.location.reload(); }, 400);
								} else {
									btn2.disabled = false;
									btn2.textContent = 'Zapisz dane i generuj etykietę →';
									var msg = (j && j.data && (j.data.detail || j.data.message)) || 'Błąd zapisu';
									showErr(msg);
								}
							})
							.catch(function(e){
								btn2.disabled = false;
								btn2.textContent = 'Zapisz dane i generuj etykietę →';
								showErr('Błąd sieci: ' + (e && e.message ? e.message : 'unknown'));
							});
					}
					// NS-86 2026-04-30: removed external InPost API validation call
					// per WP.org submission scope. Format regex check (client-side regex
					// /^[A-Z]{3}\d{2}[A-Z]?$/) wystarczy. Klient odpowiedzialny za
					// poprawnosc paczkomat ID (Furgonetka API zwroci blad jesli zly).
					_doSave();
					return;
				});
			}
			// v4.1.7 Stage R: receiver accept handler
			var cbR = document.getElementById('psle-cb-receiver');
			var btnR = document.getElementById('psle-btn-receiver');
			if (cbR && btnR) {
				btnR.disabled = !cbR.checked;
				btnR.style.opacity = cbR.checked ? '1' : '.55';
				cbR.addEventListener('change', function(){
					btnR.disabled = !cbR.checked;
					btnR.style.opacity = cbR.checked ? '1' : '.55';
				});
				btnR.addEventListener('click', function(){
					if (!cbR.checked) return;
					window.PS_LOG && window.PS_LOG('STAGER_ACCEPT', 'POST parcselect_label_accept_receiver', {order_id: ORDER_ID});
					btnR.disabled = true; btnR.textContent = 'Zapisuję…';
					var fd = new FormData();
					fd.append('action', 'parcselect_label_accept_receiver');
					fd.append('nonce', NONCE);
					fd.append('order_id', ORDER_ID);
					fetch(AJAX, {method:'POST', body:fd, credentials:'same-origin'})
						.then(function(r){return r.json();})
						.then(function(j){
							if (j && j.success) {
								var sR = document.getElementById('psle-stageR');
								if (sR) { sR.classList.remove('active'); sR.classList.add('done'); }
								setTimeout(function(){ window.location.reload(); }, 400);
							} else {
								btnR.disabled = false;
								btnR.textContent = 'Akceptuję dane odbiorcy →';
								alert('Błąd: ' + ((j && j.data && j.data.message) || 'nieznany'));
							}
						})
						.catch(function(e){
							btnR.disabled = false;
							btnR.textContent = 'Akceptuję dane odbiorcy →';
							alert('Błąd sieci: ' + (e && e.message ? e.message : 'unknown'));
						});
				});
			}

			// v4.1.9 REQUEST-21: click-to-minimize on every done panel (cross-stage, NIE Stage 6 PDF)
			document.querySelectorAll('.psle-progress-col.done, .psle-stage3-col.done, .el-col-right.done').forEach(function(panel){
				panel.style.cursor = 'pointer';
				panel.title = 'Klik: zwiń/rozwiń';
				panel.addEventListener('click', function(e){
					// Don't toggle when clicking interactive elements
					if (e.target.closest('a, button, input, label, .pscp-btn, .el-pdf-actions, .parcsepa-copy-btn')) return;
					panel.classList.toggle('psle-minimized');
				});
			});

			// v4.1.13 REQUEST-29: AUTO-MINIMIZE done panels gdy overflow w psle-layout3.
			// Priority FIFO: Zgoda (s1) -> Nadawca (s2) -> Odbiorca (sR) -> Gabaryt (stage3-col).
			// Stage 6 PDF (el-col-pdf) NIGDY nie minimalizuje (chronione w v4.1.8).
			var layout = document.querySelector('.psle-layout3');
			if (layout) {
				var PRIORITY_MIN = ['psle-stage1', 'psle-stage2', 'psle-stageR', 'psle-stage4'];
				var EXPAND_BACK_THRESHOLD = 200; // px wolnego miejsca = pozwol expandowac
				function _PSLE_autoMinimize() {
					if (!layout) return;
					// Sprawdz czy children overflow (sumaryczna szerokosc > kontener width)
					var containerW = layout.clientWidth;
					if (containerW <= 0) return;
					var children = Array.prototype.slice.call(layout.children);
					var totalW = 0;
					children.forEach(function(c){
						if (c.offsetWidth > 0 && getComputedStyle(c).display !== 'none') {
							totalW += c.offsetWidth + 16; // gap
						}
					});
					var overflow = totalW - containerW;
					// Sprawdz czy mamy aktywny stage5 lub el-col-pdf (priorytetowe)
					var hasActiveLater = !!document.querySelector('#psle-stage5, .el-col-pdf:not(.empty)');
					if (overflow > 20 && hasActiveLater) {
						// Auto-minimize w kolejnosci priority dopoki overflow nadal istnieje
						for (var i = 0; i < PRIORITY_MIN.length; i++) {
							var el = document.getElementById(PRIORITY_MIN[i]);
							if (!el) continue;
							if (el.classList.contains('psle-minimized')) continue;
							if (!el.classList.contains('done') && !el.classList.contains('psle-progress-col') && !el.classList.contains('psle-stage3-col')) continue;
							// Auto-minimize tylko done panels
							if (el.classList.contains('done') || el.querySelector('.psle-stage-done-msg[style*="display:block"], .psle-stage-done-msg:not([style*="display:none"])')) {
								el.classList.add('psle-minimized');
								el.dataset.psleAutoMinimized = '1';
								// Recalculate overflow after each minimize
								var newTotal = 0;
								Array.prototype.slice.call(layout.children).forEach(function(c){
									if (c.offsetWidth > 0 && getComputedStyle(c).display !== 'none') newTotal += c.offsetWidth + 16;
								});
								if (newTotal - containerW <= 20) break; // wystarczy
							}
						}
					} else if (overflow < -EXPAND_BACK_THRESHOLD) {
						// Mamy duzo wolnego miejsca - auto-expand back (tylko te ktore byly auto-minimized, NIE user-toggle)
						for (var j = PRIORITY_MIN.length - 1; j >= 0; j--) {
							var el2 = document.getElementById(PRIORITY_MIN[j]);
							if (el2 && el2.dataset.psleAutoMinimized === '1' && el2.classList.contains('psle-minimized')) {
								el2.classList.remove('psle-minimized');
								delete el2.dataset.psleAutoMinimized;
								break; // expand jeden na raz, recheck nastepnie
							}
						}
					}
				}
				// Run on load + on resize (debounced)
				var _resizeTimer = null;
				window.addEventListener('resize', function(){
					clearTimeout(_resizeTimer);
					_resizeTimer = setTimeout(_PSLE_autoMinimize, 150);
				});
				// Initial run after layout settles
				setTimeout(_PSLE_autoMinimize, 100);
				setTimeout(_PSLE_autoMinimize, 500);
				// Re-run gdy nowy panel zostanie dodany (np. po reload Stage 5 pojawia sie)
				if (window.MutationObserver) {
					var mo = new MutationObserver(function(){ setTimeout(_PSLE_autoMinimize, 100); });
					mo.observe(layout, { childList: true, subtree: false });
				}
			}
		})();