(function () {
	'use strict';

	var bridgeApi = null;
	var documentClickBound = false;
	var integrations = {};

	function escapeHtml(value) {
		return String(value == null ? '' : value)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;');
	}

	function adminConfig() {
		return window.LogisticaAdmin || {};
	}

	function postAjax(action, payload, nonce) {
		var config = adminConfig();
		var body = new FormData();
		body.append('action', action);
		body.append('nonce', nonce || '');

		Object.keys(payload || {}).forEach(function (key) {
			var value = payload[key];
			if (value == null) {
				return;
			}
			if (Array.isArray(value)) {
				body.append(key, JSON.stringify(value));
				return;
			}
			body.append(key, value);
		});

		return fetch(config.ajaxUrl || '/wp-admin/admin-ajax.php', {
			method: 'POST',
			credentials: 'same-origin',
			body: body
		}).then(function (response) {
			return response.json();
		});
	}

	function moduleFromTabPanel(panel) {
		if (!panel) {
			return '';
		}
		var slug = panel.getAttribute('data-tab-panel') || '';
		if (slug === 'logistica-planeacion-formado') {
			return 'formado';
		}
		if (slug === 'logistica-planeacion-impresion') {
			return 'impresion';
		}
		return '';
	}

	function resolveModule(contextEl, explicitModule) {
		if (explicitModule) {
			return explicitModule;
		}
		if (!contextEl) {
			return '';
		}
		var fromAttr = contextEl.getAttribute('data-planeacion-pedidos-module');
		if (fromAttr) {
			return fromAttr;
		}
		var panel = contextEl.closest('[data-tab-panel]');
		return moduleFromTabPanel(panel);
	}

	function findModal(module, contextEl) {
		var scopes = [];
		var panel = contextEl ? contextEl.closest('[data-tab-panel]') : null;
		var board = contextEl ? contextEl.closest('[data-planeacion-board]') : null;

		if (panel) {
			scopes.push(panel);
		}
		if (board) {
			scopes.push(board);
		}
		if (contextEl && contextEl.parentElement) {
			scopes.push(contextEl.parentElement);
		}
		scopes.push(document);

		for (var i = 0; i < scopes.length; i++) {
			var modal = scopes[i].querySelector('[data-planeacion-pedidos-modal][data-planeacion-pedidos-module="' + module + '"]');
			if (modal) {
				return modal;
			}
		}

		return null;
	}

	function showDialog(modal) {
		if (!modal) {
			return false;
		}

		if (modal.open && typeof modal.close === 'function') {
			modal.close();
		}

		try {
			if (typeof modal.showModal === 'function') {
				modal.showModal();
			} else {
				modal.setAttribute('open', 'open');
			}
			return true;
		} catch (error) {
			modal.setAttribute('open', 'open');
			return modal.hasAttribute('open');
		}
	}

	function closeDialog(modal) {
		if (!modal) {
			return;
		}
		if (typeof modal.close === 'function') {
			modal.close();
		} else {
			modal.removeAttribute('open');
		}
	}

	function createInstance(module, modal, integration) {
		var rowsBody = modal.querySelector('[data-planeacion-pedidos-rows]');
		var statusEl = modal.querySelector('[data-planeacion-pedidos-status]');
		var daySelect = modal.querySelector('[data-planeacion-pedidos-day]');
		var selectAll = modal.querySelector('[data-planeacion-pedidos-select-all]');
		var scheduleBtn = modal.querySelector('[data-action="planeacion-pedidos-schedule"]');
		var nonceKey = integration.nonceKey || (module === 'formado' ? 'planeacionFormadoNonce' : 'planeacionNonce');
		var loading = false;

		function getNonce() {
			return adminConfig()[nonceKey] || '';
		}

		function setStatus(message, type) {
			if (!statusEl) {
				return;
			}
			statusEl.textContent = message || '';
			statusEl.className = 'logistica-planeacion-pedidos-modal__status';
			if (type) {
				statusEl.classList.add('is-' + type);
			}
		}

		function getSelectedIds() {
			if (!rowsBody) {
				return [];
			}
			return Array.prototype.slice.call(
				rowsBody.querySelectorAll('[data-planeacion-pedidos-row-check]:checked')
			).map(function (input) {
				return parseInt(input.value, 10) || 0;
			}).filter(function (id) {
				return id > 0;
			});
		}

		function syncScheduleButton() {
			if (!scheduleBtn) {
				return;
			}
			var selected = getSelectedIds();
			scheduleBtn.disabled = loading || selected.length === 0;
			scheduleBtn.textContent = selected.length > 0
				? 'Programar seleccionados (' + selected.length + ')'
				: 'Programar seleccionados';
		}

		function renderRows(lineas) {
			var items = Array.isArray(lineas) ? lineas : [];

			if (!rowsBody) {
				return;
			}

			if (!items.length) {
				rowsBody.innerHTML = '<tr class="logistica-planeacion-pedidos-modal__empty"><td colspan="8">No hay pedidos vigentes pendientes de programar en este momento.</td></tr>';
				syncScheduleButton();
				return;
			}

			rowsBody.innerHTML = items.map(function (linea) {
				var entrega = linea.fecha_entrega || linea.fecha_prorroga || '—';
				return '<tr data-planeacion-pedidos-row="' + escapeHtml(linea.linea_id) + '">' +
					'<td class="logistica-planeacion-pedidos-modal__col-check">' +
						'<input type="checkbox" value="' + escapeHtml(linea.linea_id) + '" data-planeacion-pedidos-row-check aria-label="Seleccionar pedido">' +
					'</td>' +
					'<td><strong>' + escapeHtml(linea.oc_numero || '—') + '</strong>' +
						(linea.op ? '<br><span class="logistica-planeacion-pedidos-modal__op">OP ' + escapeHtml(linea.op) + '</span>' : '') +
					'</td>' +
					'<td>' + escapeHtml(linea.cliente || '—') + '</td>' +
					'<td>' + escapeHtml(linea.formado_referencia_label || linea.articulo || '—') + '</td>' +
					'<td>' + escapeHtml(linea.cantidad_pendiente_fmt || linea.cantidad_fmt || '—') + '</td>' +
					'<td>' + escapeHtml(entrega) + '</td>' +
					'<td><span class="logistica-planeacion-pedidos-modal__estado">' + escapeHtml(linea.estado_label || linea.estado || '') + '</span></td>' +
					'<td>' + escapeHtml(linea.board_label || linea.board_slug || '') + '</td>' +
				'</tr>';
			}).join('');

			if (selectAll) {
				selectAll.checked = false;
			}
			syncScheduleButton();
		}

		function loadPending() {
			if (loading) {
				return Promise.resolve();
			}

			loading = true;
			syncScheduleButton();
			setStatus('Cargando pedidos vigentes…', 'loading');

			return postAjax('logistica_get_pedidos_pendientes_planeacion', {
				module: module
			}, getNonce()).then(function (response) {
				loading = false;

				if (!response || !response.success) {
					setStatus((response && response.data && response.data.message) || 'No se pudieron cargar los pedidos.', 'error');
					renderRows([]);
					return;
				}

				var lineas = response.data && response.data.lineas ? response.data.lineas : [];
				setStatus(lineas.length
					? lineas.length + ' pedido(s) disponible(s) para programar.'
					: 'No hay pedidos pendientes de programar. Todas las órdenes vigentes ya están en planeación o no cumplen los criterios.', lineas.length ? 'info' : 'empty');
				renderRows(lineas);
			}).catch(function () {
				loading = false;
				setStatus('Error de conexión al cargar pedidos.', 'error');
				renderRows([]);
			});
		}

		function openModal() {
			setStatus('', '');
			if (rowsBody) {
				rowsBody.innerHTML = '<tr class="logistica-planeacion-pedidos-modal__empty"><td colspan="8">Cargando pedidos…</td></tr>';
			}
			syncScheduleButton();
			showDialog(modal);
			loadPending();
		}

		function closeModal() {
			closeDialog(modal);
		}

		function scheduleSelected() {
			var selected = getSelectedIds();
			if (!selected.length || loading) {
				return;
			}

			var activeIntegration = integrations[module] || integration || {};
			var context = typeof activeIntegration.getContext === 'function' ? activeIntegration.getContext() : {};
			var day = daySelect ? parseInt(daySelect.value, 10) : 0;

			loading = true;
			syncScheduleButton();
			setStatus('Programando pedidos seleccionados…', 'loading');

			postAjax('logistica_programar_pedidos_planeacion', {
				module: module,
				semana_inicio: context.semana_inicio || '',
				maquina: context.maquina || context.machine || '',
				day: Number.isFinite(day) ? day : 0,
				linea_ids: selected
			}, getNonce()).then(function (response) {
				loading = false;

				if (!response || !response.success) {
					setStatus((response && response.data && response.data.message) || 'No se pudieron programar los pedidos.', 'error');
					syncScheduleButton();
					return;
				}

				if (typeof activeIntegration.applySchedule === 'function' && response.data && response.data.schedule) {
					activeIntegration.applySchedule(response.data.schedule);
				}

				if (typeof activeIntegration.onScheduled === 'function') {
					activeIntegration.onScheduled(response.data || {});
				}

				setStatus(response.data.message || 'Pedidos programados.', 'success');
				closeModal();
			}).catch(function () {
				loading = false;
				setStatus('Error de conexión al programar pedidos.', 'error');
				syncScheduleButton();
			});
		}

		function handleAction(action) {
			if (action === 'planeacion-pedidos-open') {
				openModal();
				return true;
			}
			if (action === 'planeacion-pedidos-close') {
				closeModal();
				return true;
			}
			if (action === 'planeacion-pedidos-refresh') {
				loadPending();
				return true;
			}
			if (action === 'planeacion-pedidos-schedule') {
				scheduleSelected();
				return true;
			}
			return false;
		}

		if (!modal.getAttribute('data-planeacion-pedidos-bound')) {
			modal.setAttribute('data-planeacion-pedidos-bound', '1');

			modal.addEventListener('cancel', function (event) {
				event.preventDefault();
				closeModal();
			});

			modal.addEventListener('click', function (event) {
				if (event.target === modal) {
					closeModal();
				}
			});

			if (selectAll) {
				selectAll.addEventListener('change', function () {
					if (!rowsBody) {
						return;
					}
					var checked = !!selectAll.checked;
					rowsBody.querySelectorAll('[data-planeacion-pedidos-row-check]').forEach(function (input) {
						input.checked = checked;
					});
					syncScheduleButton();
				});
			}

			if (rowsBody) {
				rowsBody.addEventListener('change', function (event) {
					if (event.target.matches('[data-planeacion-pedidos-row-check]')) {
						syncScheduleButton();
					}
				});
			}
		}

		return {
			module: module,
			modal: modal,
			openModal: openModal,
			closeModal: closeModal,
			handleAction: handleAction
		};
	}

	function ensureInstance(module, contextEl) {
		if (!module) {
			return null;
		}

		if (bridgeApi._instances[module]) {
			return bridgeApi._instances[module];
		}

		var modal = findModal(module, contextEl);
		if (!modal) {
			return null;
		}

		var instance = createInstance(module, modal, integrations[module] || {});
		bridgeApi._instances[module] = instance;
		return instance;
	}

	function bootDiscoveredModals() {
		document.querySelectorAll('[data-planeacion-pedidos-modal][data-planeacion-pedidos-module]').forEach(function (modal) {
			var module = modal.getAttribute('data-planeacion-pedidos-module');
			if (module) {
				ensureInstance(module, modal);
			}
		});
	}

	function bindDocumentClicks() {
		if (documentClickBound) {
			return;
		}
		documentClickBound = true;

		document.addEventListener('click', function (event) {
			var actionNode = event.target.closest('[data-action^="planeacion-pedidos-"]');
			if (!actionNode) {
				return;
			}

			var action = actionNode.getAttribute('data-action');
			if (!action) {
				return;
			}

			var module = resolveModule(actionNode, '');
			if (!module) {
				var modalHost = actionNode.closest('[data-planeacion-pedidos-modal]');
				module = modalHost ? modalHost.getAttribute('data-planeacion-pedidos-module') : '';
			}
			if (!module) {
				return;
			}

			var instance = ensureInstance(module, actionNode);
			if (!instance) {
				return;
			}

			if (action === 'planeacion-pedidos-open' || instance.modal.contains(actionNode)) {
				event.preventDefault();
				instance.handleAction(action);
			}
		});
	}

	function boot() {
		bootDiscoveredModals();
		bindDocumentClicks();
	}

	bridgeApi = {
		_instances: {},

		open: function (module, contextEl) {
			var instance = ensureInstance(module, contextEl || null);
			if (instance) {
				instance.openModal();
			}
		},

		init: function (options) {
			if (!options || !options.module) {
				return;
			}

			var module = options.module;
			integrations[module] = options;

			var contextEl = options.board || options.root || null;
			var modal = findModal(module, contextEl);
			if (!modal) {
				return;
			}

			bridgeApi._instances[module] = createInstance(module, modal, options);
		}
	};

	window.LogisticaPlaneacionPedidosBridge = bridgeApi;

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', boot);
	} else {
		boot();
	}
}());
