/**
 * Keep WordPress's own submenu highlight on the screen actually showing.
 *
 * WordPress decides which submenu item is "current" on the server, from the
 * URL it was asked for — and it never sees the `#/fragment`, because browsers
 * do not send it. So every screen of this app arrived with Home highlighted,
 * and moving between screens changed nothing. This moves the `current` class
 * (and `aria-current`) to the item for the route on every navigation.
 */

import type { RouteId } from './router';

const MENU = '#toplevel_page_razorbooking';

export function syncSubmenu( route: RouteId ): void {
	const links = document.querySelectorAll< HTMLAnchorElement >( `${ MENU } .wp-submenu a` );

	links.forEach( ( link ) => {
		const target = fragmentOf( link.getAttribute( 'href' ) ?? '' );
		const active = target !== null && target === route;
		const item = link.closest( 'li' );

		link.classList.toggle( 'current', active );
		item?.classList.toggle( 'current', active );

		if ( active ) {
			link.setAttribute( 'aria-current', 'page' );
		} else {
			link.removeAttribute( 'aria-current' );
		}
	} );
}

/**
 * Make this plugin's own menu links switch screens inside the app.
 *
 * "RazorBooking" and "Home" point at `admin.php?page=razorbooking` with no
 * `#/fragment`. Clicked from another screen (`…#/team`), that is a different
 * address, so the browser reloaded the whole page and every screen loaded
 * again. A click on any of our links now only changes the fragment. A click
 * that opens a new tab or window (modifier keys, middle button) is left alone.
 */
let kept = false;

export function keepMenuInApp(): void {
	if ( kept ) return;
	kept = true;

	document.querySelector( MENU )?.addEventListener( 'click', ( event ) => {
		const mouse = event as MouseEvent;
		const link = ( event.target as Element | null )?.closest( 'a' );

		if ( ! link || mouse.button !== 0 || mouse.metaKey || mouse.ctrlKey || mouse.shiftKey || mouse.altKey ) {
			return;
		}

		const href = link.getAttribute( 'href' ) ?? '';

		if ( fragmentOf( href ) === null ) {
			return;
		}

		event.preventDefault();
		window.location.hash = href.split( '#' )[ 1 ] || '/';
	} );
}

/** The route a submenu link points at. No fragment is Home. An outbound link is neither. */
function fragmentOf( href: string ): string | null {
	if ( href.indexOf( 'page=razorbooking' ) === -1 ) {
		return null;
	}

	const hash = href.split( '#' )[ 1 ] ?? '';
	const route = hash.replace( /^\/+/, '' ).split( '/' )[ 0 ];

	return route || 'home';
}
