import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './types.js';

export function isSupportedLocale(value: string | null | undefined): value is SupportedLocale {
  return (
    typeof value === 'string' &&
    (SUPPORTED_LOCALES as readonly string[]).includes(value)
  );
}

// Strip region tag ("de-DE" -> "de"), lowercase, validate.
export function normaliseLocale(input: string | null | undefined): SupportedLocale | null {
  if (!input) return null;
  const short = input.toLowerCase().split('-')[0];
  return isSupportedLocale(short) ? short : null;
}

// Detect the best-guess initial locale using only platform-agnostic inputs.
// Host apps layer their own precedence on top (cached pref -> user profile).
export function detectBrowserLocale(
  navigatorLanguages: readonly string[] | undefined,
): SupportedLocale {
  if (!navigatorLanguages) return DEFAULT_LOCALE;
  for (const lang of navigatorLanguages) {
    const match = normaliseLocale(lang);
    if (match) return match;
  }
  return DEFAULT_LOCALE;
}
