{#
  This is in a separate file because of a bizarre TwigJS bug,
  where calling a macro imported with _self somehow wipes out the
  item object.
#}

{% macro menu_links(items, attributes, menu_level, menu_name, menu_class, item_class, link_class) %}
  {% import _self as menus %}
  {% if items %}
    <ul {{ add_attributes({class: ['c-mega-menu__subnav']}) }}>
    {% for menu_item in items %}
      {% set item_classes = ['c-mega-menu__item'] %}
      {% set link_classes = ['c-mega-menu__link'] %}

      {% if menu_item.below %}
        {% set item_classes = item_classes|merge(['has-subnav']) %}
        {% set link_classes = link_classes|merge(['has-subnav']) %}
      {% endif %}
      {% if menu_item.in_active_trail %}
        {% set item_classes = item_classes|merge(['is-active-trail']) %}
        {% set link_classes = link_classes|merge(['is-active-trail']) %}
      {% endif %}
      {% if menu_item.is_collapsed %}
        {% set item_classes = item_classes|merge(['is-collapsed']) %}
        {% set link_classes = link_classes|merge(['is-collapsed']) %}
      {% endif %}
      {% if menu_item.is_expanded %}
        {% set item_classes = item_classes|merge(['is-expanded']) %}
        {% set link_classes = link_classes|merge(['is-expanded']) %}
      {% endif %}
      {% if menu_item['original_link'].options.attributes.class %}
        {% set original_link_class = menu_item['original_link'].options.attributes.class %}
        {% if original_link_class is not iterable %}
          {% set original_link_class = [original_link_class] %}
        {% endif %}
        {% set link_classes = link_classes|merge(original_link_class) %}
      {% endif %}
      {% if item_class %}
        {% set item_classes = item_classes|merge(item_class) %}
      {% endif %}
      {% if link_class %}
        {% set link_classes = link_classes|merge(link_class) %}
      {% endif %}

      {% set additional_item_attributes = {
        'class': item_classes
      } %}

      {% set link_attributes = {
        'class': link_classes
      } %}

      <li {{ add_attributes(additional_item_attributes) }}>
        {% if menu_item.url == '<button>' %}
          {# This is needed to work in Storybook. #}
          <button {{ add_attributes(link_attributes) }}>{{ menu_item.title }}</button>
        {% else %}
          {{ link(menu_item.title, menu_item.url, link_attributes) }}
        {% endif %}

        {% if menu_item.below %}
          {{ menus.menu_links(menu_item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}
