{#
/**
 * @file
 * Theme override to display main menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}
{% import _self as menus %}

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}

  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu main-menu').setAttribute('role', 'menubar') }}>
    {% else %}
      <ul class="submenu" role="menu">
    {% endif %}

    {% for item in items %}

      {%
        set item_classes = [
          'menu-item',
          'main-menu-item',
          'menu-item-level-' ~ (menu_level + 1),
          item.is_expanded ? 'expanded',
          item.is_collapsed ? 'collapsed',
          item.below ? 'menu-item-has-children',
          item.in_active_trail ? 'active menu-item-active',
        ]
      %}
      {% set has_children = item.below ? true : false %}

      <li{{ item.attributes.addClass(item_classes).setAttribute('role', 'none') }}>
        
        {# Link #}
        <a href="{{ item.url }}"
           role="menuitem"
           tabindex="0"
           {% if has_children %}
             aria-haspopup="true"
             aria-expanded="false"
           {% endif %}
        >
          {{ item.title }}
        </a>

        {# Add button for submenu toggle (better accessibility) #}
        {% if has_children %}
          <button class="submenu-toggle"
          aria-label="Toggle submenu"
          aria-haspopup="true"
          aria-expanded="false">+</button>

          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

      </li>
    {% endfor %}

    </ul>
  {% endif %}
{% endmacro %}