{% import 'macros/side-nav-item-class.j2' as class_helper with context %}
{% import 'macros/side-nav-item.j2' as item_helper with context %}
{% import 'macros/section-index-page-title.j2' as index_helper with context %}

{% macro side_nav_item( nav_item ) -%}
    {% set macro_ns = namespace(class="") %}
    {% set macro_ns.class = class_helper.get_class( nav_item ) -%}

    {% if "navigation.side.indexes" in features and nav_item.title == index_helper.get_section_index_page_title() %}
        {{ item_helper.index_item( nav_item, macro_ns.class ) }}
    {% else %}
        {{ item_helper.non_index_item( nav_item, macro_ns.class ) }}
    {% endif %}
{%- endmacro -%}

{% macro second_level_folder( nav_items ) -%}
    <ul class="terminal-mkdocs-side-nav-li-ul">
        {% for nav_item in nav_items %}
            {% set found_index = false %}
            {% if "navigation.side.indexes" in features %}
                {% set index_matches = nav_item.children|selectattr("title", "eq", index_helper.get_section_index_page_title())|list %}
                {% if index_matches|length > 0 %}
                    {% set found_index = true %}
                {% endif %}
            {% endif %}

            {% if found_index %}
                <li class="terminal-mkdocs-side-nav-li-ul-li">{{ side_nav_item( nav_item.children|selectattr("title", "eq", index_helper.get_section_index_page_title())|list|first ) }}</li>
            {% else %} 
                <li class="terminal-mkdocs-side-nav-li-ul-li">{{ side_nav_item( nav_item ) }}</li>
            {% endif %}
        {% endfor %}    
    </ul>
{%- endmacro -%}

<li class="terminal-mkdocs-side-nav-li">
    {% if nav_item.children %}
    
        {% set ns = namespace(index_matches=[], found_index=false) %}
        {% if "navigation.side.indexes" in features %}
            {% set ns.index_matches = nav_item.children|selectattr("title", "eq", index_helper.get_section_index_page_title())|list %}
            {% if ns.index_matches|length > 0 %}
                {% set ns.found_index = true %}
            {% endif %}    
        {% endif %}

        {% if "navigation.side.indexes" in features and ns.found_index %}     
            {{ side_nav_item(ns.index_matches[0]) }}
        {% else %}
            {{ side_nav_item( nav_item ) }}
        {% endif %}
      
        {% if "navigation.side.indexes" in features and ns.found_index %}
            {{ second_level_folder( nav_item.children|rejectattr("title", "eq", index_helper.get_section_index_page_title())|list ) }}
        {% else %}
            {{ second_level_folder( nav_item.children ) }}
        {% endif %}
    {% else %}
    {{ side_nav_item( nav_item ) }}
    {% endif %}
  </li>