/**
 * Theme management with Svelte 5 runes.
 * Supports light, dark, and system preference.
 */

export type Theme = 'light' | 'dark' | 'system';

let theme = $state<Theme>('system');
let resolved = $state<'light' | 'dark'>('light');
let listenerRegistered = false;

export function getTheme() {
	return {
		get current() { return theme; },
		get resolved() { return resolved; },
		get isDark() { return resolved === 'dark'; },
	};
}

export function setTheme(newTheme: Theme) {
	theme = newTheme;
	if (typeof localStorage !== 'undefined') {
		localStorage.setItem('theme', newTheme);
	}
	applyTheme();
}

export function initTheme() {
	if (typeof localStorage !== 'undefined') {
		const saved = localStorage.getItem('theme') as Theme | null;
		if (saved && ['light', 'dark', 'system'].includes(saved)) {
			theme = saved;
		}
	}
	applyTheme();

	// Listen for system preference changes (register only once)
	if (typeof window !== 'undefined' && !listenerRegistered) {
		listenerRegistered = true;
		window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
			if (theme === 'system') applyTheme();
		});
	}
}

function applyTheme() {
	if (typeof document === 'undefined') return;

	if (theme === 'system') {
		resolved = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
	} else {
		resolved = theme;
	}

	document.documentElement.setAttribute('data-theme', resolved);
}
