import translations from './translations/accessibility-cloud.js-widget/translations';

function findLocaleWithCountry(localeWithoutCountry) {
  const regexp = new RegExp(`^${localeWithoutCountry}_`);
  return Object.keys(translations).find(locale => locale.match(regexp));
}

function translate(string, locale) {
  const localeWithoutCountry = locale.replace(/_[A-Z][A-Z]$/);
  const localeHasCountry = locale !== localeWithoutCountry;
  const localeWithDefaultCountry = localeHasCountry ? locale : findLocaleWithCountry(locale);
  const defaultLocale = 'en_US';

  const translation = translations[locale] || {};
  const translationWithoutCountry = translations[localeWithoutCountry] || {};
  const translationWithDefaultCountry = translations[localeWithDefaultCountry] || {};
  const translationWithDefaultLocale = translations[defaultLocale] || {};

  return translation[string] ||
    translationWithoutCountry[string] ||
    translationWithDefaultCountry[string] ||
    translationWithDefaultLocale ||
    string;
}

// Note that we don't support template strings for now.

// eslint-disable-next-line import/prefer-default-export
export function t(arg) {
  // eslint-disable-next-line no-undef
  return translate(arg, AccessibilityCloud.locale);
}

@@ -848,22 +848,30 @@
  %7B%7D;%0A%0A  
-return
+const result =
  transla
@@ -1004,16 +1004,24 @@
 ltLocale
+%5Bstring%5D
  %7C%7C%0A    
@@ -1027,16 +1027,34 @@
  string;
+%0A%0A  return result;
 %0A%7D%0A%0A// N

Fix a translation bug for en -> en_US fallback