'use client';

import { useLocaleOptional } from '@djangocfg/i18n';

import { resolveSpeechLanguage } from '../core/language';
import { useSpeechPrefs } from '../store/prefsStore';

/**
 * Resolves the BCP-47 language tag a speech session should use.
 *
 * Priority: explicit prop → user-picked `useSpeechPrefs.language` →
 * app i18n locale (when an `<I18nProvider>` is mounted) →
 * `navigator.language` → `en-US`.
 *
 * Uses `useLocaleOptional` (not `useLocale`) so that an unmounted
 * provider doesn't silently inject `'en'`. Without that, the i18n
 * default would shadow the user's real browser language — a Russian
 * speaker would always get `en-US` recognition.
 */
export function useResolvedLanguage(explicit?: string): string {
  const prefs = useSpeechPrefs();
  const locale = useLocaleOptional();
  return resolveSpeechLanguage({
    explicit,
    prefs: prefs.language,
    i18n: locale,
  });
}
