/**
 * RSM suite admin menu — see rsm-spark/assets/js/admin-menu.js (canonical copy).
 *
 * Spark enqueues the live script on all wp-admin screens. This file remains for
 * bundled rsm-shared parity when Spark is not active.
 */
( function ( $ ) {
	'use strict';

	if ( window.rsmSparkAdminMenuLoaded ) {
		return;
	}

	window.rsmSparkAdminMenuLoaded = true;

	var MENU_ID = 'toplevel_page_rsmspark-suite';
	var COLLAPSED = 'rsmspark-suite-submenu-collapsed';
	var ACCORDION = 'rsmspark-suite-menu-accordion';
	var STORAGE_KEY = 'rsmSuiteMenuOpenSection';
	var COLLAPSED_KEY = 'rsmSuiteMenuSubmenuCollapsed';
	var HEADING_HREF = 'page=rsmspark-suite-';

	function getItem() {
		return $( '#' + MENU_ID );
	}

	function isResponsiveMenu() {
		return !! $( '#adminmenu' ).data( 'wp-responsive' );
	}

	function getSubmenu( $item ) {
		return $item.children( '.wp-submenu' );
	}

	function isSectionHeadingHref( href ) {
		return !! href && href.indexOf( HEADING_HREF ) !== -1;
	}

	function sectionIdFromHref( href ) {
		var match = String( href ).match( /page=rsmspark-suite-([^&]+)/ );
		return match && match[1] ? match[1] : '';
	}

	function isHoverFlyout( $item, $sub ) {
		return $item.hasClass( 'opensub' ) && 'absolute' === $sub.css( 'position' );
	}

	function isPinnedInlineSubmenu( $item, $sub ) {
		if ( ! $item.hasClass( 'wp-has-current-submenu' ) || $item.hasClass( COLLAPSED ) ) {
			return false;
		}
		if ( ! $sub.length || 'none' === $sub.css( 'display' ) ) {
			return false;
		}
		if ( isHoverFlyout( $item, $sub ) ) {
			return false;
		}
		if ( 'relative' === $sub.css( 'position' ) ) {
			return true;
		}
		var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
		var body = document.body;
		var narrowMenu =
			body.classList.contains( 'folded' ) ||
			( body.classList.contains( 'auto-fold' ) && viewportWidth <= 960 );
		return ! narrowMenu;
	}

	function collapseSubmenu( $item ) {
		$item.addClass( COLLAPSED ).removeClass( 'opensub selected' );
		getSubmenu( $item ).css( 'margin-top', '' );
		try {
			window.sessionStorage.setItem( COLLAPSED_KEY, '1' );
		} catch ( err ) {
			// sessionStorage unavailable.
		}
	}

	function expandSubmenu( $item ) {
		$item.removeClass( COLLAPSED );
		try {
			window.sessionStorage.removeItem( COLLAPSED_KEY );
		} catch ( err ) {
			// sessionStorage unavailable.
		}
	}

	function buildGroups( $sub ) {
		var groups = [];
		var current = null;

		$sub.children( 'li' ).each( function () {
			var $li = $( this );
			var $a = $li.children( 'a' ).first();
			var href = $a.attr( 'href' ) || '';

			if ( isSectionHeadingHref( href ) ) {
				var id = sectionIdFromHref( href );
				if ( ! id ) {
					return;
				}
				current = { id: id, $heading: $li, $items: $( [] ) };
				groups.push( current );
				$li.addClass( 'rsmspark-suite-menu-heading' );
				$a.addClass( 'rsmspark-suite-menu-heading__link' )
					.attr( 'role', 'button' )
					.attr( 'tabindex', '0' )
					.attr( 'aria-expanded', 'false' );
				return;
			}

			if ( ! current ) {
				if ( ! groups.length || groups[0].id !== '_top' ) {
					groups.unshift( { id: '_top', $heading: null, $items: $( [] ) } );
				}
				groups[0].$items = groups[0].$items.add( $li );
				return;
			}

			$li.addClass( 'rsmspark-suite-menu-group-item' ).attr( 'data-rsm-menu-group', current.id );
			current.$items = current.$items.add( $li );
		} );

		return groups;
	}

	function findActiveGroupId( groups ) {
		var i;
		for ( i = 0; i < groups.length; i += 1 ) {
			if ( groups[i].$items.filter( '.current' ).length ) {
				return groups[i].id;
			}
		}
		return '';
	}

	function readStoredSection() {
		try {
			return window.localStorage.getItem( STORAGE_KEY ) || '';
		} catch ( err ) {
			return '';
		}
	}

	function writeStoredSection( id ) {
		try {
			if ( id ) {
				window.localStorage.setItem( STORAGE_KEY, id );
			} else {
				window.localStorage.removeItem( STORAGE_KEY );
			}
		} catch ( err ) {
			// localStorage unavailable.
		}
	}

	function setOpenGroup( groups, openId ) {
		groups.forEach( function ( group ) {
			if ( group.id === '_top' ) {
				return;
			}
			var open = group.id === openId;
			if ( group.$heading ) {
				group.$heading.toggleClass( 'rsmspark-suite-menu-heading--open', open );
				group.$heading.find( '.rsmspark-suite-menu-heading__link' ).attr( 'aria-expanded', open ? 'true' : 'false' );
			}
			group.$items.toggleClass( 'rsmspark-suite-menu-group-item--hidden', ! open );
		} );
	}

	function initialOpenGroupId( groups ) {
		var active = findActiveGroupId( groups );
		if ( active && active !== '_top' ) {
			return active;
		}

		var stored = readStoredSection();
		if ( stored ) {
			var i;
			for ( i = 0; i < groups.length; i += 1 ) {
				if ( groups[i].id === stored ) {
					return stored;
				}
			}
		}

		return '';
	}

	function initAccordion( $item ) {
		if ( isResponsiveMenu() ) {
			return;
		}

		var $sub = getSubmenu( $item );
		if ( ! $sub.length ) {
			return;
		}

		var groups = buildGroups( $sub );
		if ( groups.length < 2 ) {
			return;
		}

		$item.addClass( ACCORDION );
		var openId = initialOpenGroupId( groups );
		setOpenGroup( groups, openId );
		if ( openId ) {
			writeStoredSection( openId );
		}

		$sub.on( 'click.rsmSuiteAccordion', '.rsmspark-suite-menu-heading__link', function ( event ) {
			event.preventDefault();
			event.stopPropagation();

			var $heading = $( this ).closest( '.rsmspark-suite-menu-heading' );
			var href = $( this ).attr( 'href' ) || '';
			var id = sectionIdFromHref( href );
			if ( ! id ) {
				return;
			}

			var nextOpen = $heading.hasClass( 'rsmspark-suite-menu-heading--open' ) ? '' : id;
			setOpenGroup( groups, nextOpen );
			writeStoredSection( nextOpen );
		} );

		$sub.on( 'keydown.rsmSuiteAccordion', '.rsmspark-suite-menu-heading__link', function ( event ) {
			if ( event.key !== 'Enter' && event.key !== ' ' ) {
				return;
			}
			event.preventDefault();
			$( this ).trigger( 'click' );
		} );
	}

	function init() {
		var adminmenu = document.getElementById( 'adminmenu' );
		if ( ! adminmenu ) {
			return;
		}

		var $item = getItem();
		if ( $item.length ) {
			try {
				if (
					'1' === window.sessionStorage.getItem( COLLAPSED_KEY ) &&
					$item.hasClass( 'wp-has-current-submenu' )
				) {
					collapseSubmenu( $item );
				}
			} catch ( err ) {
				// sessionStorage unavailable.
			}
			initAccordion( $item );
		}

		adminmenu.addEventListener(
			'click',
			function ( event ) {
				var link = event.target.closest( '#' + MENU_ID + ' > a' );
				if ( ! link || isResponsiveMenu() ) {
					return;
				}

				var $menuItem = $( link ).parent( 'li' );
				if ( ! $menuItem.length || ! $menuItem.hasClass( 'wp-has-current-submenu' ) ) {
					return;
				}

				var $sub = getSubmenu( $menuItem );

				if ( isPinnedInlineSubmenu( $menuItem, $sub ) ) {
					collapseSubmenu( $menuItem );
					event.preventDefault();
					event.stopImmediatePropagation();
					return;
				}

				if ( $menuItem.hasClass( COLLAPSED ) ) {
					expandSubmenu( $menuItem );
					event.preventDefault();
					event.stopImmediatePropagation();
				}
			},
			true
		);

		$( document ).on( 'wp-collapse-menu', function () {
			getItem().removeClass( COLLAPSED );
		} );
	}

	$( init );
}( jQuery ) );
