jQuery(document).ready(function($) {
	function removeClassFromElements(elements, className) {
		elements.forEach(element => element.classList.remove(className));
	}

	/**
	 * Handle disable default behavior from plugin's admin tabs
	 * and navigate React app without reloading the page
	 *
	 */
	function messagingFlowHandleAppRouterLinks() {
		const links = document.querySelectorAll('a[href*="?page=messageflow"]');
		links.forEach((a) => {
			a.addEventListener('click', (event) => {
				event.preventDefault();

				var href = a.getAttribute('href');
				var classList = a.classList;
				var pageParam = new URLSearchParams(href.replace('admin.php', '')).get('page');
				var currentlySelected = Array.from(document.getElementsByClassName('current'));

				removeClassFromElements(currentlySelected, 'current')

				// Check whether user navigate from other admin page
				if (window.reactAppControllers) {
					window.history.pushState(pageParam, null, '/wp-admin/' + href);
					const {_navigate} = window.reactAppControllers;
					_navigate();
				} else {
					window.location.href = href;
				}

				a.parentElement.classList.add('current');
				classList.add('current');
			})
		});
	}

	messagingFlowHandleAppRouterLinks();
})
