diff --git a/frontend/src/lib/i18n/index.ts b/frontend/src/lib/i18n/index.ts index aa192d1..a3f27ae 100644 --- a/frontend/src/lib/i18n/index.ts +++ b/frontend/src/lib/i18n/index.ts @@ -8,11 +8,39 @@ export type Translations = typeof en; const translations: Record = { en, es }; +const SUPPORTED_LOCALES: Locale[] = ['en', 'es']; + +function matchLocale(lang: string): Locale | null { + const lower = lang.toLowerCase(); + // Exact match + if (SUPPORTED_LOCALES.includes(lower as Locale)) return lower as Locale; + // Match language prefix (e.g. es-MX, es-AR, es-ES -> es) + const prefix = lower.split('-')[0]; + if (SUPPORTED_LOCALES.includes(prefix as Locale)) return prefix as Locale; + return null; +} + +function getBrowserLocale(): Locale | null { + if (typeof window === 'undefined') return null; + // Check navigator.languages first (ordered by preference) + if (navigator.languages?.length) { + for (const lang of navigator.languages) { + const matched = matchLocale(lang); + if (matched) return matched; + } + } + // Fallback to navigator.language + if (navigator.language) { + return matchLocale(navigator.language); + } + return null; +} + function getInitialLocale(): Locale { if (typeof window === 'undefined') return 'en'; const stored = localStorage.getItem('locale'); if (stored === 'en' || stored === 'es') return stored; - return 'en'; + return getBrowserLocale() || 'en'; } function createLocaleStore() {