import { Direction } from '../direction.mjs';

const DEFAULT_LANG = 'en';
const DEFAULT_LOCALE = 'en-GB';
/**
 * Languages written right-to-left.
 */
const RTL_LANGUAGES = ['ar', 'he'];
/**
 * @deprecated The source of truth for supported languages lives in Crab.
 */
const SUPPORTED_LANGUAGES = [DEFAULT_LANG, 'de', 'es', 'fr', 'hu', 'id', 'it', 'ja', 'pl', 'pt', 'ro', 'ru', 'th', 'tr', 'uk', 'zh'];
/**
 * Verifies and adjusts locale, replacing `_` with `-`.
 *
 * @param locale `es`, `es_ES`, `en-GB`, `en`, `ja`, `ja-JP`, etc.
 * @returns `null` if locale is unrecognized by `Intl.Locale`.
 */
function adjustLocale(locale) {
  const localeTrimmed = locale?.trim();
  if (localeTrimmed) {
    try {
      return new Intl.Locale(localeTrimmed.replace('_', '-')).baseName;
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error(error);
    }
  }
  return null;
}
/**
 * Provides corresponding lang (iso2) for provided locale.
 *
 * @deprecated The use of this function almost always breaks language variants
 * e.g. Simplified and Traditional Chinese.
 * There should be no use case for this function.
 * To select the correct translations from a translations object, pass the
 * locale directly into Crab's getLocalisedMessages.
 * @param locale `es`, `es-ES`, `en-GB`, `en`, `ja`, `ja-JP`, etc.
 * @returns Two-letter ISO 639-1 language code, falling back to `null` if locale is invalid or language is unsupported.
 */
function getLangFromLocale(locale) {
  const adjustedLocale = adjustLocale(locale);
  if (adjustedLocale != null) {
    const {
      language
    } = new Intl.Locale(adjustedLocale);
    if (SUPPORTED_LANGUAGES.includes(language)) {
      return language;
    }
  }
  return null;
}
/**
 * Provides corresponding country code (iso2) for locales code with explicit region value.
 *
 * @param locale `es-ES`, `en-GB`, `ja-JP`, etc.
 * @returns `null` if the locale is invalid or the region can‘t be identified.
 */
function getCountryFromLocale(locale) {
  const adjustedLocale = adjustLocale(locale);
  return adjustedLocale != null ? new Intl.Locale(adjustedLocale).region ?? null : null;
}
/**
 * Provides the layout direction for a given locale.
 *
 * @param locale `es`, `es-ES`, `en-GB`, `en`, `ja`, `ja-JP`, etc.
 * @returns The layout direction based on the locale, falling back to `Direction.LTR` if the locale is invalid or unsupported.
 */
function getDirectionFromLocale(locale) {
  const adjustedLocale = adjustLocale(locale);
  return adjustedLocale != null && RTL_LANGUAGES.includes(new Intl.Locale(adjustedLocale).language) ? Direction.RTL : Direction.LTR;
}

export { DEFAULT_LANG, DEFAULT_LOCALE, RTL_LANGUAGES, SUPPORTED_LANGUAGES, adjustLocale, getCountryFromLocale, getDirectionFromLocale, getLangFromLocale };
//# sourceMappingURL=index.mjs.map
