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

export default function sideNavigation() {
	const folderButtons = Array.from( document.querySelectorAll( '.tree:not(.api-tree) .tree__item--folder' ) );
	const guideTreeElement = document.getElementById( 'guidetree' );
	const foldedClassName = 'tree__item-nested-list--hidden';
	const activeClassName = '.tree__item__wrapper--active';
	const localStorageKey = 'foldersState';

	let foldersState = JSON.parse( window.localStorage.getItem( localStorageKey ) );
	if ( foldersState === null ) {
		foldersState = {};
	}

	folderButtons.forEach( btn => {
		const element = btn.parentNode.nextElementSibling; // Get <ul> element
		const id = element.getAttribute( 'data-id' );

		applyFolderState( element, foldersState[ id ] );
		checkForActiveChildren( element, id );

		btn.addEventListener( 'click', function() {
			element.classList.toggle( foldedClassName );
			saveFolderState( id, isFolded( element ) );
		} );
	} );

	if ( guideTreeElement ) {
		guideTreeElement.classList.add( 'state-applied' );
	}

	function applyFolderState( element, folded ) {
		if ( folded === false ) {
			element.classList.remove( foldedClassName );
		}
		if ( folded === true ) {
			element.classList.add( foldedClassName );
		}
	}

	function saveFolderState( id, state ) {
		foldersState[ id ] = state;
		window.localStorage.setItem( localStorageKey, JSON.stringify( foldersState ) );
	}

	function checkForActiveChildren( element, id ) {
		if ( element.querySelectorAll( activeClassName ).length > 0 ) {
			element.classList.remove( foldedClassName );
			saveFolderState( id, isFolded( element ) );
		}
	}

	function isFolded( element ) {
		return element.classList.contains( foldedClassName );
	}
}
