/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

export default function pageNavigation() {
	const CLASS_NAMES = {
		huge: 'api-subheader__navigation-dropdown--huge',
		big: 'api-subheader__navigation-dropdown--big',
		small: 'api-subheader__navigation-dropdown--small',
		empty: 'api-subheader__navigation-dropdown--empty',
		hidden: 'api-subheader__navigation-dropdown--hidden'
	};
	const mainNavigationElements = document.querySelectorAll( '.api-subheader__navigation > ul > li' );
	for ( const element of mainNavigationElements ) {
		const ul = createListFor( element );

		element.appendChild( ul );
	}

	if ( !window.umberto ) {
		window.umberto = {};
	}

	window.umberto.updateDropdowns = function updateDropdowns() {
		for ( const element of mainNavigationElements ) {
			const ul = element.querySelector( 'ul' );
			const visibleItemsLength = ul.querySelectorAll( 'li:not(.api-subheader__navigation-dropdown--hidden)' ).length;
			if ( !visibleItemsLength ) {
				element.classList.add( CLASS_NAMES.hidden );
			} else {
				element.classList.remove( CLASS_NAMES.hidden );
				setClass( ul, dropdownLengthType( visibleItemsLength ) );
			}
		}
	};

	function createListFor( element ) {
		const links = getLinksFor( element );
		const ul = document.createElement( 'ul' );

		ul.classList.add( 'api-subheader__navigation-dropdown' );
		ul.classList.add( dropdownLengthType( links.length ) );

		for ( const link of links ) {
			ul.appendChild( link );
		}

		return ul;
	}

	function getLinksFor( element ) {
		const outputList = [];
		const lists = document.querySelectorAll( 'ul[data-type=' + element.dataset.type + ']' );
		for ( const list of lists ) {
			const links = list.querySelectorAll( 'li.collapsing-list__item' );
			for ( const link of links ) {
				const listItem = document.createElement( 'li' );
				const clonedLink = link.querySelector( 'h3 a.member-name' ).cloneNode( true );
				clonedLink.classList.add( 'api-subheader__navigation-link' );
				listItem.appendChild( clonedLink );
				Object.assign( listItem.dataset, link.dataset );
				outputList.push( listItem );
			}
		}
		return outputList;
	}

	function dropdownLengthType( elements ) {
		if ( elements > 60 ) {
			return CLASS_NAMES.huge;
		} else if ( elements > 20 ) {
			return CLASS_NAMES.big;
		} else if ( elements > 0 ) {
			return CLASS_NAMES.small;
		} else {
			return CLASS_NAMES.empty;
		}
	}

	function setClass( element, className ) {
		if ( !element.classList.contains( className ) ) {
			element.classList.add( className );
		}

		for ( const cls in CLASS_NAMES ) {
			if ( CLASS_NAMES[ cls ] !== className ) {
				element.classList.remove( CLASS_NAMES[ cls ] );
			}
		}
	}
}

