const menuOpenIconEle = '<i class="fa-solid fa-bars"></i>';
const closeMenuIconEle = '<i class="fa-solid fa-xmark"></i>';
let isMobileView = null;
let openSubMenus = [];
let openMenus = [];

function neatnote_setupMenu() {
	const navbar = document.querySelector('.NeatNote-menubar .neatnote_navbar');
	if (!navbar) return;

	const isMobile = window.innerWidth <= 992;

	// Only re-run if view type changed
	if (isMobile === isMobileView && isMobileView !== null) return;
	isMobileView = isMobile;

	// Cleanup old state
	document.querySelectorAll('.neatnote-expand-menu').forEach(btn => btn.remove());
	document.querySelectorAll('.neatnote-child-expand').forEach(btn => btn.remove());

	document.querySelectorAll('.neatnote-sub-menu').forEach(subMenu => {
		subMenu.style.display = '';
		subMenu.classList.remove('neatnote-submenu-open');
		const toggle = subMenu.previousElementSibling;
		if (toggle && toggle.classList.contains('neatnote-child-expand')) {
			toggle.classList.remove('neatnote-child-open');
			toggle.setAttribute('aria-expanded', 'false');
		} else if (toggle && toggle.classList.contains('neatnote-ToggleButton')) {
			toggle.setAttribute('aria-expanded', 'false');
		}
	});

	openSubMenus = [];
	openMenus = [];

	if (isMobile) {
		// Mobile Menu Toggle
		navbar.style.display = 'none';

		const expandMenuButton = document.createElement('button');
		expandMenuButton.className = 'neatnote-expand-menu';
		expandMenuButton.setAttribute('tabindex', '0');
		expandMenuButton.setAttribute('aria-expanded', 'false');
		expandMenuButton.setAttribute('aria-label', 'Toggle menu');
		expandMenuButton.innerHTML = menuOpenIconEle;
		navbar.before(expandMenuButton);

		expandMenuButton.addEventListener('click', () => {
			const isOpen = expandMenuButton.classList.toggle('neatnote-expand-active');
			navbar.style.display = isOpen ? 'block' : 'none';
			expandMenuButton.innerHTML = isOpen ? closeMenuIconEle : menuOpenIconEle;
			expandMenuButton.setAttribute('aria-expanded', isOpen);
		});

		// Mobile submenu toggle buttons
		document.querySelectorAll('.neatnote-sub-menu').forEach(subMenu => {
			const toggleBtn = document.createElement('span');
			toggleBtn.className = 'neatnote-child-expand';
			toggleBtn.setAttribute('tabindex', '0');
			toggleBtn.setAttribute('aria-expanded', 'false');
			toggleBtn.setAttribute('aria-label', 'Toggle submenu');
			toggleBtn.innerHTML = '<i></i><i></i>';
			subMenu.before(toggleBtn);
			subMenu.style.display = 'none';

			toggleBtn.addEventListener('click', () => neatnote_toggleSubMenu(toggleBtn));
			toggleBtn.addEventListener('keydown', e => {
				if (e.key === 'Enter' || e.key === ' ') {
					e.preventDefault();
					neatnote_toggleSubMenu(toggleBtn);
				}
			});
		});

		document.addEventListener('keydown', neatnote_escKeyHandler);

		document.addEventListener('focusout', function (event) {
			if (!event.relatedTarget || !navbar.contains(event.relatedTarget)) {
				neatnote_closeAllMenus();
			}
		});
	} else {
		// Desktop: keep menu visible
		navbar.style.display = 'block';
	}

	// Desktop submenu keyboard support (always attach)
	document.querySelectorAll('.neatnote_navbar ul li .neatnote-ToggleButton').forEach(button => {
		const submenu = button.parentElement.nextElementSibling;

		button.addEventListener('keydown', function (event) {
			if (event.key === 'Enter' || event.key === ' ') {
				const isExpanded = button.getAttribute('aria-expanded') === 'true';

				button.closest('ul').querySelectorAll('.neatnote-sub-menu').forEach(sub => {
					if (sub !== submenu) {
						sub.classList.remove('neatnote-submenu-open');
						sub.previousElementSibling?.setAttribute('aria-expanded', 'false');
						openMenus = openMenus.filter(menu => menu !== sub);
					}
				});

				if (isExpanded) {
					submenu.classList.remove('neatnote-submenu-open');
					openMenus = openMenus.filter(menu => menu !== submenu);
				} else {
					submenu.classList.add('neatnote-submenu-open');
					openMenus.push(submenu);
				}

				button.setAttribute('aria-expanded', !isExpanded);
			}

			if (event.key === 'Escape' && openMenus.length > 0) {
				const lastOpen = openMenus.pop();
				lastOpen.classList.remove('neatnote-submenu-open');
				lastOpen.previousElementSibling.setAttribute('aria-expanded', 'false');
				lastOpen.previousElementSibling.focus();
			}
		});
	});

	// Desktop submenu open on focus
	document.querySelectorAll('.neatnote_navbar ul li .neatnote-sub-menu').forEach(submenu => {
		submenu.addEventListener('focusin', () => {
			submenu.classList.add('neatnote-submenu-open');
			submenu.previousElementSibling?.setAttribute('aria-expanded', 'true');
		});
		submenu.addEventListener('focusout', () => {
			if (!submenu.contains(document.activeElement)) {
				submenu.classList.remove('neatnote-submenu-open');
				submenu.previousElementSibling?.setAttribute('aria-expanded', 'false');
			}
		});
	});
}

