{% with title='Tags', url=config.link + '/tags', description='All tags', type='index', image=None, skip_header=not config.header, styles=['/css/home.css'] %}
  {% include 'common-head.html' %}
{% endwith %}

<main>
  <div class="container">
    <div class="tags-header">
      <h1>Tags</h1>
      {% if tags %}
      <div class="tags-stats">
        <span class="tag-total">{{ tags|length }} tags</span>
        <span class="post-total">{{ tags|sum(attribute=1) }} posts</span>
      </div>
      {% endif %}
    </div>

    {% if tags %}
    <div class="tags-controls">
      <button class="sort-btn active" data-sort="count">Sort by Count</button>
      <button class="sort-btn" data-sort="alpha">Sort Alphabetically</button>
    </div>

    <div class="tags" id="tags-container">
      {% for tag, count in tags %}
        <a class="tag" href="/tags/{{ tag }}" data-tag="{{ tag }}" data-count="{{ count }}">
          <span class="tag-name">#{{ tag }}</span>
          <span class="tag-count">{{ count }}</span>
        </a>
      {% endfor %}
    </div>
    {% else %}
    <p class="no-tags">No tags found.</p>
    {% endif %}
  </div>
</main>

<script>
function refreshSort() {
  // Get active sort button
  const sortButtons = document.querySelectorAll('.sort-btn');
  const activeButton = Array.from(sortButtons).find(btn => btn.classList.contains('active'));

  // Get all tag elements
  const tagsContainer = document.getElementById('tags-container');
  const tags = Array.from(tagsContainer.querySelectorAll('.tag'));

  // Sort based on selected method
  const sortType = activeButton.dataset.sort;
  tags.sort((a, b) => {
    if (sortType === 'alpha') {
      return a.dataset.tag.localeCompare(b.dataset.tag);
    } else {
      return parseInt(b.dataset.count) - parseInt(a.dataset.count);
    }
  });

  // Re-append sorted elements
  tags.forEach(tag => tagsContainer.appendChild(tag));
}

document.addEventListener('DOMContentLoaded', function() {
  const sortButtons = document.querySelectorAll('.sort-btn');

  sortButtons.forEach(button => {
    button.addEventListener('click', (event) => {
      // Update active button
      sortButtons.forEach(btn => btn.classList.remove('active'));
      event.target.classList.add('active');

      // Refresh sort
      refreshSort();
    });
  });

  // Initial sort
  refreshSort();
});
</script>

{% include 'footer.html' %}
{% include 'common-tail.html' %}
