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;
		document.documentElement.classList.remove('light', 'dark');
		document.documentElement.classList.add(theme);
	}

	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)');
		const handleChange = (e: MediaQueryListEvent) => {
			if (preference === 'system') {
				resolved = e.matches ? 'dark' : 'light';
				applyTheme(resolved);
			}
		};

		mediaQuery.addEventListener('change', handleChange);
	}

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

export const theme = createThemeStore();