function neatnote_toggleSubMenu(toggleBtn) {
	const subMenu = toggleBtn.nextElementSibling;
	if (!subMenu) return;

	toggleBtn.parentElement.querySelectorAll('.neatnote-child-expand').forEach(sibling => {
		if (sibling !== toggleBtn) {
			sibling.classList.remove('neatnote-child-open');
			sibling.setAttribute('aria-expanded', 'false');
			const siblingSubMenu = sibling.nextElementSibling;
			if (siblingSubMenu) siblingSubMenu.style.display = 'none';
			openSubMenus = openSubMenus.filter(menu => menu !== sibling);
		}
	});

	const isOpen = toggleBtn.classList.toggle('neatnote-child-open');
	subMenu.style.display = isOpen ? 'block' : 'none';
	toggleBtn.setAttribute('aria-expanded', isOpen);

	if (isOpen) {
		openSubMenus.push(toggleBtn);
	} else {
		openSubMenus = openSubMenus.filter(menu => menu !== toggleBtn);
	}
}

function neatnote_escKeyHandler(event) {
	if (event.key === 'Escape') {
		if (openSubMenus.length > 0) {
			const lastOpen = openSubMenus.pop();
			lastOpen.classList.remove('neatnote-child-open');
			lastOpen.setAttribute('aria-expanded', 'false');
			const subMenu = lastOpen.nextElementSibling;
			if (subMenu) subMenu.style.display = 'none';
			lastOpen.focus();
		} else {
			neatnote_closeAllMenus();
		}
	}
}

function neatnote_closeAllMenus() {
	const navbar = document.querySelector('.NeatNote-menubar .neatnote_navbar');
	const expandMenuButton = document.querySelector('.neatnote-expand-menu');

	if (navbar) navbar.style.display = 'none';

	if (expandMenuButton) {
		expandMenuButton.classList.remove('neatnote-expand-active');
		expandMenuButton.setAttribute('aria-expanded', 'false');
		expandMenuButton.innerHTML = menuOpenIconEle;
	}

	document.querySelectorAll('.neatnote-child-expand').forEach(el => {
		el.classList.remove('neatnote-child-open');
		el.setAttribute('aria-expanded', 'false');
		const subMenu = el.nextElementSibling;
		if (subMenu) subMenu.style.display = 'none';
	});

	openSubMenus = [];
	openMenus = [];
}

// Run on load and resize
document.addEventListener('DOMContentLoaded', neatnote_setupMenu);
window.addEventListener('resize', neatnote_setupMenu);
