import { supportedLanguages } from '~/i18n/translations';

// Define the type for supported languages
type SupportedLanguage = (typeof supportedLanguages)[number];

export function detectPreferredLanguage(request: Request): SupportedLanguage {
  // Check for language preference in cookies (set by client-side JS)
  const cookies = request.headers.get('cookie') || '';
  const cookieMatch = cookies.match(/preferredLanguage=([^;]+)/);
  const cookieLanguage = cookieMatch ? cookieMatch[1] : null;

  // Only use browser language if there's an explicit cookie preference
  if (cookieLanguage && supportedLanguages.some((lang) => lang === cookieLanguage)) {
    return cookieLanguage as SupportedLanguage;
  }

  // Default to English
  return 'en';
}
