<script lang="ts">
	/**
	 * Fase 9.1 — three-way segmented control: Light / Dark / System.
	 *
	 * The component is purely presentational state-wise: it reads the
	 * authoritative `themePreference` store from `$lib/theme` and writes
	 * back via `setThemePreference`. That single function takes care of
	 * persisting to localStorage and flipping <html data-theme>.
	 *
	 * The optional `onChange` prop lets the parent persist the choice to
	 * the user's row in `public.users.theme`. We keep the DB write outside
	 * the toggle so the component stays storage-agnostic (and easy to test).
	 */
	import { themePreference, setThemePreference, type ThemePreference } from '$lib/theme';
	import * as m from '$lib/paraglide/messages';

	let { onChange }: { onChange?: (next: ThemePreference) => void } = $props();

	const options: Array<{ value: ThemePreference; label: () => string }> = [
		{ value: 'light', label: () => m.settings_theme_light() },
		{ value: 'dark', label: () => m.settings_theme_dark() },
		{ value: 'system', label: () => m.settings_theme_system() }
	];

	function select(value: ThemePreference) {
		if ($themePreference === value) return;
		setThemePreference(value);
		onChange?.(value);
	}
</script>

<div
	role="radiogroup"
	aria-label={m.settings_appearance()}
	class="inline-flex items-center gap-1 rounded-md border border-slate-300 bg-surface p-1 dark:border-slate-600 dark:bg-slate-800"
	data-testid="theme-toggle"
>
	{#each options as opt (opt.value)}
		<button
			type="button"
			role="radio"
			aria-checked={$themePreference === opt.value}
			data-theme-option={opt.value}
			onclick={() => select(opt.value)}
			class="rounded px-3 py-1.5 text-xs font-medium transition-colors
				{$themePreference === opt.value
					? 'bg-slate-900 text-white dark:bg-slate-50 dark:text-slate-900'
					: 'text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-700'}"
		>
			{opt.label()}
		</button>
	{/each}
</div>
