import { browser } from '$app/environment';

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

const STORAGE_KEY = 'theme-preference';

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

function getStoredTheme(): Theme {
	if (!browser) return 'system';
	const stored = localStorage.getItem(STORAGE_KEY);
	if (stored === 'light' || stored === 'dark' || stored === 'system') {
		return stored;
	}
	return 'system';
}

function createThemeStore() {
	let preference = $state<Theme>(getStoredTheme());
	let resolved = $derived<'light' | 'dark'>(
		preference === 'system' ? getSystemTheme() : preference
	);

	function applyTheme(theme: 'light' | 'dark') {
		if (!browser) return;
		const html = document.documentElement;
		// Only modify classes if needed to prevent flash
		if (theme === 'dark') {
			if (!html.classList.contains('dark')) {
				html.classList.remove('light');
				html.classList.add('dark');
			}
		} else {
			if (!html.classList.contains('light')) {
				html.classList.remove('dark');
				html.classList.add('light');
			}
		}
	}

	function setTheme(theme: Theme) {
		preference = theme;

		if (browser) {
			localStorage.setItem(STORAGE_KEY, theme);
			applyTheme(resolved);
		}
	}

	function toggle() {
		const newTheme = resolved === 'light' ? 'dark' : 'light';
		setTheme(newTheme);
	}

	function init() {
		if (!browser) return;

		applyTheme(resolved);

		const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
		mediaQuery.addEventListener('change', (e: MediaQueryListEvent) => {
			if (preference === 'system') {
				applyTheme(e.matches ? 'dark' : 'light');
			}
		});
	}

	return {
		get preference() {
			return preference;
		},
		get resolved() {
			return resolved;
		},
		get isDark() {
			return resolved === 'dark';
		},
		setTheme,
		toggle,
		init
	};
}

export const theme = createThemeStore();
