/**
 * PS_LABEL v2 — iframe loader with onload/timeout fallback to native UI.
 *
 * Decision tree (visible in F12 as `PS-LABEL iframe.*` events):
 *   1. cfg.use_iframe === false           → SKIP iframe, native UI stays.
 *   2. cfg.iframe_params missing/empty    → SKIP, native UI stays.
 *   3. orderId === 0                      → SKIP, not an order edit screen.
 *   4. Render iframe + 8 s onload watchdog.
 *      - onload fires with valid contentWindow size → SUCCESS, hide native.
 *      - onload never fires within 8 s → BLOCKED (X-Frame-Options, CSP
 *        frame-ancestors, network) → tear iframe down, show native UI,
 *        admin_notice with concrete reason.
 *      - onload fires but contentWindow inaccessible (cross-origin throw on
 *        a same-origin probe) → still SUCCESS (expected for cross-origin
 *        iframes — trust the load event).
 *
 * Every decision is console-logged with `PS-LABEL iframe.<step>` so F12 +
 * the metabox accordion show exactly which path the loader took.
 */
(function ($) {
	'use strict';

	var cfg = window.parcselectLabelConfig || {};
	var orderId = 0;
	var iframeBase = (cfg.vps_embed_url || 'https://map.parcelselector.com/embed/label').replace(/\/+$/, '');
	var TIMEOUT_MS = 8000;
	var $wrap, $payStep, $iframeHolder;

	function log(stage, data) {
		try {
			console.log('%cPS-LABEL iframe.' + stage + '%c',
				'color:#fff;background:#7c3aed;padding:1px 6px;border-radius:3px;font-weight:600;', '',
				data || '');
		} catch (e) {}
	}

	function reportToTrail(stage, data) {
		// Mirror the JS-side decision into the server-side trail so the
		// metabox accordion shows the same story without admin opening F12.
		if (!cfg.ajaxUrl || !cfg.nonce || !orderId) return;
		try {
			var body = new FormData();
			body.append('action', 'parcselect_label_iframe_event');
			body.append('nonce', cfg.nonce);
			body.append('order_id', orderId);
			body.append('stage', stage);
			body.append('data', JSON.stringify(data || {}));
			body.append('_ps_debug_internal', '1');
			fetch(cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body });
		} catch (e) {}
	}

	$(document).ready(function () {
		$wrap = $('#ps-label-wrap');
		if (!$wrap.length) {
			log('skip.no_wrap');
			return;
		}
		orderId = parseInt($wrap.data('order-id'), 10) || 0;
		if (!orderId) {
			log('skip.no_order_id');
			return;
		}
		if (cfg.use_iframe === false) {
			log('skip.use_iframe_false', { native_ui: true });
			reportToTrail('skip.use_iframe_disabled');
			return;
		}
		if (!cfg.iframe_params || typeof cfg.iframe_params !== 'object' ||
			Object.keys(cfg.iframe_params).length === 0) {
			log('skip.no_iframe_params', { reason: 'PHP did not provide iframe_params' });
			reportToTrail('skip.no_iframe_params');
			return;
		}

		// Pre-flight: bail if required iframe_params are empty (we'd just
		// render a broken VPS page that errors out). Show concrete reason.
		var required = ['order_id', 'locker_id'];
		var missing = required.filter(function (k) {
			var v = cfg.iframe_params[k];
			return v === undefined || v === null || v === '';
		});
		if (missing.length) {
			log('skip.missing_required', { missing: missing, params_present: Object.keys(cfg.iframe_params) });
			reportToTrail('skip.missing_required', { missing: missing });
			showError('Iframe nie wystartował: brakuje wymaganych pól w order meta: ' + missing.join(', '));
			return;
		}

		renderIframe(cfg.iframe_params);
	});


	function renderIframe(params) {
		var qs = Object.keys(params).filter(function (k) {
			return params[k] !== undefined && params[k] !== null && String(params[k]).length > 0;
		}).map(function (k) {
			return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
		}).join('&');

		var url = iframeBase + '?' + qs;
		log('render.attempt', { url: url, params_count: Object.keys(params).length });
		reportToTrail('render.attempt', { url_path: iframeBase, params_keys: Object.keys(params) });

		$payStep = $('#etyk-step-payment');
		if (!$payStep.length) $payStep = $wrap;

		// Build the iframe but keep it hidden until onload — prevents the
		// "broken iframe icon" flash if X-Frame-Options blocks immediately.
		$iframeHolder = $(
			'<div class="etyk-iframe-holder" style="position:relative;min-height:200px;">' +
			'  <div class="etyk-iframe-loading" style="padding:32px 16px;text-align:center;color:#64748b;font-size:13px;">' +
			'    <div style="margin-bottom:8px;font-size:16px;">⏳</div>' +
			'    Ładowanie modułu płatności VPS…' +
			'  </div>' +
			'</div>'
		);
		$payStep.html($iframeHolder).show();

		var loaded = false;
		var iframe = document.createElement('iframe');
		iframe.src = url;
		iframe.style.cssText = 'width:100%;min-height:820px;border:0;border-radius:10px;display:none;';
		iframe.setAttribute('referrerpolicy', 'no-referrer-when-downgrade');
		// `clipboard-write` only — wildcard `*` is invalid Permissions Policy syntax.
		iframe.setAttribute('allow', 'clipboard-write');
		iframe.onload = function () {
			loaded = true;
			iframe.style.display = 'block';
			$iframeHolder.find('.etyk-iframe-loading').remove();
			log('render.onload', { ok: true });
			reportToTrail('render.onload_ok');
			// Hide the native size picker — VPS iframe takes over.
			$('#ps-label-form').hide();
		};
		iframe.onerror = function (e) {
			log('render.onerror', { error: String(e && e.message || e) });
			reportToTrail('render.onerror', { error: String(e && e.message || e) });
			fallbackToNative('iframe onerror fired');
		};
		$iframeHolder.append(iframe);

		// Watchdog: if onload never fires (X-Frame-Options DENY, CSP
		// frame-ancestors block, network unreachable), fall back to native.
		setTimeout(function () {
			if (loaded) return;
			log('render.timeout', { ms: TIMEOUT_MS, reason: 'onload never fired — likely X-Frame-Options or CSP block' });
			reportToTrail('render.timeout', { ms: TIMEOUT_MS });
			fallbackToNative('Iframe nie załadował się w ' + (TIMEOUT_MS / 1000) +
				' s — prawdopodobnie X-Frame-Options/CSP blokuje. Native UI ma kontrolę.');
		}, TIMEOUT_MS);
	}

	function fallbackToNative(reason) {
		if (!$iframeHolder) return;
		$iframeHolder.remove();
		log('fallback.native', { reason: reason });
		reportToTrail('fallback.native', { reason: reason });
		// Make sure the native size picker is visible — render() left it
		// in the DOM, we never hid it before onload.
		$('#ps-label-form').show();
		// Surface a non-fatal banner so the admin understands why iframe
		// disappeared. Native UI still works (uses ajax.create_session).
		var banner = $(
			'<div style="margin:8px 0;padding:10px 14px;border-radius:6px;background:#fff7ed;border-left:4px solid #f59e0b;color:#9a3412;font-size:12px;">' +
			'  <strong>VPS iframe niedostępny</strong> — używam natywnego UI. <span style="opacity:0.7">' +
			$('<div>').text(reason).html() +
			'</span>' +
			'</div>'
		);
		$wrap.prepend(banner);
	}

	function showError(msg) {
		if (!$wrap || !$wrap.length) return;
		$wrap.prepend(
			'<div style="margin:8px 0;padding:10px 14px;border-radius:6px;background:#fee2e2;border-left:4px solid #dc2626;color:#7f1d1d;font-size:12px;">' +
			'  <strong>Etykietownik:</strong> ' + $('<div>').text(msg).html() +
			'</div>'
		);
	}
})(jQuery);
