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

import $ from 'jquery';

/**
 * Scrolls page to an anchor when clicking a link to an anchor.
 */
export function enableAnchors() {
	setTimeout( scrollToHashTarget, 100 );

	$( window ).on( 'hashchange', () => {
		setTimeout( scrollToHashTarget, 0 );
	} );

	$( 'a[href^="#"]' ).on( 'click', function( evt ) {
		const el = $( this );
		const href = el.attr( 'href' );
		const hash = location.hash;

		if ( el.hasClass( 'member-name' ) ) {
			locationHashUpdate( href );
			if ( el.hasClass( 'api-subheader__navigation-link' ) ) {
				scrollToHashTarget();
			}
			evt.preventDefault();
		}
		else if ( href == hash ) {
			scrollToHashTarget();
			evt.preventDefault();
		}
	} );

	function scrollToHashTarget() {
		const target = $( ':target' );
		const offset = target.offset();

		if ( offset ) {
			const scrollTop = offset.top - $( '.top' ).height();

			if ( target && target.is( '[class*="toggler"]' ) ) {
				target.removeClass( 'toggler--collapsed' );
				target.addClass( 'toggler--expanded' );
			}

			$( 'html, body' ).scrollTop( scrollTop );
		}
	}

	function locationHashUpdate( newHash ) {
		if ( newHash && newHash !== location.hash ) {
			location.hash = newHash;
		}
	}
}
