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

import { BaseComponent } from './base-component';
import { scrollToHash } from '../helpers/scroll-to-hash';

/**
 * HashLink component.
 * Handles navigation to hash links within the page with scrolling.
 */
export class HashLink extends BaseComponent {
	/**
	 * Attaches event listeners to handle hash link navigation.
	 */
	static attach() {
		// Handle initial hash link navigation if present in the URL
		this._handleInitialHash();

		// Add click event listener to handle hash link clicks
		document.addEventListener( 'click', event => {
			const target = event.target.closest( 'a[href^="#"]' );

			if ( !target ) {
				return;
			}

			event.preventDefault();
			scrollToHash( target );
		} );
	}

	/**
	 * Handles initial hash link navigation if present in the URL on page load.
	 *
	 * @private
	 */
	static _handleInitialHash() {
		if ( !window.location.hash ) {
			return;
		}

		let abortScroll = false;

		window.addEventListener( 'mousewheel', () => {
			abortScroll = true;
		}, { once: true } );

		window.addEventListener( 'load', () => {
			if ( abortScroll ) {
				return;
			}

			scrollToHash( window.location.hash.substring( 1 ), {
				pushState: false
			} );
		}, { once: true } );
	}
}
