import { resolvedTheme } from '$lib/stores/theme.svelte';

// TODO(#375): keep these hex values in sync with tokens.json
// colors.dark.obsidian / colors.light.obsidian. The duplication is a known
// drift hazard from #363; consume from the generated CSS layer instead.
const DARK = '#14171A';
const LIGHT = '#F8F5EE';

// applyMetaThemeColor wires a Svelte 5 $effect that keeps a single
// <meta name="theme-color"> (without a media query) in sync with the
// resolved theme. The Vite build plugin injects two media-query
// variants for first paint / pre-hydration; the meta tag this helper
// manages is added on hydration and tracks the user's explicit
// Dark / Light / System choice. On a phone, the mobile address bar
// retints the moment the user changes the theme in Settings.
//
// Must be called from a component setup (uses $effect).
export function applyMetaThemeColor(): void {
	$effect(() => {
		const target = resolvedTheme.value === 'light' ? LIGHT : DARK;
		let meta = document.querySelector<HTMLMetaElement>(
			'meta[name="theme-color"]:not([media])'
		);
		if (!meta) {
			meta = document.createElement('meta');
			meta.name = 'theme-color';
			document.head.appendChild(meta);
		}
		meta.content = target;
	});
}
