/**
 * theme-toggle.ts
 * Dark-mode toggle with localStorage persistence + system preference detection.
 */

type Theme = 'light' | 'dark';

const STORAGE_KEY = 'cyywordpress-theme';

function getSystemTheme(): Theme {
	return window.matchMedia( '(prefers-color-scheme: dark)' ).matches ? 'dark' : 'light';
}

function applyTheme( theme: Theme ): void {
	document.documentElement.setAttribute( 'data-theme', theme );
}

function getSavedTheme(): Theme | null {
	const saved = localStorage.getItem( STORAGE_KEY );
	return saved === 'dark' || saved === 'light' ? saved : null;
}

export function initThemeToggle(): void {
	// Apply saved or system theme immediately (before paint).
	const initialTheme = getSavedTheme() ?? getSystemTheme();
	applyTheme( initialTheme );

	const btn = document.getElementById( 'theme-toggle' ) as HTMLButtonElement | null;
	if ( ! btn ) return;

	btn.addEventListener( 'click', () => {
		const current = document.documentElement.getAttribute( 'data-theme' ) as Theme | null;
		const next: Theme = current === 'dark' ? 'light' : 'dark';
		applyTheme( next );
		localStorage.setItem( STORAGE_KEY, next );
		btn.setAttribute( 'aria-label', next === 'dark' ? '切换浅色模式' : '切换深色模式' );
	} );

	// Respond to OS-level change when user hasn't set a preference.
	window.matchMedia( '(prefers-color-scheme: dark)' ).addEventListener( 'change', ( e ) => {
		if ( getSavedTheme() === null ) {
			applyTheme( e.matches ? 'dark' : 'light' );
		}
	} );
}
