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

import $ from 'jquery';
import throttle from 'lodash/throttle';

/**
 * Expands corresponding API tree item on navigation tree when viewing a page.
 */
export function expandApiTree() {
	const activeTreeItemClass = 'tree__item__wrapper--active';
	const togglerExpandedClass = 'toggler--expanded';
	const togglerCollapsedClass = 'toggler--collapsed';
	const pageIdentifier = $( 'h1' ).data( 'ln' );

	if ( !pageIdentifier ) {
		return;
	}

	const apiTree = $( 'ul.api-tree' );

	if ( apiTree.length === 0 ) {
		return;
	}

	const currentTreeItem = apiTree.find( `div[data-ln="${ pageIdentifier }"]` );
	currentTreeItem.addClass( activeTreeItemClass );
	currentTreeItem.parents( '.api-tree li[class*="toggler--"]' ).removeClass( togglerCollapsedClass ).addClass( togglerExpandedClass );
}

/**
 * Scrolls API navigation tree to currently viewed page.
 */
export function scrollApiTree() {
	if ( $( '.side-navigation' ).length === 0 ) {
		return;
	}

	const tree = $( '.side-navigation__inner' );
	const treeHeight = tree.height();
	const storageKey = 'side-nav-scroll-top';
	const sideNavScrollTop = Number( window.localStorage.getItem( storageKey ) );
	const activeTreeItemClass = 'tree__item__wrapper--active';
	const activeTreeItem = $( `div.side-navigation .${ activeTreeItemClass }` );
	let activeTreeItemTop = 0;
	const bound = 50; // Offset from top and bottom of side nav.

	if ( activeTreeItem.length ) {
		activeTreeItemTop = activeTreeItem[ 0 ].offsetParent ? activeTreeItem[ 0 ].offsetParent.offsetTop : 0;

		if (
			sideNavScrollTop !== null &&
			activeTreeItemTop > sideNavScrollTop + bound &&
			activeTreeItemTop < sideNavScrollTop + treeHeight - bound
		) {
			tree.scrollTop( sideNavScrollTop );
		} else {
			activeTreeItem[ 0 ].scrollIntoView( { block: 'center' } );
		}
	}

	tree.scroll( throttle( () => {
		window.localStorage.setItem( storageKey, tree.scrollTop() );
	}, 200 ) );
}
