/**
 * Colorful Blog Mobile Menu
 *
 * Modern, accessible mobile navigation with smooth animations,
 * touch-friendly interactions, and keyboard navigation support.
 *
 * @package Colorful Blog
 */

(function() {
	'use strict';

	// DOM Elements
	const smButton = document.getElementById('mmenu-btn');
	const smMenu = document.getElementById('mobile-navigation');
	const mobileMenuBar = document.getElementById('wsm-menu');

	if (!smButton) {
		return;
	}

	// Menu elements may not exist if no menu assigned and no pages exist
	const smOpen = smButton.querySelector('.mopen');
	const smClose = smButton.querySelector('.mclose');
	let overlay = document.querySelector('.mobile-menu-overlay');

	// Create overlay if it doesn't exist
	if (!overlay && mobileMenuBar) {
		overlay = document.createElement('div');
		overlay.className = 'mobile-menu-overlay';
		overlay.setAttribute('aria-hidden', 'true');
		mobileMenuBar.parentNode.insertBefore(overlay, mobileMenuBar.nextSibling);
	}

	// Initial state
	if (smClose) smClose.style.display = 'none';

	// Exit if no menu exists
	if (!smMenu) {
		// Still allow button to show but do nothing
		smButton.style.display = 'flex';
		return;
	}

	// Close button inside sidebar
	const closeBtn = document.getElementById('mobile-menu-close');
	if (closeBtn) {
		closeBtn.addEventListener('click', function(e) {
			e.preventDefault();
			closeMenu();
		});
	}

	/**
	 * Open mobile menu
	 */
	function openMenu() {
		smMenu.classList.add('menu-active');
		document.body.classList.add('mobile-menu-open');
		smButton.setAttribute('aria-expanded', 'true');
		
		if (smClose) smClose.style.display = 'inline-block';
		if (smOpen) smOpen.style.display = 'none';
		
		// Focus first menu item for accessibility
		const firstLink = smMenu.querySelector('ul li a');
		if (firstLink) {
			setTimeout(() => firstLink.focus(), 300);
		}
	}

	/**
	 * Close mobile menu
	 */
	function closeMenu() {
		smMenu.classList.remove('menu-active');
		document.body.classList.remove('mobile-menu-open');
		smButton.setAttribute('aria-expanded', 'false');
		
		if (smClose) smClose.style.display = 'none';
		if (smOpen) smOpen.style.display = 'inline-block';
		
		// Return focus to menu button
		smButton.focus();
	}

	/**
	 * Toggle menu state
	 */
	function toggleMenu() {
		if (smButton.getAttribute('aria-expanded') === 'true') {
			closeMenu();
		} else {
			openMenu();
		}
	}

	// Menu button click event
	smButton.addEventListener('click', function(e) {
		e.preventDefault();
		e.stopPropagation();
		toggleMenu();
	});

	// Close menu when clicking overlay
	if (overlay) {
		overlay.addEventListener('click', closeMenu);
	}

	// Close menu on outside click
	document.addEventListener('click', function(e) {
		const isInsideMenu = smMenu.contains(e.target);
		const isButton = smButton.contains(e.target);

		if (!isInsideMenu && !isButton && smMenu.classList.contains('menu-active')) {
			closeMenu();
		}
	});

	// Close menu on Escape key
	document.addEventListener('keydown', function(e) {
		if (e.key === 'Escape' && smMenu.classList.contains('menu-active')) {
			closeMenu();
		}
	});

	// Handle window resize - close menu if screen becomes large
	let resizeTimer;
	window.addEventListener('resize', function() {
		clearTimeout(resizeTimer);
		resizeTimer = setTimeout(function() {
			if (window.innerWidth > 991 && smMenu.classList.contains('menu-active')) {
				closeMenu();
			}
		}, 250);
	});

	// ====================================
	// Submenu Toggle Functionality
	// ====================================

	// Add toggle icons to menu items with children
	const subMenus = smMenu.querySelectorAll('.menu-item-has-children > .sub-menu, .page_item_has_children > .children');

	subMenus.forEach(function(subMenu) {
		const icon = document.createElement('i');
		icon.className = 'fas fa-chevron-down';
		icon.setAttribute('tabindex', '0');
		icon.setAttribute('role', 'button');
		icon.setAttribute('aria-label', 'Toggle submenu');
		icon.setAttribute('aria-expanded', 'false');
		subMenu.parentNode.insertBefore(icon, subMenu);
	});

	// Get all submenu toggle icons
	const subMenuIcons = smMenu.querySelectorAll('.menu-item-has-children > i, .page_item_has_children > i');

	subMenuIcons.forEach(function(icon) {
		// Click event
		icon.addEventListener('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			toggleSubmenu(this);
		});

		// Keyboard event
		icon.addEventListener('keydown', function(e) {
			if (e.key === 'Enter' || e.key === ' ') {
				e.preventDefault();
				toggleSubmenu(this);
			}
		});
	});

	/**
	 * Toggle submenu visibility
	 * @param {Element} icon - The toggle icon element
	 */
	function toggleSubmenu(icon) {
		const parent = icon.parentNode;
		const isOpen = parent.classList.contains('clicked');

		// Close other open submenus at the same level
		const siblings = parent.parentNode.querySelectorAll(':scope > .menu-item-has-children.clicked, :scope > .page_item_has_children.clicked');
		siblings.forEach(function(sibling) {
			if (sibling !== parent) {
				sibling.classList.remove('clicked', 'focus');
				const siblingIcon = sibling.querySelector(':scope > i');
				if (siblingIcon) {
					siblingIcon.setAttribute('aria-expanded', 'false');
				}
			}
		});

		// Toggle current submenu
		if (isOpen) {
			parent.classList.remove('clicked', 'focus');
			icon.setAttribute('aria-expanded', 'false');
		} else {
			parent.classList.add('clicked');
			parent.classList.remove('focus');
			icon.setAttribute('aria-expanded', 'true');
		}
	}

	// ====================================
	// Keyboard Navigation (Focus Trap)
	// ====================================

	const focusableElements = smMenu.querySelectorAll(
		'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
	);

	if (focusableElements.length > 0) {
		const firstFocusable = focusableElements[0];
		const lastFocusable = focusableElements[focusableElements.length - 1];

		// Trap focus within menu when open
		smMenu.addEventListener('keydown', function(e) {
			if (e.key !== 'Tab') return;

			if (e.shiftKey) {
				// Shift + Tab
				if (document.activeElement === firstFocusable) {
					e.preventDefault();
					lastFocusable.focus();
				}
			} else {
				// Tab
				if (document.activeElement === lastFocusable) {
					e.preventDefault();
					firstFocusable.focus();
				}
			}
		});
	}

	// ====================================
	// Touch Swipe Support
	// ====================================

	let touchStartX = 0;
	let touchEndX = 0;

	smMenu.addEventListener('touchstart', function(e) {
		touchStartX = e.changedTouches[0].screenX;
	}, { passive: true });

	smMenu.addEventListener('touchend', function(e) {
		touchEndX = e.changedTouches[0].screenX;
		handleSwipe();
	}, { passive: true });

	function handleSwipe() {
		const swipeThreshold = 50;
		const swipeDistance = touchEndX - touchStartX;

		// Swipe left to close menu
		if (swipeDistance < -swipeThreshold && smMenu.classList.contains('menu-active')) {
			closeMenu();
		}
	}

	// Allow swipe from left edge to open menu
	document.addEventListener('touchstart', function(e) {
		if (e.touches[0].clientX < 30) {
			touchStartX = e.touches[0].screenX;
		}
	}, { passive: true });

	document.addEventListener('touchend', function(e) {
		if (touchStartX < 30 && touchStartX > 0) {
			touchEndX = e.changedTouches[0].screenX;
			const swipeDistance = touchEndX - touchStartX;
			
			// Swipe right from edge to open menu
			if (swipeDistance > 50 && !smMenu.classList.contains('menu-active')) {
				openMenu();
			}
		}
		touchStartX = 0;
	}, { passive: true });

})();