/* Parcel Selector — Label QR & payment polling.
 * Vars (orderId, qrUri, expiresAt, nonce) injected via wp_add_inline_script. */

		(function(){
			var order_id = window.PARCSELECT_LABEL_VARS.orderId;
			var qrUri    = window.PARCSELECT_LABEL_VARS.qrUri;
			var expiresAt = window.PARCSELECT_LABEL_VARS.expiresAt;
			var nonce    = window.PARCSELECT_LABEL_VARS.nonce;
			var ajaxUrl  = (typeof ajaxurl !== 'undefined') ? ajaxurl : '/wp-admin/admin-ajax.php';

			// --- QR render (NS-38 hotfix 2026-04-30 — race condition fix) ---
			// Library qrcode.min.js loaded in footer (in_footer=true) → moze byc niedostepna w momencie tego inline IIFE.
			// Aktualnie defensive `if (window.QRCode)` powodowal silent fail (puste pole).
			// Fix: retry-poll co 100ms, max 5s. Idempotent (skip jesli juz wyrenderowane).
			// Docelowy fix v4.3.8: server-side PNG z VPS (eliminuje race + XSS attack vector).
			(function renderQR(){
				var qrEl = document.getElementById('parcselect-qr-canvas');
				if (!qrEl || !qrUri) return;
				if (qrEl.querySelector('canvas, img')) return; // juz wyrenderowane
				if (typeof window.QRCode === 'undefined') {
					var attempts = 0;
					var iv = setInterval(function(){
						attempts++;
						if (typeof window.QRCode !== 'undefined') {
							clearInterval(iv);
							renderQR();
						} else if (attempts > 50) {
							clearInterval(iv);
							qrEl.innerHTML = '<div style="padding:80px 0;color:#dc2626;font-size:12px">QR library failed to load (5s timeout)</div>';
							if (window.console) console.error('[PS-LABEL] QRCode library timeout after 5s');
						}
					}, 100);
					return;
				}
				try {
					qrEl.innerHTML = '';
					new QRCode(qrEl, { text: qrUri, width: 216, height: 216,
					                   correctLevel: QRCode.CorrectLevel.M });
				} catch(e) {
					qrEl.innerHTML = '<div style="padding:80px 0;color:#dc2626;font-size:12px">QR error: ' + e.message + '</div>';
				}
			})();

			// --- Timer ---
			if (expiresAt) {
				var expMs = Date.parse(expiresAt);
				var timerEl = document.getElementById('parcselect-timer');
				var fillEl  = document.getElementById('parcselect-progress-fill');
				var totalMs = 30 * 60 * 1000; // 30min TTL
				function tick() {
					// BUG #19 2026-05-15: stop timer gdy polling wykryl local_status='error'
					// (Order expired -> _ps_label_status=error). Bez tego countdown leci 00:00
					// + progress bar tkwi mimo, ze ponizej pokazany jest FAIL panel.
					if (window.__PSLE_stopped) {
						if (timerEl) timerEl.textContent = '--:--';
						if (fillEl) { fillEl.style.width = '0%'; fillEl.style.background = '#9ca3af'; }
						return;
					}
					var left = expMs - Date.now();
					if (left <= 0) {
						if (timerEl) timerEl.textContent = '00:00';
						if (fillEl) { fillEl.style.width = '0%'; fillEl.style.background = '#dc2626'; }
						return;
					}
					var s = Math.floor(left / 1000);
					var mm = Math.floor(s / 60).toString().padStart(2,'0');
					var ss = (s % 60).toString().padStart(2,'0');
					if (timerEl) timerEl.textContent = mm + ':' + ss;
					if (fillEl) {
						var pct = Math.max(0, Math.min(100, (left / totalMs) * 100));
						fillEl.style.width = pct + '%';
						fillEl.style.background = (pct < 20) ? '#dc2626' : (pct < 50 ? '#f59e0b' : '#10b981');
					}
					setTimeout(tick, 1000);
				}
				tick();
			}

			// --- Copy buttons ---
			document.querySelectorAll('.parcsepa-copy-btn').forEach(function(btn){
				btn.addEventListener('click', function(){
					var t = btn.getAttribute('data-copy') || '';
					if (navigator.clipboard && navigator.clipboard.writeText) {
						navigator.clipboard.writeText(t).then(function(){
							var orig = btn.textContent;
							btn.textContent = '✓ Skopiowano';
							btn.classList.add('copied');
							setTimeout(function(){
								btn.textContent = orig;
								btn.classList.remove('copied');
							}, 1500);
						}).catch(function(){});
					}
				});
			});

			// --- Status polling (every 10s) ---
			var statusText = document.getElementById('parcselect-status-text');
			var statusDot  = document.getElementById('parcselect-status-dot');
			var tries = 0;
			var POST_PAID_MAX_MS = 600 * 1000; // 2026-05-15: 90s -> 600s (10 min) - chain CEB+Integrator+Furgonetka moze trwac >7min w peak (case #301). Plugin sweep cron sprawdza Oracle co minute - jesli paid ALE label_url NULL po 600s -> wtedy fire mark_failed.
			var __PSLE_failed_marked = false;
			function poll(){
				tries++;
				// HARD CAP: 30 polls (~5 min total). Nigdy w nieskonczonosc.
				if (tries > 90) {  // FIX A 2026-05-15: 30 -> 90 (15 min coverage zamiast 5 min, zgodne z POST_PAID_MAX_MS=600s+sweep_cron 1min)
					if (statusText) statusText.textContent = '⛔ Polling zatrzymany — wymagana interwencja administratora.';
					return;
				}
				// Post-paid 90s timeout: jesli paid wykryty i minelo >90s bez label_url -> mark FAIL i stop.
				if (window.__PSLE_paid_seen && window.__PSLE_paid_at_ms && !window.__PSLE_label_url_seen) {
					var _elapsed = Date.now() - window.__PSLE_paid_at_ms;
					if (_elapsed > POST_PAID_MAX_MS && !__PSLE_failed_marked) {
						__PSLE_failed_marked = true;
						console.warn('[PSLE] 90s post-paid timeout — marking FAILED');
						var fdF = new FormData();
						fdF.append('action', 'parcselect_label_mark_failed');
						fdF.append('nonce', nonce);
						fdF.append('order_id', order_id);
						fdF.append('reason', 'timeout_90s_no_label');
						fetch(ajaxUrl, {method:'POST', body:fdF, credentials:'same-origin'})
							.then(function(){ window.location.reload(); })
							.catch(function(){ window.location.reload(); });
						return; // STOP polling
					}
				}
				var fd = new FormData();
				fd.append('action', 'parcselect_label_check_payment');
				fd.append('nonce', nonce);
				fd.append('order_id', order_id);
				fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
					.then(function(r){ return r.json(); })
					.then(function(j){
						// NS-72 2026-04-30: pełne F12 console logging — admin widzi w realtime
						// każdy state change, polling response, paid detection, label_url arrival.
						try {
							var _now = new Date().toISOString().substr(11,8);
							var _d = j && j.data || {};
							console.log('%c[PSLE poll #'+tries+' @ '+_now+']%c oracle='+(_d.oracle_status||'?')+' status='+(_d.status||'?')+' label_url='+(_d.label_url?'✓':'✗')+' tracking='+(_d.tracking?'✓':'✗')+' error='+(_d.error?'⚠':'·'),
								'background:#10b981;color:#fff;padding:2px 6px;border-radius:3px;font-weight:700','color:#065f46');
							if (_d.oracle_txid) console.log('  └ TXID:', _d.oracle_txid);
							if (_d.label_url) console.log('  └ LABEL URL:', _d.label_url);
							// On label_url arrival: mark + reload to render success state.
							if (_d.label_url && !window.__PSLE_label_url_seen) {
								window.__PSLE_label_url_seen = true;
								console.log('[PSLE] Label URL arrived — reloading page for success render');
								setTimeout(function(){ window.location.reload(); }, 800);
								return;
							}
							if (_d.error_msg) console.warn('  └ ERROR_MSG:', _d.error_msg);
						} catch(e) {}
						if (j && j.success && j.data) {
							// NS-56 2026-04-30: CEB/Furgonetka error detection — czerwony panel
							// z instrukcją kontaktu po refund. Stop polling — final state.
							if (j.data.error && !window.__PSLE_error_seen) {
								window.__PSLE_error_seen = true;
								// BUG #19 2026-05-15: gdy local_status='error' (np. Order expired ->
								// _ps_label_status=error) trzeba CALKOWICIE UKRYC Stage 4 (QR + countdown
								// + progress bar + adres + amount). Wczesniej UI pokazywal "00:00 / 0%"
								// + QR z FAIL panelem ponizej — klient zdezorientowany. Teraz: hide
								// caly .parcselect-stage4-wrap kontener i pokaz tylko FAIL panel.
								window.__PSLE_stopped = true; // sygnal dla tick()
								try {
									var _stageWrap = document.querySelector('.parcselect-stage4-wrap');
									if (_stageWrap) _stageWrap.style.display = 'none';
									// Defensive — gdyby kiedys uzyto plugin-native Stage 4:
									var _stage4Native = document.getElementById('parcselect-stage4');
									if (_stage4Native) _stage4Native.style.display = 'none';
								} catch(e) {}
								if (window.__PSLE_countdown_iv) {
									try { clearInterval(window.__PSLE_countdown_iv); } catch(e) {}
								}
								var _errBox = document.getElementById('parcselect-label-error');
								if (_errBox) {
									_errBox.style.display = 'block';
									try { _errBox.scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch(e) {}
									// BUG #19: zawsze pokaz blok detali nawet gdy error_msg pusty
									// (klient widzi przynajmniej generyczny komunikat zamiast nic).
									var _msgEl = document.getElementById('parcselect-error-msg');
									var _detEl = document.getElementById('parcselect-error-techdetails');
									var _msgFinal = j.data.error_msg || 'Sesja płatności wygasła — etykieta nie została wygenerowana.';
									if (_msgEl) _msgEl.textContent = _msgFinal;
									if (_detEl) _detEl.style.display = 'block';
								} else {
									// FAIL panel nie istnieje w renderze — fallback reload aby PHP
									// re-renderowal odpowiedni stan (status='error' -> FAIL view).
									console.warn('[PSLE BUG#19] FAIL panel missing — falling back to reload');
									setTimeout(function(){ window.location.reload(); }, 600);
								}
								var _genHide = document.getElementById('parcselect-generating-label');
								if (_genHide) _genHide.style.display = 'none';
								if (window.__PSLE_genlabel_iv) clearInterval(window.__PSLE_genlabel_iv);
								if (statusText) statusText.textContent = '⚠️ Błąd kreacji etykiety — patrz panel poniżej.';
								if (statusDot)  statusDot.style.background = '#dc2626';
								return; // Stop polling — final terminal state
							}
							// NS-54 2026-04-30: full beauty pass on first paid detection.
							// 1) lock entire panel (data-paid="yes" → green gradient + disabled UI)
							// 2) fire fireworks + beep (C5 E5 G5) via PSLE_Confetti
							// 3) animated status text "Potwierdzone na blockchain!"
							// 4) NS-54 v3: pokaz "Generujemy etykietę..." panel + start escalation timer
							if ((j.data.oracle_status === 'paid' || j.data.status === 'paid' || j.data.status === 'completed') && !window.__PSLE_paid_seen) {
								window.__PSLE_paid_seen = true;
								window.__PSLE_paid_at_ms = Date.now();
								var _krok2 = document.getElementById('parcselect-krok2');
								if (_krok2) { _krok2.setAttribute('data-paid', 'yes'); }
								// P0 #2 — natychmiastowy UI swap: ukryc QR / kwote / adres / przyciski wallet.
								// Pokazac duzy zielony banner + 90s countdown przed reload.
								try {
									['parcselect-qr-canvas','parcselect-amount-hero','parcselect-wallet-line','parcselect-wallet-buttons','parcselect-warning-box'].forEach(function(_id){
										var _el = document.getElementById(_id);
										if (_el) { _el.style.display = 'none'; }
									});
									// Hide bigger panel sections by querying common classes used in render_from_pscp_payload.
									var _hideSel = ['.parcselect-payment-amount','.parcselect-payment-qr','.parcselect-payment-address','.parcselect-payment-wallet-buttons'];
									_hideSel.forEach(function(_s){ var _e = document.querySelector(_s); if (_e) _e.style.display = 'none'; });
									// Insert success banner with countdown.
									if (_krok2 && !document.getElementById('parcselect-paid-banner')) {
										var _ban = document.createElement('div');
										_ban.id = 'parcselect-paid-banner';
										_ban.style.cssText = 'margin:16px 0;padding:24px;background:linear-gradient(135deg,#ecfdf5 0%,#d1fae5 100%);border:2px solid #10b981;border-radius:12px;text-align:center;color:#065f46;box-shadow:0 4px 14px rgba(16,185,129,.2);';
										_ban.innerHTML = '<div style="font-size:20px;font-weight:800;margin-bottom:10px">&#10003; P\u0142atno\u015b\u0107 potwierdzona na blockchain</div>' +
											'<div style="font-size:13px;margin-bottom:14px;color:#047857">Generujemy etykiet\u0119 InPost\u2026 (max 90s)</div>' +
											'<div style="background:rgba(255,255,255,.7);border-radius:8px;padding:10px;font-size:12px;font-family:monospace;color:#065f46">' +
												'Pozosta\u0142o: <span id="parcselect-paid-countdown" style="font-weight:800;font-size:16px">90</span> sekund' +
											'</div>' +
											'<div style="height:6px;background:#a7f3d0;border-radius:3px;overflow:hidden;margin-top:10px">' +
												'<div id="parcselect-paid-progress" style="height:100%;background:#10b981;width:100%;transition:width 1s linear"></div>' +
											'</div>';
										var _container = _krok2.querySelector('.parcselect-payment-status') || _krok2;
										_container.insertBefore(_ban, _container.firstChild);
										// Start countdown
										var _secs = 90;
										window.__PSLE_countdown_iv = setInterval(function(){
											_secs--;
											var _c = document.getElementById('parcselect-paid-countdown');
											var _p = document.getElementById('parcselect-paid-progress');
											if (_c) _c.textContent = _secs;
											if (_p) _p.style.width = (_secs / 90 * 100) + '%';
											if (_secs <= 0) { clearInterval(window.__PSLE_countdown_iv); }
										}, 1000);
									}
								} catch(e) { console.warn('[PSLE] paid UI swap error:', e); }
								if (statusText) statusText.textContent = '✓ Potwierdzone na blockchain!';
								if (statusDot)  statusDot.style.background = '#10b981';
								if (window.PSLE_Confetti) {
									try {
										var _panel = _krok2 || document.getElementById('psle-stages') || document.body;
										window.PSLE_Confetti.fire(_panel);
										window.PSLE_Confetti.toast('Płatność potwierdzona na blockchain!');
										setTimeout(function(){
											try { window.PSLE_Confetti.fire(_panel); } catch(e){}
										}, 1600);
									} catch(e){}
								}
								// NS-54 v3: show "Generujemy etykietę..." panel z animowanymi kropeczkami
								var _genBox = document.getElementById('parcselect-generating-label');
								if (_genBox && !j.data.label_url) {
									_genBox.style.display = 'block';
									var _elapsedEl = document.getElementById('parcselect-genlabel-elapsed');
									var _emergencyEl = document.getElementById('parcselect-genlabel-emergency');
									window.__PSLE_genlabel_iv = setInterval(function(){
										if (window.__PSLE_pdf_opened) {
											clearInterval(window.__PSLE_genlabel_iv);
											if (_genBox) { _genBox.style.display = 'none'; }
											return;
										}
										var elapsed = Math.floor((Date.now() - window.__PSLE_paid_at_ms) / 1000);
										if (_elapsedEl) { _elapsedEl.textContent = elapsed; }
										if (elapsed >= 180 && _emergencyEl && _emergencyEl.style.display === 'none') {
											_emergencyEl.style.display = 'block';
										}
									}, 1000);
								}
							}
							// NS-54 v3: gdy paid + brak label_url po 60s/120s → wymusz Oracle re-check
							if (window.__PSLE_paid_seen && !j.data.label_url && !window.__PSLE_pdf_opened) {
								var _e = Math.floor((Date.now() - (window.__PSLE_paid_at_ms || Date.now())) / 1000);
								var _retryInfo = document.getElementById('parcselect-genlabel-retry-info');
								var _retryCount = document.getElementById('parcselect-genlabel-retry-count');
								if (_e >= 60 && !window.__PSLE_recheck_60) {
									window.__PSLE_recheck_60 = true;
									if (_retryCount) _retryCount.textContent = '1';
									if (_retryInfo)  _retryInfo.style.display = 'inline';
									try {
										var fdR = new FormData();
										fdR.append('action', 'parcselect_label_force_recheck');
										fdR.append('nonce', nonce);
										fdR.append('order_id', order_id);
										fetch(ajaxUrl, { method:'POST', body:fdR, credentials:'same-origin' }).catch(function(){});
									} catch(e){}
								}
								if (_e >= 120 && !window.__PSLE_recheck_120) {
									window.__PSLE_recheck_120 = true;
									if (_retryCount) _retryCount.textContent = '2';
									try {
										var fdR2 = new FormData();
										fdR2.append('action', 'parcselect_label_force_recheck');
										fdR2.append('nonce', nonce);
										fdR2.append('order_id', order_id);
										fetch(ajaxUrl, { method:'POST', body:fdR2, credentials:'same-origin' }).catch(function(){});
									} catch(e){}
								}
							}
							// NS-54: auto-open PDF in new tab as soon as label_url arrives,
							// even before reload (so admin sees the label without F5).
							if (j.data.label_url && !window.__PSLE_pdf_opened) {
								window.__PSLE_pdf_opened = true;
								var _genBoxDone = document.getElementById('parcselect-generating-label');
								if (_genBoxDone) { _genBoxDone.style.display = 'none'; }
								if (window.__PSLE_genlabel_iv) { clearInterval(window.__PSLE_genlabel_iv); }
								try {
									window.open(j.data.label_url, '_blank', 'noopener,noreferrer');
								} catch(e){}
							}
							if (j.data.reload) {
								if (statusText) statusText.textContent = '✓ Etykieta gotowa — odświeżam…';
								if (statusDot)  statusDot.style.background = '#10b981';
								setTimeout(function(){ window.location.reload(); }, 1400);
								return;
							}
							if (j.data.status === 'expired') {
								if (statusText) statusText.textContent = 'Sesja wygasła — wygeneruj nową.';
								if (statusDot)  statusDot.style.background = '#dc2626';
								return;
							}
						}
						setTimeout(poll, 10000);
					})
					.catch(function(){ setTimeout(poll, 15000); });
			}
			setTimeout(poll, 5000);
		})();