{% extends "base.html" %}

{#
================================================================================
Category Browser Template (Kida-Native v2)
================================================================================

Displays all categories with post counts and recent posts.
Perfect for documentation sites to browse by category/type.
Uses query indexes for O(1) category lookups.

URL Pattern: /categories/

KIDA FEATURES SHOWCASED:
- {% let %} for template-scoped variables (multi-assignment)
- {% match %} for layout dispatch and pluralization
- {% cache %} for expensive category computations
- {% unless %} for negative conditionals
- Pipeline operators (|>) for filter chains
- Optional chaining (?.) and null coalescing (??)
- {% spaceless %} for clean HTML output

Usage:
Create content/categories/_index.md:
---
title: "Browse by Category"
template: category-browser.html
description: "Explore documentation organized by category"
---

Optional metadata:
- sections: ["docs", "blog"] (only show categories from these sections)
- show_recent: 3 (number of recent posts to show per category)
- layout: "grid" or "list" (default: "grid")

Context variables:
- page: Current page
- site.indexes.category: Category index
================================================================================
#}

{% from 'partials/navigation-components.html' import breadcrumbs %}
{% from 'partials/components/tags.html' import tag_list %}

{# =============================================================================
   CONFIGURATION (Kida multi-let)
   ============================================================================= #}
{% let
    section_filters = params?.sections ?? [],
    show_recent = params?.show_recent ?? 3,
    layout = params?.layout ?? 'grid',
    all_categories = (site?.indexes?.category?.keys() ?? []) |> sort |> list
%}

{# =============================================================================
   HELPER MACROS
   ============================================================================= #}

{# Filter posts by section - returns filtered list #}
{% def filter_by_section(posts, filters) %}
{% if filters | length > 0 %}
{{ posts |> selectattr('_section.name', 'in', filters) |> list }}
{% else %}
{{ posts }}
{% end %}
{% end %}

{# Category card component with caching #}
{% def category_card(category, section_filters, show_recent) %}
{% let raw_posts = site.indexes.category.get(category) |> resolve_pages %}
{% let category_posts = raw_posts |> selectattr('_section.name', 'in', section_filters) |> list if section_filters | length > 0 else raw_posts %}

{% if category_posts | length > 0 %}
{% let
    post_count = category_posts | length,
    total_words = category_posts |> map(attribute='content') |> join('') |> wordcount,
    authors = category_posts |> map(attribute='params.author') |> unique |> list,
    recent_posts = category_posts |> sort(attribute='date', reverse=true) |> take(show_recent)
%}

<article class="category-card">
    <div class="category-header">
        <h2 class="category-title">
            <a href="{{ ('/category/' ~ category ~ '/') | absolute_url }}">{{ category | title }}</a>
        </h2>
        {% spaceless %}
        <span class="category-count">
            {% match post_count %}
            {% case 1 %}1 page
            {% case n %}{{ n }} pages
            {% end %}
        </span>
        {% end %}
    </div>

    {# Category stats #}
    <div class="category-meta">
        <span class="meta-item">
            {{ total_words |> format_number }} words
        </span>

        {% if authors | length > 0 %}
        {% spaceless %}
        <span class="meta-item">
            {% match authors | length %}
            {% case 1 %}1 author
            {% case n %}{{ n }} authors
            {% end %}
        </span>
        {% end %}
        {% end %}
    </div>

    {# Recent posts in this category #}
    {% if show_recent > 0 and recent_posts | length > 0 %}
    <div class="category-recent">
        <h3 class="recent-title">Recent:</h3>
        <ul class="recent-list">
            {% for post in recent_posts %}
            <li>
                <a href="{{ post?.href ?? '#' }}">{{ post?.title ?? 'Untitled' }}</a>
                {% with post?.date as post_date %}
                <time datetime="{{ post_date |> date_iso }}">
                    {{ post_date |> time_ago }}
                </time>
                {% end %}
            </li>
            {% end %}
        </ul>

        {% if post_count > show_recent %}
        <a href="{{ ('/category/' ~ category ~ '/') | absolute_url }}" class="view-all">
            View all {{ post_count }} →
        </a>
        {% end %}
    </div>
    {% end %}
</article>
{% end %}
{% end %}

{# Letter group for A-Z index - uses caching for expensive lookups #}
{% def letter_group(letter, categories, section_filters) %}
<div class="letter-group">
    <strong class="letter">{{ letter }}</strong>
    <ul class="letter-list">
        {% for cat in categories %}
        {% let raw_posts = site.indexes.category.get(cat) |> resolve_pages %}
        {% let cat_posts = raw_posts |> selectattr('_section.name', 'in', section_filters) |> list if section_filters | length > 0 else raw_posts %}
        {% if cat_posts | length > 0 %}
        <li>
            <a href="{{ ('/category/' ~ cat ~ '/') | absolute_url }}">
                {{ cat | title }} ({{ cat_posts | length }})
            </a>
        </li>
        {% end %}
        {% end %}
    </ul>
</div>
{% end %}

{# =============================================================================
   MAIN TEMPLATE
   ============================================================================= #}

{% block content %}
{{ breadcrumbs(page) }}

<div class="category-browser">
    <header class="browser-header">
        <h1>{{ page?.title ?? 'Browse by Category' }}</h1>

        {% with params?.description as desc %}
        <p class="browser-description">{{ desc }}</p>
        {% end %}
    </header>

    {# Main content from markdown #}
    {% with content as page_content %}
    <div class="browser-content prose">
        {{ page_content | safe }}
    </div>
    {% end %}

    {% if all_categories | length > 0 %}
    {# =========================================================================
       SUMMARY STATS - Cached for expensive computation
       ========================================================================= #}
    {% cache 'category-browser-stats-' ~ (section_filters |> join('-')) %}
    {% let total_pages = all_categories |> map('site.indexes.category.get') |> map('resolve_pages') |> map('length') |> sum ?? 0 %}
    <div class="browser-stats">
        {% spaceless %}
        <span class="stat">
            <strong>{{ all_categories | length }}</strong>
            {% match all_categories | length %}
            {% case 1 %}category
            {% case _ %}categories
            {% end %}
        </span>
        {% end %}

        <span class="stat">
            <strong>{{ total_pages }}</strong> total pages
        </span>
    </div>
    {% end %}

    {# =========================================================================
       LAYOUT TOGGLE - Pattern matched for active state
       ========================================================================= #}
    <div class="layout-toggle">
        {% for layout_option in ['grid', 'list'] %}
        {% let is_active = layout == layout_option %}
        {% let label = 'Grid view' if layout_option == 'grid' else 'List view' %}
        {% let emoji = '' %}
        <button class="layout-btn{{ ' active' if is_active else '' }}"
                data-layout="{{ layout_option }}"
                aria-label="{{ label }}"
                {{ 'aria-pressed="true"' | safe if is_active else '' }}>
            {{ emoji }} {{ layout_option | title }}
        </button>
        {% end %}
    </div>

    {# =========================================================================
       CATEGORY GRID/LIST - Main content area
       ========================================================================= #}
    <div class="category-container" data-layout="{{ layout }}">
        {% for category in all_categories %}
        {{ category_card(category, section_filters, show_recent) }}
        {% end %}
    </div>

    {# =========================================================================
       ALPHABETICAL INDEX - Grouped by first letter
       ========================================================================= #}
    {% cache 'category-browser-index-' ~ (section_filters |> join('-')) %}
    <aside class="category-index">
        <h3>Quick Index</h3>
        <nav class="alpha-nav" aria-label="Alphabetical category index">
            {# Group categories by first letter using Kida's groupby filter #}
            {% for group in all_categories |> groupby('0 | upper') %}
            {% let letter = group?.grouper ?? '?' %}
            {% let cats = group?.list ?? [] %}
            {{ letter_group(letter, cats, section_filters) }}
            {% end %}
        </nav>
    </aside>
    {% end %}

    {% else %}
    {# =========================================================================
       EMPTY STATE
       ========================================================================= #}
    <div class="browser-empty">
        <div class="empty-state">
            <p class="empty-message">No categories found.</p>
            <p class="empty-hint">Add <code>categories: ["tutorial", "guide"]</code> to page frontmatter to create categories.</p>
        </div>
    </div>
    {% end %}
</div>

<script>
    // Layout toggle functionality
    document.querySelectorAll('.layout-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const layout = btn.dataset.layout;
            const container = document.querySelector('.category-container');

            // Update buttons
            document.querySelectorAll('.layout-btn').forEach(b => {
                b.classList.remove('active');
                b.setAttribute('aria-pressed', 'false');
            });
            btn.classList.add('active');
            btn.setAttribute('aria-pressed', 'true');

            // Update container
            container.dataset.layout = layout;
        });
    });
</script>

{% end %}
