/**
 * Script for mobile menu
 *
 * Handles toggling the navigation menu for small screens and enables TAB key
 * navigation support for dropdown menus.
 */


(function(){
	// select all variable
const smButton = document.getElementById('mmenu-btn');
const smMenu = document.getElementById('mobile-navigation');
const menuWrapper = document.getElementById('wsm-menu');
if (!smMenu || !smButton || !menuWrapper) {
	return;
}
// Create overlay dynamically (if not present)
let overlay = document.getElementById('mobile-menu-overlay');
if (!overlay) {
	overlay = document.createElement('div');
	overlay.id = 'mobile-menu-overlay';
	overlay.className = 'mobile-menu-overlay';
	overlay.setAttribute('aria-hidden', 'true');
	menuWrapper.appendChild(overlay);		overlay.addEventListener('click', function () {
			// Close the menu when overlay is clicked
			smMenu.classList.remove('menu-active');
			smButton.setAttribute('aria-expanded', 'false');
			if (smClose) smClose.style.display = 'none';
			if (smOpen) smOpen.style.display = 'block';
			overlay.classList.remove('active');
			overlay.setAttribute('aria-hidden', 'true');
			smButton.focus();
		});}
	const smOpen = smMenu.querySelector('.mopen');
	const smClose = smMenu.querySelector('.mclose');
	smClose.style.display = 'none';

// button click event
  smButton.addEventListener('click', function( ){
	if (smMenu.classList.contains('menu-active')) {
		// closing menu
		smMenu.classList.remove('menu-active');
		smButton.setAttribute('aria-expanded', 'false');
		if (smClose) smClose.style.display = 'none';
		if (smOpen) smOpen.style.display = 'block';
		overlay.classList.remove('active');
		overlay.setAttribute('aria-hidden', 'true');
		smButton.focus();
	} else {
		// opening menu
		smMenu.classList.add('menu-active');
		smButton.setAttribute('aria-expanded', 'true');
		if (smClose) smClose.style.display = 'block';
		if (smOpen) smOpen.style.display = 'none';
		overlay.classList.add('active');
		overlay.setAttribute('aria-hidden', 'false');
		const first = smMenu.querySelector('a, button');
		if (first) first.focus();
	}

  }); // Click event end

  // set outside the menu area 
document.addEventListener('click',function(e){
	const isInsideMenu = smMenu.contains(e.target);

	if( ! isInsideMenu){
		smMenu.classList.remove('menu-active');
		smButton.setAttribute('aria-expanded','false');
		smClose.style.display = 'none';
		smOpen.style.display = 'block';
	}

})

// close on pressing Escape key
document.addEventListener('keydown', function (e) {
	if (e.key === 'Escape' && smMenu.classList.contains('menu-active')) {
		smMenu.classList.remove('menu-active');
		smButton.setAttribute('aria-expanded', 'false');
		if (smClose) smClose.style.display = 'none';
		if (smOpen) smOpen.style.display = 'block';
		overlay.classList.remove('active');
		overlay.setAttribute('aria-hidden', 'true');
		smButton.focus();
	}
});

// add Icon has Children item

//const linkHasSub = smMenu.querySelectorAll('.menu-item-has-children > a, .page_item_has_children > a');
const linkHasSub = smMenu.querySelectorAll('.menu-item-has-children > .sub-menu, .page_item_has_children > .sub-menu');


for (const child of linkHasSub) {
	var icon = document.createElement('i');
    // icon.className = 'fas fa-chevron-down'; // removed; replaced by accessible submenu toggle button
	child.parentNode.insertBefore(icon, child);
	
}

const subMenuIcon = smMenu.querySelectorAll('.menu-item-has-children > i , .page_item_has_children > i');

for (const iconset of subMenuIcon) {
	iconset.setAttribute('tabindex','0');
	
}

	const linksWithChildren = smMenu.querySelectorAll( '.menu-item-has-children > a, .page_item_has_children > a' );

	for ( const link of subMenuIcon ) {
		link.addEventListener( 'click', toggleClick, true );
		link.addEventListener( 'focus', toggleFocus, true );
	//	link.addEventListener( 'blur', toggleblur, true );
	}

	function toggleFocus(e){
		
		if( ! this.parentNode.classList.contains('focus')){
			this.parentNode.classList.add('focus');
			this.parentNode.classList.remove('clicked');
		}

	}
	function toggleblur(e){
		const firstLiA = smMenu.querySelctorAll('#wsm-menu >li a');

		const firstLiaBlur = firstLiA.contains(e.target);
		console.log(firstLiA);
		
		if(firstLiaBlur){

			this.parentNode.classList.remove('focus');
		}else{
			this.parentNode.classList.add('focus');
		}
		

	}
	function toggleClick(e){
		
		if( this.parentNode.classList.contains('clicked')){
			this.parentNode.classList.remove('clicked');
		}else{
			this.parentNode.classList.add('clicked');
			this.parentNode.classList.remove('focus');
		}

	}

focusableInNav = smMenu.querySelectorAll('button, [href], [tabindex]:not([tabindex="-1"])');


	let firstFocusElement = focusableInNav[0];
	let lestFocusElement = focusableInNav[focusableInNav.length - 1];
	
	firstFocusElement.addEventListener( 'keydown', moveFocusToBottom, true );
	lestFocusElement.addEventListener( 'keydown', moveFocusToTop, true );

	function moveFocusToBottom(e) {
		if (e.key === "Tab" && e.shiftKey) {
			e.preventDefault();
			lestFocusElement.focus()
		}
	}
	function moveFocusToTop(e) {
		if (e.key === "Tab" && !e.shiftKey) {
			e.preventDefault();
			firstFocusElement.focus();
		}
	}




// Improved focus trapping and submenu/button behavior
let focusableInNav = function () {
	return smMenu.querySelectorAll('a, button, [tabindex]:not([tabindex="-1"])');
};

function handleTabKey(e) {
	if (e.key !== 'Tab' || !smMenu.classList.contains('menu-active')) return;
	const nodes = Array.prototype.slice.call(focusableInNav());
	if (!nodes.length) return;
	const first = nodes[0];
	const last = nodes[nodes.length - 1];
	if (e.shiftKey && document.activeElement === first) {
		e.preventDefault();
		last.focus();
	} else if (!e.shiftKey && document.activeElement === last) {
		e.preventDefault();
		first.focus();
	}
}

document.addEventListener('keydown', handleTabKey, true);

// Add accessible submenu toggles (if not already added)
const existingToggles = smMenu.querySelectorAll('.submenu-toggle');
if (!existingToggles.length) {
	const itemsWithChildren = smMenu.querySelectorAll('.menu-item-has-children');
	itemsWithChildren.forEach(function (li, idx) {
		const submenu = li.querySelector('.sub-menu');
		if (!submenu) return;
		if (!submenu.id) submenu.id = 'submenu-' + idx;
		const toggle = document.createElement('button');
		toggle.className = 'submenu-toggle';
		toggle.type = 'button';
		toggle.setAttribute('aria-expanded', 'false');
		toggle.setAttribute('aria-controls', submenu.id);
		toggle.setAttribute('aria-label', 'Toggle submenu');
		const link = li.querySelector('a');
		if (link && link.nextSibling) {
			link.parentNode.insertBefore(toggle, link.nextSibling);
		} else if (link) {
			link.parentNode.appendChild(toggle);
		} else {
			li.insertBefore(toggle, submenu);
		}
		// Toggle submenu open/close
		toggle.addEventListener('click', function (e) {
			e.preventDefault();
			const expanded = this.getAttribute('aria-expanded') === 'true';
			this.setAttribute('aria-expanded', String(!expanded));
			li.classList.toggle('submenu-open');
		});
	});
}

// close menu when a non-parent link is clicked
const menuLinks = smMenu.querySelectorAll('a');
menuLinks.forEach(function(link){
	link.addEventListener('click', function(e){
		const parentLi = this.closest('.menu-item-has-children');
		if (parentLi && parentLi.querySelector('.sub-menu') && !parentLi.classList.contains('submenu-open')) {
			// user likely opening submenu; don't close
			return;
		}
		// otherwise close the menu on mobile link click
		smMenu.classList.remove('menu-active');
		smButton.setAttribute('aria-expanded','false');
		if (overlay) { overlay.classList.remove('active'); overlay.setAttribute('aria-hidden','true'); }
		smButton.focus();
	});
});

}())