(function () {
  function closeMenu(shell, button) {
    shell.classList.remove('is-open');
    button.setAttribute('aria-expanded', 'false');
  }

  function normalizeLanguageCode(value) {
    return String(value || '').trim().toLowerCase();
  }

  function initNavigation() {
    var shell = document.querySelector('.nav-shell');
    var button = document.querySelector('.nav-toggle');
    var nav = document.querySelector('.nav');

    if (!shell || !button || !nav) {
      return;
    }

    button.addEventListener('click', function () {
      var isOpen = shell.classList.toggle('is-open');
      button.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    });

    nav.addEventListener('click', function (event) {
      if (event.target.tagName === 'A') {
        closeMenu(shell, button);
      }
    });

    window.addEventListener('resize', function () {
      if (window.innerWidth > 760) {
        closeMenu(shell, button);
      }
    });

    document.addEventListener('keydown', function (event) {
      if (event.key === 'Escape') {
        closeMenu(shell, button);
      }
    });
  }

  function parseListingHashState() {
    var hash = window.location.hash ? window.location.hash.slice(1) : '';
    var params;

    if (!hash) {
      return {
        lang: '',
        article: '',
        category: ''
      };
    }

    params = new URLSearchParams(hash);
    return {
      lang: normalizeLanguageCode(params.get('lang')),
      article: String(params.get('article') || '').trim(),
      category: String(params.get('category') || '').trim()
    };
  }

  function optionExists(select, value) {
    var normalizedValue = normalizeLanguageCode(value);
    var options = select.options;
    var index;

    for (index = 0; index < options.length; index += 1) {
      if (normalizeLanguageCode(options[index].value) === normalizedValue) {
        return true;
      }
    }

    return false;
  }

  function updateListingHash(nextState, defaultLanguage) {
    var normalizedDefault = normalizeLanguageCode(defaultLanguage) || 'en';
    var currentState = parseListingHashState();
    var normalizedLanguage = currentState.lang;
    var articleTarget = currentState.article;
    var categoryTarget = currentState.category;
    var baseUrl = window.location.pathname + window.location.search;
    var params = new URLSearchParams();

    if (Object.prototype.hasOwnProperty.call(nextState, 'lang')) {
      normalizedLanguage = normalizeLanguageCode(nextState.lang);
    }
    if (Object.prototype.hasOwnProperty.call(nextState, 'article')) {
      articleTarget = String(nextState.article || '').trim();
    }
    if (Object.prototype.hasOwnProperty.call(nextState, 'category')) {
      categoryTarget = String(nextState.category || '').trim();
    }

    if (normalizedLanguage && normalizedLanguage !== normalizedDefault) {
      params.set('lang', normalizedLanguage);
    }
    if (articleTarget) {
      params.set('article', articleTarget);
    }
    if (categoryTarget) {
      params.set('category', categoryTarget);
    }

    if (!params.toString()) {
      if (window.location.hash) {
        window.history.replaceState(null, '', baseUrl);
      }
      return;
    }

    window.history.replaceState(null, '', baseUrl + '#' + params.toString());
  }

  function syncLanguageSelectPresentation(select) {
    var selectedOption;
    var optionDirection;
    var optionLanguage;

    if (!select || !select.options || select.selectedIndex < 0) {
      return;
    }

    selectedOption = select.options[select.selectedIndex];
    if (!selectedOption) {
      return;
    }

    optionLanguage = normalizeLanguageCode(selectedOption.getAttribute('lang')) || normalizeLanguageCode(selectedOption.value);
    optionDirection = String(selectedOption.getAttribute('dir') || '').trim().toLowerCase();

    if (optionLanguage) {
      select.setAttribute('lang', optionLanguage);
    } else {
      select.removeAttribute('lang');
    }

    if (optionDirection === 'rtl' || optionDirection === 'ltr') {
      select.setAttribute('dir', optionDirection);
    } else {
      select.removeAttribute('dir');
    }
  }

  function initArticleLanguageSelectors() {
    var selectors = document.querySelectorAll('.article-reader-controls__select');

    selectors.forEach(function (select) {
      syncLanguageSelectPresentation(select);
    });
  }

  function initArticlesListingLanguage() {
    var select = document.getElementById('articles-language-select');
    var categorySelects = document.querySelectorAll('[data-articles-category-select]');
    var routePayloadNode = document.getElementById('articles-language-routes');
    var displayPayloadNode = document.getElementById('articles-language-display');

    if (!categorySelects.length) {
      categorySelects = document.querySelectorAll('#articles-category-select');
    }

    if (!select || !routePayloadNode) {
      return;
    }

    var routePayload;
    var displayPayload = {};
    try {
      routePayload = JSON.parse(routePayloadNode.textContent || '{}');
    } catch (error) {
      return;
    }

    if (displayPayloadNode) {
      try {
        displayPayload = JSON.parse(displayPayloadNode.textContent || '{}');
      } catch (error) {
        displayPayload = {};
      }
    }

    var links = document.querySelectorAll('.listing-article-card[data-article-base-key]');
    if (!links.length) {
      return;
    }

    var defaultLanguage = normalizeLanguageCode(select.getAttribute('data-default-language')) || 'en';

    function resolveRoute(baseKey, languageCode, fallbackHref) {
      var languageRoutes = routePayload[baseKey];
      var normalizedLanguage = normalizeLanguageCode(languageCode);

      if (!languageRoutes) {
        return fallbackHref;
      }

      return languageRoutes[normalizedLanguage] || languageRoutes[defaultLanguage] || fallbackHref;
    }

    function resolveDisplayRecord(baseKey, languageCode) {
      var languageDisplay = displayPayload[baseKey];
      var normalizedLanguage = normalizeLanguageCode(languageCode);

      if (!languageDisplay) {
        return null;
      }

      return languageDisplay[normalizedLanguage] || languageDisplay[defaultLanguage] || null;
    }

    function resolveDisplayValue(displayRecord, fallbackRecord, fieldName) {
      var selectedValue = displayRecord && String(displayRecord[fieldName] || '').trim();
      if (selectedValue) {
        return selectedValue;
      }

      return fallbackRecord && String(fallbackRecord[fieldName] || '').trim();
    }

    function applyLanguageRoutes(normalizedLanguage) {
      links.forEach(function (link) {
        var baseKey = link.getAttribute('data-article-base-key');
        var fallbackHref = link.getAttribute('data-default-href') || link.getAttribute('href') || '';

        if (!baseKey) {
          return;
        }

        var nextHref = resolveRoute(baseKey, normalizedLanguage, fallbackHref);
        if (nextHref) {
          link.setAttribute('href', nextHref);
        }
      });
    }

    function applyLanguageDisplay(normalizedLanguage) {
      links.forEach(function (link) {
        var baseKey = link.getAttribute('data-article-base-key');
        var displayRecord;
        var fallbackRecord;
        var titleNode;
        var summaryNode;
        var metaNode;
        var titleText;
        var summaryText;
        var metaText;

        if (!baseKey) {
          return;
        }

        displayRecord = resolveDisplayRecord(baseKey, normalizedLanguage);
        fallbackRecord = resolveDisplayRecord(baseKey, defaultLanguage);

        if (!displayRecord && !fallbackRecord) {
          return;
        }

        titleNode = link.querySelector('.listing-article-title');
        summaryNode = link.querySelector('.listing-article-summary');
        metaNode = link.querySelector('.listing-article-meta');

        titleText = resolveDisplayValue(displayRecord, fallbackRecord, 'title');
        if (titleNode && titleText) {
          titleNode.textContent = titleText;
        }

        summaryText = resolveDisplayValue(displayRecord, fallbackRecord, 'summary');
        if (summaryNode && summaryText) {
          summaryNode.textContent = summaryText;
        }

        metaText = resolveDisplayValue(displayRecord, fallbackRecord, 'meta_text');
        if (metaNode && metaText) {
          metaNode.textContent = metaText;
        }
      });
    }

    function scrollToTarget(targetId, behavior) {
      var resolvedTargetId = String(targetId || '').trim();
      var target;

      if (!resolvedTargetId) {
        return;
      }

      target = document.getElementById(resolvedTargetId);
      if (!target) {
        return;
      }

      window.requestAnimationFrame(function () {
        target.scrollIntoView({
          behavior: behavior || 'auto',
          block: 'start'
        });
      });
    }

    function syncCategorySelect(categoryAnchorId) {
      var resolvedValue = String(categoryAnchorId || '').trim();
      categorySelects.forEach(function (categorySelect) {
        var options;
        var index;

        if (!resolvedValue) {
          categorySelect.value = '';
          return;
        }

        options = categorySelect.options;
        for (index = 0; index < options.length; index += 1) {
          if (String(options[index].value || '').trim() === resolvedValue) {
            categorySelect.value = resolvedValue;
            return;
          }
        }

        categorySelect.value = '';
      });
    }

    function applyLanguage(languageCode) {
      var normalizedLanguage = normalizeLanguageCode(languageCode);
      if (!normalizedLanguage || !optionExists(select, normalizedLanguage)) {
        normalizedLanguage = defaultLanguage;
      }

      select.value = normalizedLanguage;
      syncLanguageSelectPresentation(select);

      applyLanguageRoutes(normalizedLanguage);
      applyLanguageDisplay(normalizedLanguage);
    }

    function applyHashState(scrollBehavior) {
      var hashState = parseListingHashState();
      applyLanguage(hashState.lang || defaultLanguage);
      syncCategorySelect(hashState.category);
      scrollToTarget(hashState.article || hashState.category, scrollBehavior || 'auto');
    }

    select.addEventListener('change', function () {
      var selectedLanguage = normalizeLanguageCode(select.value) || defaultLanguage;
      applyLanguage(selectedLanguage);
      updateListingHash({ lang: selectedLanguage }, defaultLanguage);
    });

    categorySelects.forEach(function (categorySelect) {
      categorySelect.addEventListener('change', function () {
        var targetId = String(categorySelect.value || '').trim();
        syncCategorySelect(targetId);

        if (!targetId) {
          updateListingHash({ article: '', category: '' }, defaultLanguage);
          return;
        }

        scrollToTarget(targetId, 'smooth');
        updateListingHash({ article: '', category: targetId }, defaultLanguage);
      });
    });

    window.addEventListener('hashchange', function () {
      applyHashState('auto');
    });

    applyHashState('auto');
  }

  document.addEventListener('DOMContentLoaded', function () {
    initNavigation();
    initArticlesListingLanguage();
    initArticleLanguageSelectors();
  });
}());

