import {
	type NavigationItem,
	navigationForScreen,
	screenFromNavigationHref,
} from './admin-data';

export interface AppNavigationTarget {
	item: NavigationItem;
	href: string;
}

export const appNavigationTarget = (
	event: MouseEvent,
	app: HTMLElement | null,
	navigation: NavigationItem[]
): AppNavigationTarget | null => {
	const target =
		event.target instanceof HTMLElement
			? event.target.closest( 'a' )
			: null;

	if (
		event.defaultPrevented ||
		! ( target instanceof HTMLAnchorElement ) ||
		! app?.contains( target ) ||
		0 !== event.button ||
		event.metaKey ||
		event.ctrlKey ||
		event.shiftKey ||
		event.altKey ||
		target.target
	) {
		return null;
	}

	const rawHref = target.getAttribute( 'href' ) || '';
	const changeHashHref = /^#change-[a-zA-Z0-9_-]+$/.test( rawHref );

	if ( ! rawHref || ( rawHref.startsWith( '#' ) && ! changeHashHref ) ) {
		return null;
	}

	const screen = screenFromNavigationHref(
		navigation,
		target.href,
		window.location.href
	);
	const item = navigationForScreen( navigation, screen );

	if ( ! item ) {
		return null;
	}

	return {
		item,
		href: target.href,
	};
};
