{#
================================================================================
Tag Navigation Sidebar Component (Kida-Native)
================================================================================

Displays a list of all tags in the sidebar.

KIDA FEATURES USED:
- {% let %} for template-scoped variables
- Optional chaining (?.) for null-safe access
- Null coalescing (??) for smart defaults

Variables:
- tags: List of tag objects with .name and .count (optional)
- current_tag: Current tag name if viewing a tag page (optional)
================================================================================
#}

{# Template-scoped variables #}
{# Popular tags - assign outside cache for variable access #}
{% if tags is defined %}
  {% let all_tags = tags %}
{% else %}
  {% let all_tags = popular_tags(limit=50) %}
{% end %}
{% let current_tag_normalized = (current_tag ?? '') | lower %}

<nav class="docs-nav" aria-label="Tags">
  <div class="docs-nav-tree">
    {# Link to all tags page #}
    {% let is_all_tags = (current_tag ?? '') | length == 0 %}
    <a href="{{ '/tags/' | absolute_url }}" class="{{ ['docs-nav-link', 'active' if is_all_tags] | classes }}"
      {{ 'aria-current="page"' | safe if is_all_tags else '' }}>
      All Tags
    </a>

    {# List of tags #}
    {% if all_tags %}
    {% for tag_item in all_tags %}
    {# Handle both formats: dict with .name/.count (from tags page) OR tuples (slug, count) from popular_tags #}
    {# For dicts, tag_item[1] raises KeyError; for tuples, tag_item?.count returns the .count method. #}
    {% let tag_name = tag_item?.name ?? tag_item[0] ?? '' %}
    {% let tag_count = (tag_item?.count if tag_item is mapping else tag_item[1]) ?? 0 %}
    {% let tag_name_normalized = tag_name | lower %}
    {% let is_active = current_tag_normalized == tag_name_normalized %}

    <a href="{{ (tag_item?.href ?? tag_url(tag_name)) | absolute_url }}" class="{{ ['docs-nav-link', 'active' if is_active] | classes }}" {{ 'aria-current="page"'
      | safe if is_active else '' }}>
      <span class="tag-nav-name">{{ tag_name }}</span>
      <span class="tag-nav-count">({{ tag_count }})</span>
    </a>
    {% export last_tag = tag_item %}
    {% end %}
    {% end %}
  </div>
</nav>
