(function () {
	'use strict';

	var INVENTORY_NAV_COLLAPSED_KEY = 'logistica_inventory_nav_collapsed_v2';
	var CONVERSION_NAV_COLLAPSED_KEY = 'logistica_conversion_nav_collapsed_v1';
	var ADMIN_ONLY_CONTEXT_TABS = ['logistica-configuracion'];
	var documentClickBound = false;

	function resolveShell(node) {
		return node && node.closest ? node.closest('[data-logistica-inventory-shell]') : null;
	}

	function getActiveConversionBoard(shell, options) {
		var activePanel;
		var board;
		var opts = options || {};
		var activeOnly = !!opts.activePanelOnly;

		if (!shell) {
			return null;
		}

		activePanel = shell.querySelector('.logistica-tab-panel.is-active:not([hidden])');
		if (activePanel) {
			board = activePanel.querySelector('[data-config-section-board]');
			if (board) {
				return board;
			}

			board = activePanel.querySelector('[data-user-panel-section-board]');
			if (board) {
				return board;
			}

			board = activePanel.querySelector('[data-conversion-board]');
			if (board) {
				return board;
			}

			// En pestañas con paneles: no usar boards de otras pestañas ocultas.
			if (activeOnly || shell.querySelector('.logistica-tab-panel')) {
				return null;
			}
		}

		if (activeOnly) {
			return null;
		}

		board = shell.querySelector('[data-config-section-board]');
		if (board) {
			return board;
		}

		board = shell.querySelector('[data-user-panel-section-board]');
		if (board) {
			return board;
		}

		board = shell.querySelector('[data-conversion-board]');
		if (board && board.matches('[data-conversion-board]')) {
			return board;
		}

		return null;
	}

	function boardHasSectionNavLinks(board) {
		var nav;
		var links;

		if (!board) {
			return false;
		}

		nav = board.querySelector('[data-conversion-nav], [data-logistica-config-nav], [data-logistica-user-panel-nav]');
		if (!nav || nav.hidden) {
			return false;
		}

		links = nav.querySelectorAll(
			'a.logistica-conversion-nav__link:not([hidden]), ' +
			'a[data-config-section-nav]:not([hidden]), ' +
			'button[data-config-section-nav]:not([hidden]), ' +
			'a[data-user-panel-section-nav]:not([hidden]), ' +
			'.logistica-conversion-nav__list a:not([hidden])'
		);

		return links.length > 0;
	}

	function syncAppRailInventoryButton(shell, collapsed) {
		var railMenuBtn = shell.querySelector('.logistica-app-rail [data-action="toggle-inventory-nav"]');
		var visibleTabLinks;

		if (!railMenuBtn) {
			return;
		}

		visibleTabLinks = shell.querySelectorAll('[data-logistica-tabs] [data-logistica-tab]:not([hidden])');
		if (!visibleTabLinks.length) {
			railMenuBtn.hidden = true;
			railMenuBtn.setAttribute('aria-expanded', 'false');
			railMenuBtn.classList.remove('is-active');
			return;
		}

		railMenuBtn.hidden = false;
		railMenuBtn.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
		railMenuBtn.classList.toggle('is-active', !collapsed);
	}

	function updateSectionNavBackdrop(shell) {
		var board;
		var open;
		var backdrop;

		if (!shell) {
			return;
		}

		board = getActiveConversionBoard(shell, { activePanelOnly: true });
		open = !!(boardHasSectionNavLinks(board) && !board.classList.contains('is-nav-collapsed'));
		backdrop = shell.querySelector('.logistica-section-nav-backdrop');
		document.body.classList.toggle('logistica-section-nav-open', open);

		if (backdrop) {
			backdrop.setAttribute('aria-hidden', open ? 'false' : 'true');
			backdrop.tabIndex = open ? 0 : -1;
		}
	}

	function mapTabForContextSwitch(tab, targetContext) {
		var mappedTab = tab || 'logistica';

		if ('operations' === targetContext && ADMIN_ONLY_CONTEXT_TABS.indexOf(mappedTab) !== -1) {
			return 'logistica';
		}

		return mappedTab;
	}

	function buildContextPanelUrl(targetContext, tab) {
		var url = new URL(window.location.href);

		if ('config' === targetContext) {
			url.searchParams.set('config', '1');
		} else {
			url.searchParams.delete('config');
		}

		url.searchParams.set('tab', tab);
		url.hash = '';

		return url.toString();
	}

	function resolveShellActiveTab(shell) {
		var activeLink;
		var params;
		var tab;

		if (!shell) {
			return 'logistica';
		}

		activeLink = shell.querySelector('[data-logistica-tab].nav-tab-active');
		if (activeLink) {
			return activeLink.getAttribute('data-logistica-tab') || 'logistica';
		}

		params = new URLSearchParams(window.location.search);
		tab = params.get('tab');
		if (tab) {
			return tab;
		}

		return shell.getAttribute('data-logistica-initial-tab') || 'logistica';
	}

	function syncAppRailContextPins(shell, tab) {
		var configPin;
		var operationsPin;
		var resolvedTab = tab || resolveShellActiveTab(shell);

		if (!shell || !resolvedTab) {
			return;
		}

		configPin = shell.querySelector('[data-logistica-context-pin="config"]');
		operationsPin = shell.querySelector('[data-logistica-context-pin="operations"]');

		if (configPin) {
			configPin.href = buildContextPanelUrl(
				'config',
				mapTabForContextSwitch(resolvedTab, 'config')
			);
		}

		if (operationsPin) {
			operationsPin.href = buildContextPanelUrl(
				'operations',
				mapTabForContextSwitch(resolvedTab, 'operations')
			);
		}
	}

	function syncAppRailSectionButton(shell) {
		var railSectionBtn = shell.querySelector('.logistica-app-rail [data-action="toggle-section-nav"]');
		var board;
		var collapsed;

		if (!railSectionBtn) {
			return;
		}

		board = getActiveConversionBoard(shell, { activePanelOnly: true });
		if (!boardHasSectionNavLinks(board)) {
			railSectionBtn.hidden = true;
			railSectionBtn.setAttribute('aria-expanded', 'false');
			railSectionBtn.classList.remove('is-active');
			if (board) {
				board.classList.add('is-nav-collapsed');
			}
			updateSectionNavBackdrop(shell);
			return;
		}

		railSectionBtn.hidden = false;
		collapsed = board.classList.contains('is-nav-collapsed');
		railSectionBtn.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
		railSectionBtn.classList.toggle('is-active', !collapsed);
		updateSectionNavBackdrop(shell);
	}

	function setSectionNavCollapsed(board, collapsed) {
		var navToggle;
		var reopenButton;
		var shell;

		if (!board) {
			return;
		}

		board.classList.toggle('is-nav-collapsed', collapsed);
		navToggle = board.querySelector('.logistica-conversion-nav__toggle');
		reopenButton = board.querySelector('.logistica-conversion-nav-reopen');

		if (navToggle) {
			navToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
			navToggle.title = collapsed ? 'Mostrar menú' : 'Ocultar menú';
		}

		if (reopenButton) {
			reopenButton.hidden = !collapsed;
			reopenButton.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
		}

		shell = board.closest('[data-logistica-inventory-shell]');
		if (shell) {
			syncAppRailSectionButton(shell);
		}

		try {
			localStorage.setItem(CONVERSION_NAV_COLLAPSED_KEY, collapsed ? '1' : '0');
		} catch (error) {
			// Ignore storage errors.
		}
	}

	function toggleSectionNavBoard(board) {
		if (!board) {
			return;
		}

		setSectionNavCollapsed(board, !board.classList.contains('is-nav-collapsed'));
	}

	function closeAllSectionNavs(shell) {
		if (!shell) {
			return;
		}

		shell.querySelectorAll('[data-conversion-board]:not(.is-nav-collapsed), [data-config-section-board]:not(.is-nav-collapsed), [data-user-panel-section-board]:not(.is-nav-collapsed)').forEach(function (board) {
			setSectionNavCollapsed(board, true);
		});
	}

	function setInventoryNavCollapsed(shell, collapsed) {
		var navToggle;
		var reopenButton;
		var backdrop;

		if (!shell) {
			return;
		}

		if (!collapsed) {
			closeAllSectionNavs(shell);
		}

		shell.classList.toggle('is-nav-collapsed', collapsed);
		navToggle = shell.querySelector('.logistica-inventory-nav__toggle');
		reopenButton = shell.querySelector('.logistica-inventory-nav-reopen');
		backdrop = shell.querySelector('.logistica-inventory-nav-backdrop');

		if (navToggle) {
			navToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
			navToggle.title = collapsed ? 'Mostrar menú' : 'Ocultar menú';
		}

		if (reopenButton) {
			reopenButton.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
			reopenButton.setAttribute('aria-hidden', collapsed ? 'false' : 'true');
			reopenButton.tabIndex = collapsed ? 0 : -1;
		}

		if (backdrop) {
			backdrop.setAttribute('aria-hidden', collapsed ? 'true' : 'false');
			backdrop.tabIndex = collapsed ? -1 : 0;
		}

		syncAppRailInventoryButton(shell, collapsed);
		syncAppRailSectionButton(shell);
		document.body.classList.toggle('logistica-inventory-nav-open', !collapsed);

		try {
			localStorage.setItem(INVENTORY_NAV_COLLAPSED_KEY, collapsed ? '1' : '0');
		} catch (error) {
			// Ignore storage errors.
		}
	}

	function toggleInventoryNav(shell) {
		if (!shell) {
			return;
		}

		setInventoryNavCollapsed(shell, !shell.classList.contains('is-nav-collapsed'));
	}

	function toggleSectionNav(shell) {
		var board;

		if (!shell) {
			return;
		}

		board = getActiveConversionBoard(shell);
		if (!board) {
			return;
		}

		if (board.classList.contains('is-nav-collapsed') && !shell.classList.contains('is-nav-collapsed')) {
			setInventoryNavCollapsed(shell, true);
		}

		toggleSectionNavBoard(board);
	}

	function readSectionNavCollapsedState(board) {
		var collapsed = true;
		var stored;

		if (!board) {
			return true;
		}

		if (board.classList.contains('is-nav-collapsed')) {
			return true;
		}

		try {
			stored = localStorage.getItem(CONVERSION_NAV_COLLAPSED_KEY);
			if (stored !== null) {
				collapsed = stored === '1';
			}
		} catch (error) {
			collapsed = true;
		}

		return collapsed;
	}

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

		board.dataset.conversionNavBound = '1';
		setSectionNavCollapsed(board, readSectionNavCollapsedState(board));
	}

	function initSectionNavs() {
		document.querySelectorAll('[data-conversion-board], [data-config-section-board], [data-user-panel-section-board]').forEach(initSectionNavBoard);
	}

	function handleDocumentClick(event) {
		var sectionToggle = event.target.closest('[data-action="toggle-section-nav"], [data-action="toggle-conversion-nav"]');
		var inventoryToggle = event.target.closest('[data-action="toggle-inventory-nav"]');
		var shell;
		var board;
		var tabLink;

		if (sectionToggle || inventoryToggle) {
			shell = resolveShell(event.target);
			if (!shell) {
				return;
			}

			event.preventDefault();

			if (sectionToggle) {
				if (sectionToggle.matches('[data-action="toggle-conversion-nav"]')) {
					board = sectionToggle.closest('[data-conversion-board]');
					if (!board) {
						return;
					}

					if (board.classList.contains('is-nav-collapsed') && !shell.classList.contains('is-nav-collapsed')) {
						setInventoryNavCollapsed(shell, true);
					}

					toggleSectionNavBoard(board);
					return;
				}

				toggleSectionNav(shell);
				return;
			}

			toggleInventoryNav(shell);
			return;
		}

		shell = resolveShell(event.target);
		if (!shell) {
			return;
		}

		tabLink = event.target.closest('[data-logistica-tab]');
		if (!tabLink || tabLink.classList.contains('logistica-inventory-nav__frontend-link')) {
			return;
		}

		if (!shell.classList.contains('is-nav-collapsed')) {
			setInventoryNavCollapsed(shell, true);
		}
	}

	function bindDocumentClick() {
		if (documentClickBound) {
			return;
		}

		documentClickBound = true;
		document.addEventListener('click', handleDocumentClick, true);
	}

	function readCollapsedState(shell) {
		var collapsed = true;
		var stored;
		var isConfig = shell.getAttribute('data-logistica-panel-context') === 'config'
			|| shell.classList.contains('logistica-config');

		if (isConfig) {
			return shell.classList.contains('is-nav-collapsed');
		}

		try {
			stored = localStorage.getItem(INVENTORY_NAV_COLLAPSED_KEY);
			if (stored !== null) {
				collapsed = stored === '1';
			}
		} catch (error) {
			collapsed = true;
		}

		return collapsed;
	}

	function initInventoryNav() {
		bindDocumentClick();
		initSectionNavs();

		document.querySelectorAll('[data-logistica-inventory-shell]').forEach(function (shell) {
			if (shell.dataset.inventoryNavBound === '1') {
				syncAppRailSectionButton(shell);
				syncAppRailContextPins(shell);
				return;
			}

			shell.dataset.inventoryNavBound = '1';
			setInventoryNavCollapsed(shell, readCollapsedState(shell));
			syncAppRailSectionButton(shell);
			syncAppRailContextPins(shell);
		});
	}

	window.LogisticaPanelNav = {
		init: initInventoryNav,
		initSectionNavs: initSectionNavs,
		setInventoryNavCollapsed: setInventoryNavCollapsed,
		setSectionNavCollapsed: setSectionNavCollapsed,
		toggleInventoryNav: toggleInventoryNav,
		toggleSectionNav: toggleSectionNav,
		syncAppRailInventoryButton: syncAppRailInventoryButton,
		syncAppRailSectionButton: syncAppRailSectionButton,
		syncAppRailContextPins: syncAppRailContextPins,
		getActiveConversionBoard: getActiveConversionBoard
	};

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