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

import { prefersReducedMotion } from './prefers-reduced-motion';

export function scrollToHash( target, { margin = 32, pushState = true } = {} ) {
	const targetId = (
		typeof target === 'string' ?
			target :
			target.getAttribute( 'href' ).substring( 1 )
	);

	const targetElement = document.getElementById( targetId );

	if ( !targetElement ) {
		return;
	}

	const header = document.querySelector( '.js-header' );

	if ( pushState ) {
		history.pushState( true, '', target.getAttribute( 'href' ) );
	}

	window.scrollTo( {
		top: targetElement.getBoundingClientRect().top + window.scrollY - header.clientHeight - margin,
		behavior: prefersReducedMotion() ? 'instant' : 'smooth'
	} );
}
