/**
 * reading-progress.ts
 * Fills a thin progress bar at the top of single-post pages
 * based on how far down the user has scrolled.
 */

export function initReadingProgress(): void {
	const progressEl = document.querySelector<HTMLElement>( '.reading-progress' );
	const barEl      = document.querySelector<HTMLElement>( '.reading-progress__bar' );
	if ( ! progressEl || ! barEl ) return;

	const article = document.querySelector<HTMLElement>( '.single-article' ) ?? document.body;

	const update = (): void => {
		const articleTop    = article.getBoundingClientRect().top + window.scrollY;
		const articleHeight = article.offsetHeight;
		const scrolled      = window.scrollY - articleTop;
		const progress      = Math.min( 100, Math.max( 0, ( scrolled / articleHeight ) * 100 ) );

		barEl.style.width = `${ progress }%`;
		progressEl.setAttribute( 'aria-valuenow', String( Math.round( progress ) ) );
	};

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