/**
 * 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);
	}
});

/**
 * Tracks system color-scheme preference changes so that the derived store
 * re-evaluates when the OS theme changes while mode is 'system'.
 */
const systemDark = writable(
	typeof window !== 'undefined'
		? window.matchMedia('(prefers-color-scheme: dark)').matches
		: false
);

if (typeof window !== 'undefined') {
	const mq = window.matchMedia('(prefers-color-scheme: dark)');
	mq.addEventListener('change', (e) => {
		systemDark.set(e.matches);
	});
}

/**
 * Resolved theme based on mode and system preference.
 * Returns 'light' or 'dark'.
 */
export const resolvedTheme = derived([themeMode, systemDark], ([$mode, $dark]) => {
	if ($mode === 'system') {
		return $dark ? 'dark' : '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);
}
