const foodordAdminNavInit = () => {
	const navs = document.querySelectorAll('.foodord-admin-nav');
	if (!navs.length) {
		return;
	}

	const ensureActiveItemVisible = (nav) => {
		const list = nav.querySelector('.foodord-admin-nav__list');
		if (!list) {
			return;
		}

		const activeLink = list.querySelector('.foodord-admin-nav__link.is-active, .foodord-admin-nav__link[aria-current="page"]');
		if (!activeLink || !(activeLink instanceof HTMLElement)) {
			return;
		}

		const activeItem = activeLink.closest('.foodord-admin-nav__item');
		if (!activeItem || !(activeItem instanceof HTMLElement)) {
			return;
		}

		const listRect = list.getBoundingClientRect();
		const itemRect = activeItem.getBoundingClientRect();
		const isOutOfView = itemRect.left < listRect.left || itemRect.right > listRect.right;
		if (!isOutOfView) {
			return;
		}

		const centeredLeft = activeItem.offsetLeft - Math.max((list.clientWidth - activeItem.offsetWidth) / 2, 0);
		list.scrollLeft = Math.max(0, centeredLeft);
	};

	const getOverflowItemIndexes = (nav) => {
		const list = nav.querySelector('.foodord-admin-nav__list');
		const wrapper = nav.querySelector('.foodord-admin-nav__wrapper');
		const toggleWrap = nav.querySelector('.foodord-admin-nav__toggle-wrap');
		const items = list ? Array.from(list.querySelectorAll('.foodord-admin-nav__item')) : [];

		if (!list || !wrapper || !toggleWrap || !items.length) {
			return [];
		}

		const listStyle = window.getComputedStyle(list);
		const wrapperStyle = window.getComputedStyle(wrapper);
		const gap = parseFloat(listStyle.columnGap || listStyle.gap || '0') || 0;
		const itemWidths = items.map((item) => item.offsetWidth);
		const totalItemWidth = itemWidths.reduce((total, width) => total + width, 0) + Math.max(itemWidths.length - 1, 0) * gap;
		const wrapperPadding = (parseFloat(wrapperStyle.paddingLeft || '0') || 0) + (parseFloat(wrapperStyle.paddingRight || '0') || 0);
		const availableWithoutToggle = wrapper.clientWidth - wrapperPadding;

		if (totalItemWidth <= availableWithoutToggle) {
			return [];
		}

		list.scrollLeft = 0;

		const listRect = list.getBoundingClientRect();
		const visibleRight = listRect.left + list.clientWidth;
		const wrappedIndexes = items.reduce((indexes, item, index) => {
			const itemRect = item.getBoundingClientRect();
			if (itemRect.right > visibleRight + 1) {
				indexes.push(index);
			}

			return indexes;
		}, []);

		return wrappedIndexes;
	};

	const setupNav = (nav) => {
		const list = nav.querySelector('.foodord-admin-nav__list');
		const dropdown = nav.querySelector('.foodord-admin-nav__dropdown');
		const toggleWrap = nav.querySelector('.foodord-admin-nav__toggle-wrap');
		const toggleBtn = toggleWrap ? toggleWrap.querySelector('.foodord-admin-nav__toggle') : null;

		if (!list || !dropdown || !toggleWrap || !toggleBtn) {
			return;
		}

		dropdown.innerHTML = '';
		toggleWrap.setAttribute('aria-hidden', 'true');
		nav.classList.remove('is-collapsible', 'is-expanded', 'is-ready');

		const items = Array.from(list.querySelectorAll('.foodord-admin-nav__item'));
		if (!items.length) {
			nav.classList.add('is-ready');
			return;
		}

		const wrappedIndexes = getOverflowItemIndexes(nav);
		if (wrappedIndexes.length > 0) {
			toggleWrap.setAttribute('aria-hidden', 'false');
			nav.classList.add('is-collapsible');

			wrappedIndexes.forEach((itemIndex) => {
				if (items[itemIndex]) {
					dropdown.appendChild(items[itemIndex].cloneNode(true));
				}
			});
		}

		nav.classList.add('is-ready');
		window.requestAnimationFrame(() => {
			ensureActiveItemVisible(nav);
		});
	};

	const updateToggleLabel = (nav, toggleBtn) => {
		const textEl = toggleBtn.querySelector('.foodord-admin-nav__toggle-text');
		const moreText = toggleBtn.getAttribute('data-more-text') || 'More';
		const lessText = toggleBtn.getAttribute('data-less-text') || 'Less';
		const expanded = nav.classList.contains('is-expanded');

		toggleBtn.setAttribute('aria-expanded', expanded ? 'true' : 'false');
		if (textEl) {
			textEl.textContent = expanded ? lessText : moreText;
		}
	};

	const setupAndSyncNav = (nav) => {
		const toggleBtn = nav.querySelector('.foodord-admin-nav__toggle');
		if (!toggleBtn) {
			return;
		}

		setupNav(nav);
		updateToggleLabel(nav, toggleBtn);
	};

	navs.forEach((nav) => {
		const toggleBtn = nav.querySelector('.foodord-admin-nav__toggle');
		if (!toggleBtn) {
			return;
		}

		setupAndSyncNav(nav);

		toggleBtn.addEventListener('click', (e) => {
			e.stopPropagation();
			const isExpanded = nav.classList.contains('is-expanded');
			nav.classList.toggle('is-expanded', !isExpanded);
			updateToggleLabel(nav, toggleBtn);
		});
	});

	document.addEventListener('click', (e) => {
		navs.forEach(nav => {
			if (nav.classList.contains('is-expanded') && !nav.contains(e.target)) {
				nav.classList.remove('is-expanded');
				const toggleBtn = nav.querySelector('.foodord-admin-nav__toggle');
				if (toggleBtn) updateToggleLabel(nav, toggleBtn);
			}
		});
	});

	let resizeTimer = 0;
	window.addEventListener('resize', () => {
		window.clearTimeout(resizeTimer);
		resizeTimer = window.setTimeout(() => {
			navs.forEach(setupAndSyncNav);
		}, 60);
	});

	window.addEventListener('load', () => {
		navs.forEach(setupAndSyncNav);
	});

	if (document.fonts && document.fonts.ready) {
		document.fonts.ready.then(() => {
			navs.forEach(setupAndSyncNav);
		});
	}

	if ('ResizeObserver' in window) {
		const observer = new ResizeObserver((entries) => {
			const changedNavs = new Set();
			entries.forEach((entry) => {
				const nav = entry.target.closest('.foodord-admin-nav');
				if (nav) {
					changedNavs.add(nav);
				}
			});

			changedNavs.forEach(setupAndSyncNav);
		});

		navs.forEach((nav) => {
			const wrapper = nav.querySelector('.foodord-admin-nav__wrapper');
			if (wrapper) {
				observer.observe(wrapper);
			}
		});
	}
};

document.addEventListener('DOMContentLoaded', foodordAdminNavInit);
