(function (global) {
  'use strict';
  var STORAGE_KEY = 'crash_console_lang';
  var SUPPORTED = ['en', 'ru'];
  var DEFAULT_LANG = 'en';
  var LANG_DISPLAY = { en: { flag: '\uD83C\uDDEC\uD83C\uDDE7', code: 'EN' }, ru: { flag: '\uD83C\uDDF7\uD83C\uDDFA', code: 'RU' } };
  var lang = DEFAULT_LANG;
  var catalog = {};
  var fallback = {};

  function hubAsset(rel) {
    var link = document.querySelector('link[href*="hub.css"]');
    var base = link ? (link.getAttribute('href') || '').replace(/[^/]*$/, '') : '';
    return base + rel;
  }

  function storedLang() {
    try {
      var v = localStorage.getItem(STORAGE_KEY);
      return SUPPORTED.indexOf(v) >= 0 ? v : DEFAULT_LANG;
    } catch (e) {
      return DEFAULT_LANG;
    }
  }

  function t(key, params) {
    var s = catalog[key] || fallback[key] || key;
    if (params) {
      Object.keys(params).forEach(function (k) {
        s = s.split('{' + k + '}').join(String(params[k]));
      });
    }
    return s;
  }

  function apply(root) {
    var scope = root || document;
    scope.querySelectorAll('[data-i18n]').forEach(function (el) {
      var key = el.getAttribute('data-i18n');
      if (!key) return;
      el.textContent = t(key);
    });
    scope.querySelectorAll('[data-i18n-placeholder]').forEach(function (el) {
      var key = el.getAttribute('data-i18n-placeholder');
      if (key) el.setAttribute('placeholder', t(key));
    });
    scope.querySelectorAll('[data-i18n-aria]').forEach(function (el) {
      var key = el.getAttribute('data-i18n-aria');
      if (key) el.setAttribute('aria-label', t(key));
    });
    scope.querySelectorAll('[data-i18n-title]').forEach(function (el) {
      var key = el.getAttribute('data-i18n-title');
      if (key) el.setAttribute('title', t(key));
    });
    var disp = LANG_DISPLAY[lang] || LANG_DISPLAY.en;
    document.querySelectorAll('.locale-flag').forEach(function (el) {
      el.textContent = disp.flag;
    });
    document.querySelectorAll('.lang-select').forEach(function (sel) {
      SUPPORTED.forEach(function (code) {
        var meta = LANG_DISPLAY[code] || LANG_DISPLAY.en;
        var opt = sel.querySelector('option[value="' + code + '"]');
        if (opt) opt.textContent = meta.flag + ' ' + meta.code;
      });
      sel.value = lang;
    });
    document.documentElement.setAttribute('lang', lang);
    var footerLeft = document.querySelector('.platform-footer__left[data-i18n]');
    if (footerLeft) {
      var holder = footerLeft.getAttribute('data-holder') || 'Anton Afanaasyeu';
      var year = footerLeft.getAttribute('data-year') || String(new Date().getFullYear());
      footerLeft.textContent = t('footer.copyright', { holder: holder, year: year });
    }
  }

  function load(code) {
    lang = SUPPORTED.indexOf(code) >= 0 ? code : DEFAULT_LANG;
    try { localStorage.setItem(STORAGE_KEY, lang); } catch (e) {}
    return fetch(hubAsset('assets/i18n/hub-' + lang + '.json'), { credentials: 'same-origin' })
      .then(function (r) { return r.json(); })
      .then(function (json) {
        catalog = json || {};
        if (lang !== DEFAULT_LANG) {
          return fetch(hubAsset('assets/i18n/hub-en.json'), { credentials: 'same-origin' })
            .then(function (r) { return r.json(); })
            .then(function (fb) { fallback = fb || {}; });
        }
        fallback = catalog;
      })
      .then(function () { apply(document); });
  }

  function init() {
    var sel = document.getElementById('lang-select');
    lang = storedLang();
    if (sel) sel.value = lang;
    load(lang).then(function () {
      if (sel) {
        sel.addEventListener('change', function () { load(sel.value); });
      }
    });
  }

  global.HubI18n = { t: t, apply: apply, load: load, init: init };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})(window);
