/**
 * Dark mode support store.
 * Task 12: Toggle in settings, respect system preference, persist to localStorage.
 */

import { writable, derived } from 'svelte/store';

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

const THEME_KEY = 'dw_theme';

function getInitialMode(): ThemeMode {
	if (typeof localStorage !== 'undefined') {
		const stored = localStorage.getItem(THEME_KEY);
		if (stored === 'light' || stored === 'dark' || stored === 'system') return stored;
	}
	return 'system';
}

export const themeMode = writable<ThemeMode>(getInitialMode());

// Persist theme preference.
themeMode.subscribe((value) => {
	if (typeof localStorage !== 'undefined') {
		localStorage.setItem(THEME_KEY, value);
	}
});

/**
 * Resolved theme based on mode and system preference.
 * Returns 'light' or 'dark'.
 */
export const resolvedTheme = derived(themeMode, ($mode) => {
	if ($mode === 'system') {
		if (typeof window !== 'undefined') {
			return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
		}
		return 'light';
	}
	return $mode;
});

/**
 * Apply the theme to the document element.
 * Call this in the root layout's $effect.
 */
export function applyTheme(theme: 'light' | 'dark'): void {
	if (typeof document !== 'undefined') {
		document.documentElement.setAttribute('data-theme', theme);
	}
}

export function setThemeMode(mode: ThemeMode): void {
	themeMode.set(mode);
}
