/**
 * main.ts
 * Entry point – conditionally imports each module based on the page context.
 *
 * Import the SCSS entry point here so Vite bundles both together.
 */
import '@scss/main.scss';

import { initNavigation }      from './navigation';
import { initThemeToggle }     from './theme-toggle';
import { initBackToTop }       from './back-to-top';
import { initLazyImages }      from './lazy-images';

// Single-post-only modules (guard by DOM presence to keep bundles lean).
async function loadSingleModules(): Promise<void> {
	if ( ! document.querySelector( '.single-article' ) ) return;

	const [ { initReadingProgress }, { initToc }, { initCopyCode } ] = await Promise.all( [
		import( './reading-progress' ),
		import( './toc' ),
		import( './copy-code' ),
	] );

	initReadingProgress();
	initToc();
	initCopyCode();

	// Social share – copy link button.
	const copyLinkBtns = document.querySelectorAll<HTMLButtonElement>( '.social-share__btn--copy' );
	copyLinkBtns.forEach( ( btn ) => {
		btn.addEventListener( 'click', async () => {
			const url = btn.dataset.url ?? window.location.href;
			try {
				await navigator.clipboard.writeText( url );
				btn.setAttribute( 'aria-label', '链接已复制!' );
				setTimeout( () => btn.setAttribute( 'aria-label', '复制链接' ), 2000 );
			} catch {
				// Clipboard API unavailable – silent fail.
			}
		} );
	} );
}

document.addEventListener( 'DOMContentLoaded', () => {
	// Apply saved theme before paint to avoid FOUC (also done inline in theme-toggle).
	initThemeToggle();
	initNavigation();
	initBackToTop();
	initLazyImages();
	void loadSingleModules();
} );
