let theme = $state<'light' | 'dark'>('light');

export function initTheme() {
	if (typeof window === 'undefined') return;
	const stored = localStorage.getItem('theme') as 'light' | 'dark' | null;
	const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
	theme = stored ?? (prefersDark ? 'dark' : 'light');
	applyTheme();
}

function applyTheme() {
	if (typeof document === 'undefined') return;
	const root = document.documentElement;
	root.classList.remove('light', 'dark');
	root.classList.add(theme);
}

export function toggleTheme() {
	theme = theme === 'light' ? 'dark' : 'light';
	localStorage.setItem('theme', theme);
	applyTheme();
}

export function isDark(): boolean {
	return theme === 'dark';
}
