{% assign desktopMode = desktopMode | default: false %}
{% assign parentClass = parentClass | default: "" %}

<a class="
  {% if desktopMode %}
    np-header-avatar-tooltip-navigation-link
  {% else %}
    np-header-mobile-menu-content-button
  {% endif %}
  " onclick="toggleLanguageSelector('{{parentClass}}')">
  <span class="lang-en">Language</span>
  <span class="lang-es">Idioma</span>
  <div
    {% if desktopMode %}
    style="padding-top: 10px;"
    {% endif %}
    class="language-selector-dropdown">
    <div class="{% if desktopMode %}np-header-avatar-tooltip-navigation-link{% else %}language-selector-dropdown-item{% endif %}" onclick="changeLanguage('en')">English</div>
    <div class="{% if desktopMode %}np-header-avatar-tooltip-navigation-link{% else %}language-selector-dropdown-item{% endif %}" onclick="changeLanguage('es')">Español</div>
  </div>
</a>


<style>
  .language-selector-dropdown {
    position: absolute;
    width: 97%;
    background-color: white;
    z-index: 1;
    top: 54px;
    padding: 0 10px 10px;
    border-radius: 4px;
    box-shadow: 0 2px 4px 0 rgba(72, 103, 118, 0.65);
  }

  .language-selector-dropdown-item {
    align-items: center;
    background: #e4e8eb;
    border-radius: 4px;
    box-shadow: 0 2px 4px 0 rgba(72, 103, 118, 0.15);
    color: #305263;
    display: flex;
    font-size: 14px;
    font-weight: 500;
    height: 52px;
    justify-content: center;
    margin-top: 12px;
    text-decoration: none;
    width: 100%;
  }
</style>
<script>
  $(document).ready(function () {
    $('.language-selector-dropdown').hide();

    // Close dropdown when clicking outside
    $(document).on('click', function (event) {
      if (!$(event.target).closest('.language-selector-dropdown, [onclick*="toggleLanguageSelector"]').length) {
        $('.language-selector-dropdown').hide();
      }
    });
  });

  function toggleLanguageSelector(parentClass) {
    $(`.${parentClass} .language-selector-dropdown`).toggle();
  }

  function changeLanguage(language) {
    const url = "https://instacart.northpass.com/learning/api/v1/carrot_academy/languages/{{current_person.id}}";
    const token = document.querySelector('meta[name="csrf-token"]')?.content;

    fetch(url, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-Token": token
        },
        credentials: "include",
        body: JSON.stringify({
          language: language,
        })
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok ' + response.statusText);
        }
        return response;
      })
      .then(data => {
        const currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set('lang', language);
        window.location.href = currentUrl.toString();
      })
      .catch(error => {
        console.error("Error sending language information:", error);
      });
  }
</script>
