(function () {
	'use strict';

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

	function bindLifecycleBoard(board) {
		if (!board || board.dataset.lifecycleBound === '1') {
			return;
		}

		var admin = window.LogisticaAdmin || {};
		var ajaxUrl = admin.ajaxUrl || '';
		var nonce = admin.lifecycleNonce || '';
		var exportBase = admin.adminPostUrl || '';
		var canRestore = admin.canRestoreLifecycle !== false;
		var canPurge = admin.canPurgeLifecycle === true;

		var scope = 'audit';
		var state = {
			page: 1,
			pageSize: 25,
			search: '',
			module_key: '',
			status: 'deleted',
			date_from: '',
			date_to: ''
		};

		var head = board.querySelector('[data-lifecycle-table-head]');
		var body = board.querySelector('[data-lifecycle-table-body]');
		var meta = board.querySelector('[data-lifecycle-filter-meta]');
		var badge = board.querySelector('[data-lifecycle-filter-badge]');
		var statusWrap = board.querySelector('[data-lifecycle-filter-status-wrap]');
		var searchInput = board.querySelector('[data-lifecycle-filter-search]');
		var moduleSelect = board.querySelector('[data-lifecycle-filter-module]');
		var statusSelect = board.querySelector('[data-lifecycle-filter-status]');
		var dateFromInput = board.querySelector('[data-lifecycle-filter-date-from]');
		var dateToInput = board.querySelector('[data-lifecycle-filter-date-to]');
		var clearBtn = board.querySelector('[data-action="clear-lifecycle-filters"]');
		var exportLink = board.querySelector('[data-lifecycle-export]');
		var pagination = board.querySelector('[data-lifecycle-pagination]');
		var pageInfo = board.querySelector('[data-lifecycle-page-info]');
		var pageLabel = board.querySelector('[data-lifecycle-page-label]');
		var pageSizeSelect = board.querySelector('[data-lifecycle-page-size]');
		var prevBtn = board.querySelector('[data-action="lifecycle-page-prev"]');
		var nextBtn = board.querySelector('[data-action="lifecycle-page-next"]');

		if (!head || !body) {
			return;
		}

		var HEADERS = {
			audit: [
				{ key: 'created_at', label: 'Fecha' },
				{ key: 'module_label', label: 'Módulo' },
				{ key: 'entity_type', label: 'Tipo' },
				{ key: 'entity_id', label: 'ID' },
				{ key: 'action', label: 'Acción' },
				{ key: 'summary', label: 'Resumen' },
				{ key: 'created_by_name', label: 'Usuario' },
				{ key: 'ip_address', label: 'IP' }
			],
			trash: [
				{ key: 'deleted_at', label: 'Eliminado' },
				{ key: 'module_label', label: 'Módulo' },
				{ key: 'entity_type', label: 'Tipo' },
				{ key: 'entity_label', label: 'Etiqueta' },
				{ key: 'entity_id', label: 'ID' },
				{ key: 'status', label: 'Estado' },
				{ key: 'deleted_by_name', label: 'Usuario' },
				{ key: '_actions', label: 'Acción' }
			],
			versions: [
				{ key: 'created_at', label: 'Fecha' },
				{ key: 'module_label', label: 'Módulo' },
				{ key: 'entity_type', label: 'Tipo' },
				{ key: 'entity_id', label: 'ID' },
				{ key: 'version_no', label: 'Versión' },
				{ key: 'summary', label: 'Resumen' },
				{ key: 'created_by_name', label: 'Usuario' },
				{ key: '_actions', label: 'Acción' }
			]
		};

		function renderHead() {
			var cols = HEADERS[scope] || HEADERS.audit;
			var html = '<tr>';
			cols.forEach(function (col) {
				html += '<th scope="col">' + escapeHtml(col.label) + '</th>';
			});
			html += '</tr>';
			head.innerHTML = html;
		}

		function hasActiveFilters() {
			return Boolean(state.search || state.module_key || state.date_from || state.date_to || (scope === 'trash' && state.status !== 'deleted'));
		}

		function syncFilterUi() {
			var active = hasActiveFilters();
			if (badge) {
				badge.hidden = !active;
			}
			if (clearBtn) {
				clearBtn.disabled = !active;
			}
			if (statusWrap) {
				statusWrap.hidden = scope !== 'trash';
			}
		}

		function updateExportLink() {
			if (!exportLink || !exportBase) {
				return;
			}
			var url = new URL(exportBase, window.location.origin);
			url.searchParams.set('action', 'logistica_export_lifecycle');
			url.searchParams.set('scope', scope);
			url.searchParams.set('_wpnonce', nonce);
			if (state.search) {
				url.searchParams.set('search', state.search);
			}
			if (state.module_key) {
				url.searchParams.set('module_key', state.module_key);
			}
			if (scope === 'trash' && state.status) {
				url.searchParams.set('status', state.status);
			}
			if (state.date_from) {
				url.searchParams.set('date_from', state.date_from);
			}
			if (state.date_to) {
				url.searchParams.set('date_to', state.date_to);
			}
			exportLink.href = url.toString();
		}

		function renderRows(items) {
			var cols = HEADERS[scope] || HEADERS.audit;
			if (!items.length) {
				body.innerHTML = '<tr><td colspan="' + cols.length + '">' + escapeHtml('Sin registros para los filtros actuales.') + '</td></tr>';
				return;
			}

			var html = '';
			items.forEach(function (item) {
				html += '<tr>';
				cols.forEach(function (col) {
					if (col.key === '_actions') {
						if (scope === 'trash' && item.can_restore && canRestore) {
							html += '<td class="logistica-lifecycle-actions">';
							html += '<button type="button" class="button button-small" data-lifecycle-restore-trash="' + escapeHtml(item.id) + '">Restaurar</button>';
							if (item.can_purge && canPurge) {
								html += ' <button type="button" class="button button-small button-link-delete" data-lifecycle-purge-trash="' + escapeHtml(item.id) + '">Eliminar definitivamente</button>';
							}
							html += '</td>';
						} else if (scope === 'versions' && canRestore) {
							html += '<td><button type="button" class="button button-small" data-lifecycle-restore-version="' + escapeHtml(item.id) + '">Restaurar</button></td>';
						} else {
							html += '<td></td>';
						}
						return;
					}
					html += '<td>' + escapeHtml(item[col.key] || '') + '</td>';
				});
				html += '</tr>';
			});
			body.innerHTML = html;
		}

		function updatePagination(total) {
			var totalPages = Math.max(1, Math.ceil(total / state.pageSize));
			if (state.page > totalPages) {
				state.page = totalPages;
			}
			var start = (state.page - 1) * state.pageSize;
			var from = total > 0 ? start + 1 : 0;
			var to = Math.min(start + state.pageSize, total);

			if (pageLabel) {
				pageLabel.textContent = total > 0 ? ('Página ' + state.page + ' de ' + totalPages) : '';
			}
			if (pageInfo) {
				pageInfo.textContent = total > 0 ? ('Mostrando ' + from + '-' + to + ' de ' + total + ' registros') : '';
			}
			if (prevBtn) {
				prevBtn.disabled = state.page <= 1 || total === 0;
			}
			if (nextBtn) {
				nextBtn.disabled = state.page >= totalPages || total === 0;
			}
			if (pagination) {
				pagination.hidden = false;
			}
		}

		function fetchRows() {
			var colCount = (HEADERS[scope] || HEADERS.audit).length;

			if (!ajaxUrl || !nonce) {
				body.innerHTML = '<tr><td colspan="' + colCount + '">No se pudo cargar la trazabilidad (sesión o nonce).</td></tr>';
				return Promise.resolve();
			}

			body.innerHTML = '<tr><td colspan="' + colCount + '">Cargando…</td></tr>';

			var params = new URLSearchParams();
			params.set('action', 'logistica_query_lifecycle');
			params.set('nonce', nonce);
			params.set('scope', scope);
			params.set('page', String(state.page));
			params.set('page_size', String(state.pageSize));
			if (state.search) {
				params.set('search', state.search);
			}
			if (state.module_key) {
				params.set('module_key', state.module_key);
			}
			if (scope === 'trash') {
				params.set('status', state.status);
			}
			if (state.date_from) {
				params.set('date_from', state.date_from);
			}
			if (state.date_to) {
				params.set('date_to', state.date_to);
			}

			return fetch(ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
				body: params.toString()
			})
				.then(function (response) {
					return response.text().then(function (text) {
						var payload = null;
						try {
							payload = text ? JSON.parse(text) : null;
						} catch (err) {
							throw new Error('Respuesta inválida del servidor al consultar trazabilidad.');
						}
						if (!response.ok) {
							throw new Error((payload && payload.data && payload.data.message) || ('Error HTTP ' + response.status));
						}
						return payload;
					});
				})
				.then(function (payload) {
					if (!payload || !payload.success) {
						throw new Error((payload && payload.data && payload.data.message) || 'Error al consultar.');
					}
					var items = (payload.data && payload.data.items) || [];
					var total = parseInt((payload.data && payload.data.total) || 0, 10) || 0;
					renderRows(items);
					updatePagination(total);
					if (meta) {
						meta.textContent = total + ' registro(s)';
						meta.hidden = false;
					}
				})
				.catch(function (error) {
					body.innerHTML = '<tr><td colspan="' + colCount + '">' + escapeHtml(error.message || 'Error al cargar.') + '</td></tr>';
				});
		}

		function setScope(nextScope) {
			scope = nextScope;
			state.page = 1;
			board.querySelectorAll('[data-lifecycle-scope]').forEach(function (btn) {
				btn.classList.toggle('is-active', btn.getAttribute('data-lifecycle-scope') === scope);
			});
			renderHead();
			syncFilterUi();
			updateExportLink();
			fetchRows();
		}

		function postAction(action, extra) {
			var params = new URLSearchParams();
			params.set('action', action);
			params.set('nonce', nonce);
			Object.keys(extra || {}).forEach(function (key) {
				params.set(key, extra[key]);
			});
			return fetch(ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
				body: params.toString()
			}).then(function (response) { return response.json(); });
		}

		board.addEventListener('click', function (event) {
			var scopeBtn = event.target.closest('[data-lifecycle-scope]');
			if (scopeBtn) {
				setScope(scopeBtn.getAttribute('data-lifecycle-scope') || 'audit');
				return;
			}

			if (event.target.closest('[data-action="lifecycle-page-prev"]')) {
				state.page -= 1;
				fetchRows();
				return;
			}

			if (event.target.closest('[data-action="lifecycle-page-next"]')) {
				state.page += 1;
				fetchRows();
				return;
			}

			var restoreTrash = event.target.closest('[data-lifecycle-restore-trash]');
			if (restoreTrash) {
				var trashId = restoreTrash.getAttribute('data-lifecycle-restore-trash');
				restoreTrash.disabled = true;
				postAction('logistica_restore_lifecycle_trash', { trash_id: trashId }).then(function (payload) {
					if (!payload || !payload.success) {
						window.alert((payload && payload.data && payload.data.message) || 'No se pudo restaurar.');
						restoreTrash.disabled = false;
						return;
					}
					fetchRows();
				});
				return;
			}

			var restoreVersion = event.target.closest('[data-lifecycle-restore-version]');
			if (restoreVersion) {
				var versionId = restoreVersion.getAttribute('data-lifecycle-restore-version');
				restoreVersion.disabled = true;
				postAction('logistica_restore_lifecycle_version', { version_id: versionId }).then(function (payload) {
					if (!payload || !payload.success) {
						window.alert((payload && payload.data && payload.data.message) || 'No se pudo restaurar la versión.');
						restoreVersion.disabled = false;
						return;
					}
					fetchRows();
				});
				return;
			}

			var purgeTrash = event.target.closest('[data-lifecycle-purge-trash]');
			if (purgeTrash) {
				var purgeId = purgeTrash.getAttribute('data-lifecycle-purge-trash');
				if (!window.confirm('¿Eliminar definitivamente este registro? Esta acción no se puede deshacer.')) {
					return;
				}
				purgeTrash.disabled = true;
				postAction('logistica_purge_lifecycle_trash', { trash_id: purgeId }).then(function (payload) {
					if (!payload || !payload.success) {
						window.alert((payload && payload.data && payload.data.message) || 'No se pudo eliminar definitivamente.');
						purgeTrash.disabled = false;
						return;
					}
					fetchRows();
				});
			}
		});

		if (searchInput) {
			var searchTimer = null;
			searchInput.addEventListener('input', function () {
				clearTimeout(searchTimer);
				searchTimer = setTimeout(function () {
					state.search = String(searchInput.value || '').trim();
					state.page = 1;
					syncFilterUi();
					updateExportLink();
					fetchRows();
				}, 250);
			});
		}

		if (moduleSelect) {
			moduleSelect.addEventListener('change', function () {
				state.module_key = String(moduleSelect.value || '');
				state.page = 1;
				syncFilterUi();
				updateExportLink();
				fetchRows();
			});
		}

		if (statusSelect) {
			statusSelect.addEventListener('change', function () {
				state.status = String(statusSelect.value || 'deleted');
				state.page = 1;
				syncFilterUi();
				updateExportLink();
				fetchRows();
			});
		}

		function bindDateFilter(input, key) {
			if (!input) {
				return;
			}
			input.addEventListener('change', function () {
				state[key] = String(input.value || '');
				state.page = 1;
				syncFilterUi();
				updateExportLink();
				fetchRows();
			});
		}

		bindDateFilter(dateFromInput, 'date_from');
		bindDateFilter(dateToInput, 'date_to');

		if (clearBtn) {
			clearBtn.addEventListener('click', function () {
				state.search = '';
				state.module_key = '';
				state.status = 'deleted';
				state.date_from = '';
				state.date_to = '';
				state.page = 1;
				if (searchInput) {
					searchInput.value = '';
				}
				if (moduleSelect) {
					moduleSelect.value = '';
				}
				if (statusSelect) {
					statusSelect.value = 'deleted';
				}
				if (dateFromInput) {
					dateFromInput.value = '';
				}
				if (dateToInput) {
					dateToInput.value = '';
				}
				syncFilterUi();
				updateExportLink();
				fetchRows();
			});
		}

		if (pageSizeSelect) {
			pageSizeSelect.addEventListener('change', function () {
				state.pageSize = parseInt(pageSizeSelect.value, 10) || 25;
				state.page = 1;
				fetchRows();
			});
		}

		board.dataset.lifecycleBound = '1';
		renderHead();
		syncFilterUi();
		updateExportLink();
		fetchRows();
	}

	function initAll() {
		document.querySelectorAll('[data-lifecycle-board]').forEach(bindLifecycleBoard);
	}

	window.LogisticaLifecycleTables = {
		init: initAll,
		bind: bindLifecycleBoard
	};

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

	document.addEventListener('logistica:tab-loaded', function (event) {
		var tab = event && event.detail ? event.detail.tab : '';
		var panel = event && event.detail ? event.detail.panel : null;
		if (tab === 'logistica-configuracion' || (panel && panel.querySelector('[data-lifecycle-board]'))) {
			window.setTimeout(initAll, 0);
		}
	});
})();
