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

// Browser address-bar tint matches the page background — colors.<mode>.obsidian
// is the canonical background token, the same value the runtime CSS variables
// resolve to for each mode. Reading from tokens.json (not the generated CSS)
// avoids a getComputedStyle round-trip and keeps the source of truth in one
// place; if a designer rotates the palette, both surfaces move together.
const DARK = tokens.colors.dark.obsidian;
const LIGHT = tokens.colors.light.obsidian;

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