import { locales } from '$lib/paraglide/runtime';

/**
 * Picks the best supported locale from an Accept-Language header value.
 * Returns null when no supported locale is found.
 */
export function detectLocale(acceptLanguage: string): string | null {
	const preferred = acceptLanguage
		.split(',')
		.map((part) => {
			const [lang, q] = part.trim().split(';q=');
			return { lang: lang.trim().split('-')[0].toLowerCase(), q: q ? parseFloat(q) : 1 };
		})
		.sort((a, b) => b.q - a.q);

	for (const { lang } of preferred) {
		if ((locales as readonly string[]).includes(lang)) return lang;
	}
	return null;
}
