/**
 * back-to-top.ts
 * Shows a back-to-top button after scrolling 300 px;
 * scrolls to top using smooth behaviour on click.
 */

const SCROLL_THRESHOLD = 300;

export function initBackToTop(): void {
	const btn = document.getElementById( 'back-to-top' ) as HTMLButtonElement | null;
	if ( ! btn ) return;

	// Remove the `hidden` attribute so CSS can control visibility via `.is-visible`.
	btn.removeAttribute( 'hidden' );

	const onScroll = (): void => {
		btn.classList.toggle( 'is-visible', window.scrollY > SCROLL_THRESHOLD );
	};

	window.addEventListener( 'scroll', onScroll, { passive: true } );
	onScroll();

	btn.addEventListener( 'click', () => {
		window.scrollTo( { top: 0, behavior: 'smooth' } );
		btn.blur();
	} );
}
