/**
 * Front-end JavaScript
 *
 * The JavaScript code you place here will be processed by esbuild. The output
 * file will be created at `../js/script.min.js` and enqueued in
 * `../functions.php`.
 *
 * For esbuild documentation, please see:
 * https://esbuild.github.io/
 */

document.addEventListener('DOMContentLoaded', function () {
	// Navigation Submenu Toggle
	const submenuToggles = document.querySelectorAll(
		'.wp-block-navigation-submenu__toggle'
	);

	submenuToggles.forEach(function (toggle) {
		toggle.addEventListener('click', function (event) {
			event.preventDefault();
			event.stopPropagation();

			// Get the parent submenu item
			const parentItem = toggle.closest('.wp-block-navigation-submenu');

			if (parentItem) {
				// Find the submenu container
				const submenuContainer = parentItem.querySelector(
					'.wp-block-navigation__submenu-container'
				);

				if (submenuContainer) {
					// Toggle the submenu visibility
					const isOpen = parentItem.classList.contains('is-open');

					if (isOpen) {
						// Close the submenu
						parentItem.classList.remove('is-open');
						toggle.setAttribute('aria-expanded', 'false');
					} else {
						// Close all other open submenus at the same level
						const siblings = parentItem.parentElement.querySelectorAll(
							'.wp-block-navigation-submenu.is-open'
						);
						siblings.forEach(function (sibling) {
							if (sibling !== parentItem) {
								sibling.classList.remove('is-open');
								const siblingToggle = sibling.querySelector(
									'.wp-block-navigation-submenu__toggle'
								);
								if (siblingToggle) {
									siblingToggle.setAttribute('aria-expanded', 'false');
								}
							}
						});

						// Open the submenu
						parentItem.classList.add('is-open');
						toggle.setAttribute('aria-expanded', 'true');
					}
				}
			}
		});
	});

	// Close submenus when clicking outside
	document.addEventListener('click', function (event) {
		if (!event.target.closest('.wp-block-navigation-submenu')) {
			const openSubmenus = document.querySelectorAll(
				'.wp-block-navigation-submenu.is-open'
			);
			openSubmenus.forEach(function (submenu) {
				submenu.classList.remove('is-open');
				const toggle = submenu.querySelector(
					'.wp-block-navigation-submenu__toggle'
				);
				if (toggle) {
					toggle.setAttribute('aria-expanded', 'false');
				}
			});
		}
	});
});
