{% extends "base.twig" %}

{% block title %}{{ title }}{% endblock %}

{% block styles %}
<style>
    :root {
        --primary: #667eea;
        --primary-light: #818cf8;
        --primary-dark: #4f46e5;
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --info: #3b82f6;
        --gray-50: #f9fafb;
        --gray-100: #f3f4f6;
        --gray-200: #e5e7eb;
        --gray-500: #6b7280;
        --gray-600: #4b5563;
        --gray-700: #374151;
        --gray-800: #1f2937;
        --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
        --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
    }

    .comparison-container {
        width: 100%;
        padding: 24px;
        background: var(--gray-50);
        min-height: calc(100vh - 70px);
    }

    /* Header */
    .page-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 28px 32px;
        border-radius: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: var(--shadow-lg);
        margin-bottom: 24px;
        position: relative;
        overflow: hidden;
    }

    .page-header::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -10%;
        width: 300px;
        height: 300px;
        background: rgba(255,255,255,0.1);
        border-radius: 50%;
    }

    .header-content h1 {
        font-size: 28px;
        font-weight: 700;
        margin-bottom: 4px;
    }

    .header-content p {
        opacity: 0.9;
        font-size: 14px;
    }

    /* KPI Cards */
    .kpi-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20px;
        margin-bottom: 24px;
    }

    .kpi-card {
        background: white;
        border-radius: 12px;
        padding: 20px 24px;
        box-shadow: var(--shadow);
        display: flex;
        align-items: center;
        gap: 16px;
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .kpi-card:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
    }

    .kpi-icon {
        width: 52px;
        height: 52px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        flex-shrink: 0;
    }

    .kpi-icon.blue { background: rgba(102, 126, 234, 0.12); color: var(--primary); }
    .kpi-icon.green { background: rgba(16, 185, 129, 0.12); color: var(--success); }
    .kpi-icon.red { background: rgba(239, 68, 68, 0.12); color: var(--danger); }

    .kpi-info .label {
        font-size: 13px;
        color: var(--gray-500);
        margin-bottom: 4px;
    }

    .kpi-info .value {
        font-size: 28px;
        font-weight: 700;
        color: var(--gray-800);
    }

    /* Chart Card */
    .chart-card {
        background: white;
        border-radius: 16px;
        box-shadow: var(--shadow);
        padding: 24px;
        margin-bottom: 24px;
    }

    .chart-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .chart-title {
        font-size: 18px;
        font-weight: 600;
        color: var(--gray-800);
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .chart-title i {
        color: var(--primary);
    }

    .chart-wrapper {
        position: relative;
        height: 320px;
    }

    /* Table Card */
    .table-card {
        background: white;
        border-radius: 16px;
        box-shadow: var(--shadow);
        overflow: hidden;
    }

    .table-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 24px;
        border-bottom: 1px solid var(--gray-100);
        flex-wrap: wrap;
        gap: 12px;
    }

    .table-title {
        font-size: 18px;
        font-weight: 600;
        color: var(--gray-800);
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .table-title i {
        color: var(--primary);
    }

    .search-box {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 16px;
        border: 1px solid var(--gray-200);
        border-radius: 8px;
        background: var(--gray-50);
    }

    .search-box input {
        border: none;
        background: transparent;
        outline: none;
        font-size: 14px;
        width: 220px;
    }

    .search-box i {
        color: var(--gray-500);
    }

    /* Table Styles */
    .table-responsive {
        overflow-x: auto;
    }

    .data-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }

    .data-table thead th {
        background: var(--gray-50);
        padding: 12px 10px;
        font-weight: 600;
        color: var(--gray-700);
        border-bottom: 2px solid var(--gray-200);
        white-space: nowrap;
        text-align: left;
        cursor: pointer;
        user-select: none;
        position: relative;
    }

    .data-table thead th:hover {
        background: var(--gray-100);
    }

    .data-table thead th .sort-icon {
        margin-left: 4px;
        opacity: 0.4;
        font-size: 12px;
    }

    .data-table thead th.sort-asc .sort-icon,
    .data-table thead th.sort-desc .sort-icon {
        opacity: 1;
        color: var(--primary);
    }

    .data-table thead th.text-center { text-align: center; }
    .data-table thead th.text-right { text-align: right; }

    .data-table tbody td {
        padding: 12px 10px;
        border-bottom: 1px solid var(--gray-100);
        vertical-align: middle;
    }

    .data-table tbody tr:hover {
        background: var(--gray-50);
    }

    .participant-name {
        font-weight: 500;
        color: var(--gray-800);
    }

    .business-name {
        font-size: 12px;
        color: var(--gray-500);
    }

    .coach-badge {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 12px;
        background: rgba(102, 126, 234, 0.1);
        color: var(--primary);
        white-space: nowrap;
    }

    .money-value {
        font-family: 'JetBrains Mono', monospace;
        font-size: 13px;
        font-weight: 500;
        white-space: nowrap;
    }

    .money-zero {
        color: var(--gray-500);
    }

    /* Change % */
    .change-badge {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 13px;
        font-weight: 600;
        white-space: nowrap;
    }

    .change-badge.positive {
        background: rgba(16, 185, 129, 0.12);
        color: #059669;
    }

    .change-badge.negative {
        background: rgba(239, 68, 68, 0.12);
        color: #dc2626;
    }

    .change-badge.neutral {
        background: var(--gray-100);
        color: var(--gray-500);
    }

    /* Trend Arrow */
    .trend-arrow {
        font-size: 18px;
    }

    .trend-arrow.up { color: var(--success); }
    .trend-arrow.down { color: var(--danger); }
    .trend-arrow.flat { color: var(--gray-500); }
    .trend-arrow.none { color: var(--gray-200); }

    /* Compare highlight */
    .show-highlight .cmp-latest { background: rgba(102,126,234,0.12); border-left: 2px solid #667eea; }
    .show-highlight .cmp-previous { background: rgba(148,163,184,0.12); border-left: 2px solid #94a3b8; }
    .cmp-tag { font-size: 9px; font-weight: 600; }
    .cmp-tag-latest { color: #667eea; }
    .cmp-tag-previous { color: #94a3b8; }
    .show-highlight .cmp-tag { display: block; }
    .cmp-tag { display: none; }

    /* No data */
    .no-data-row td {
        padding: 40px !important;
        text-align: center;
        color: var(--gray-500);
    }

    /* Responsive */
    @media (max-width: 1200px) {
        .kpi-grid { grid-template-columns: repeat(3, 1fr); }
    }

    @media (max-width: 768px) {
        .kpi-grid { grid-template-columns: 1fr; }
        .page-header {
            flex-direction: column;
            text-align: center;
            gap: 16px;
        }
        .table-header { flex-direction: column; }
        .search-box { width: 100%; }
        .search-box input { width: 100%; }
    }
</style>
{% endblock %}

{% block contents %}
<div class="comparison-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1><i class="bi bi-bar-chart-steps me-2"></i>{{ title }}</h1>
            <p>Prestasi jualan berdasarkan majoriti bulan meningkat/menurun sepanjang 6 bulan. Jika seri (3:3), magnitud terbesar menjadi penentu.</p>
        </div>
    </div>

    <!-- KPI Cards -->
    <div class="kpi-grid">
        <div class="kpi-card">
            <div class="kpi-icon blue">
                <i class="bi bi-people-fill"></i>
            </div>
            <div class="kpi-info">
                <div class="label">Jumlah Peserta</div>
                <div class="value">{{ totalParticipants }}</div>
            </div>
        </div>
        <div class="kpi-card">
            <div class="kpi-icon green">
                <i class="bi bi-arrow-up-circle-fill"></i>
            </div>
            <div class="kpi-info">
                <div class="label">Meningkat</div>
                <div class="value" style="color: var(--success);">{{ improvedCount }}</div>
            </div>
        </div>
        <div class="kpi-card">
            <div class="kpi-icon red">
                <i class="bi bi-arrow-down-circle-fill"></i>
            </div>
            <div class="kpi-info">
                <div class="label">Menurun</div>
                <div class="value" style="color: var(--danger);">{{ declinedCount }}</div>
            </div>
        </div>
        <div class="kpi-card">
            <div class="kpi-icon" style="background: rgba(245, 158, 11, 0.15); color: var(--warning);">
                <i class="bi bi-balance-scale"></i>
            </div>
            <div class="kpi-info">
                <div class="label">Seri (Magnitud Penentu)</div>
                <div class="value" style="color: var(--warning);">{{ tieCount|default(0) }}</div>
            </div>
        </div>
    </div>

    <!-- Aggregate Chart -->
    <div class="chart-card">
        <div class="chart-card-header">
            <h3 class="chart-title">
                <i class="bi bi-bar-chart-line-fill"></i> Trend Hasil & Keuntungan Keseluruhan
            </h3>
        </div>
        <div class="chart-wrapper">
            <canvas id="aggregateChart"></canvas>
        </div>
    </div>

    <!-- Data Table -->
    <div class="table-card">
        <div class="table-header">
            <h3 class="table-title">
                <i class="bi bi-table"></i> Perbandingan Bulanan Peserta
            </h3>
            <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
                <div style="display:flex; align-items:center; gap:6px; font-size:13px; color:#64748b;">
                    <label for="rowsPerPage" style="margin:0;">Tunjuk:</label>
                    <select id="rowsPerPage" style="padding:6px 10px; border:1px solid #e5e7eb; border-radius:6px; background:white;">
                        <option value="10">10</option>
                        <option value="25">25</option>
                        <option value="50" selected>50</option>
                        <option value="100">100</option>
                        <option value="all">Semua</option>
                    </select>
                    <span>baris</span>
                </div>
                <div class="search-box">
                    <i class="bi bi-search"></i>
                    <input type="text" id="searchInput" placeholder="Cari nama, perniagaan, coach...">
                </div>
            </div>
        </div>
        <div class="table-responsive">
            <table class="data-table" id="comparisonTable">
                <thead>
                    <tr>
                        <th data-sort="name">
                            Peserta <i class="bi bi-arrow-down-up sort-icon"></i>
                        </th>
                        <th data-sort="coach">
                            Coach <i class="bi bi-arrow-down-up sort-icon"></i>
                        </th>
                        {% for label in monthLabels %}
                        <th class="text-right" data-sort="month-{{ loop.index0 }}">
                            {{ label }} <i class="bi bi-arrow-down-up sort-icon"></i>
                        </th>
                        {% endfor %}
                        <th class="text-right" data-sort="change">
                            Jumlah Jualan <i class="bi bi-arrow-down-up sort-icon"></i>
                        </th>
                        <th class="text-center" data-sort="counts">
                            Naik / Turun <i class="bi bi-arrow-down-up sort-icon"></i>
                        </th>
                        <th class="text-center" data-sort="trend">
                            Prestasi Jualan <i class="bi bi-arrow-down-up sort-icon"></i>
                        </th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    {% for p in comparison %}
                    <tr class="data-row"
                        data-name="{{ p.name|lower }}"
                        data-business="{{ p.business_name|lower }}"
                        data-coach="{{ p.coach_name|lower }}"
                        data-change="{{ p.totalSales|default(0) }}"
                        data-counts="{{ p.salesInc|default(0) - p.salesDec|default(0) }}"
                        data-trend="{{ p.trend }}"
                        {% for m in p.monthData %}
                        data-month-{{ loop.index0 }}="{{ m.revenue }}"
                        {% endfor %}
                    >
                        <td>
                            <div class="participant-name">{{ p.name }}</div>
                            <div class="business-name">{{ p.business_name ?: '-' }}</div>
                        </td>
                        <td>
                            <span class="coach-badge">{{ p.coach_name ?: '-' }}</span>
                        </td>
                        {% for m in p.monthData %}
                        <td class="text-right">
                            {% if m.revenue is not null and m.revenue > 0 %}
                                <span class="money-value">RM {{ m.revenue|number_format(0, '.', ',') }}</span>
                            {% elseif m.revenue is not null %}
                                <span class="money-value money-zero">RM 0</span>
                            {% else %}
                                <span class="money-value money-zero">-</span>
                            {% endif %}
                        </td>
                        {% endfor %}
                        <td class="text-right">
                            <span class="money-value">RM {{ p.totalSales|number_format(0, '.', ',') }}</span>
                        </td>
                        <td class="text-center">
                            {% if (p.salesInc + p.salesDec) > 0 %}
                                <span style="color: var(--success); font-weight: 600;">{{ p.salesInc }}↑</span>
                                <span style="color: var(--gray-500); margin: 0 4px;">/</span>
                                <span style="color: var(--danger); font-weight: 600;">{{ p.salesDec }}↓</span>
                            {% else %}
                                <span style="color: var(--gray-500);">-</span>
                            {% endif %}
                        </td>
                        <td class="text-center">
                            {% if p.trend == 'up' %}
                                <span class="change-badge positive">
                                    <i class="bi bi-caret-up-fill"></i> Meningkat
                                </span>
                                {% if p.tieBreaker == 'magnitude' %}
                                <div style="font-size:9px; color:var(--warning); margin-top:2px;" title="Ditentukan oleh magnitud kerana naik/turun seri">
                                    <i class="bi bi-balance-scale"></i> seri (magnitud)
                                </div>
                                {% endif %}
                            {% elseif p.trend == 'down' %}
                                <span class="change-badge negative">
                                    <i class="bi bi-caret-down-fill"></i> Menurun
                                </span>
                                {% if p.tieBreaker == 'magnitude' %}
                                <div style="font-size:9px; color:var(--warning); margin-top:2px;" title="Ditentukan oleh magnitud kerana naik/turun seri">
                                    <i class="bi bi-balance-scale"></i> seri (magnitud)
                                </div>
                                {% endif %}
                            {% else %}
                                <span class="change-badge neutral" style="font-size:11px;">
                                    <i class="bi bi-dash"></i> Tiada Perbandingan
                                </span>
                            {% endif %}
                        </td>
                    </tr>
                    {% else %}
                    <tr class="no-data-row">
                        <td colspan="{{ 5 + monthLabels|length }}">Tiada data perbandingan ditemui.</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        <div style="display:flex; justify-content:space-between; align-items:center; padding:12px 16px; border-top:1px solid #e5e7eb; gap:12px; flex-wrap:wrap;">
            <div id="paginationInfo" style="font-size:13px; color:#64748b;"></div>
            <div id="paginationControls" style="display:flex; gap:6px; align-items:center;"></div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {

    // ── Aggregate Chart ──
    const monthLabels = {{ monthLabels|json_encode|raw }};
    const monthlyTotals = {{ monthlyTotals|json_encode|raw }};

    const revenueData = monthlyTotals.map(m => m.revenue || 0);
    const profitData  = monthlyTotals.map(m => m.profit || 0);

    const ctx = document.getElementById('aggregateChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: monthLabels,
            datasets: [
                {
                    label: 'Jumlah Hasil (RM)',
                    data: revenueData,
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.08)',
                    borderWidth: 3,
                    pointRadius: 5,
                    pointBackgroundColor: '#667eea',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    tension: 0.3,
                    fill: true
                },
                {
                    label: 'Jumlah Keuntungan (RM)',
                    data: profitData,
                    borderColor: '#10b981',
                    backgroundColor: 'rgba(16, 185, 129, 0.08)',
                    borderWidth: 3,
                    pointRadius: 5,
                    pointBackgroundColor: '#10b981',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    tension: 0.3,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        padding: 20,
                        font: { size: 13, weight: '500' }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(31, 41, 55, 0.95)',
                    titleFont: { size: 13, weight: '600' },
                    bodyFont: { size: 12 },
                    padding: 12,
                    cornerRadius: 8,
                    callbacks: {
                        label: function(context) {
                            let val = context.parsed.y || 0;
                            return context.dataset.label + ': RM ' + val.toLocaleString('ms-MY', {minimumFractionDigits: 0, maximumFractionDigits: 0});
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: { font: { size: 12 } }
                },
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0,0,0,0.05)' },
                    ticks: {
                        font: { size: 12 },
                        callback: function(value) {
                            if (value >= 1000000) return 'RM ' + (value / 1000000).toFixed(1) + 'M';
                            if (value >= 1000) return 'RM ' + (value / 1000).toFixed(0) + 'K';
                            return 'RM ' + value;
                        }
                    }
                }
            }
        }
    });

    // ── Search / Filter / Pagination ──
    const searchInput = document.getElementById('searchInput');
    const rowsPerPageEl = document.getElementById('rowsPerPage');
    const allRows = Array.from(document.querySelectorAll('#tableBody .data-row'));
    let filteredRows = allRows.slice();
    let currentPage = 1;
    let pageSize = 50;

    function applyFilter() {
        const term = (searchInput.value || '').toLowerCase().trim();
        filteredRows = allRows.filter(function(row) {
            if (!term) return true;
            const name = row.getAttribute('data-name') || '';
            const biz  = row.getAttribute('data-business') || '';
            const coach = row.getAttribute('data-coach') || '';
            return name.includes(term) || biz.includes(term) || coach.includes(term);
        });
        currentPage = 1;
        renderPage();
    }

    function renderPage() {
        allRows.forEach(function(r) { r.style.display = 'none'; });
        const total = filteredRows.length;
        const ps = pageSize === 'all' ? total : pageSize;
        const totalPages = ps > 0 ? Math.max(1, Math.ceil(total / ps)) : 1;
        if (currentPage > totalPages) currentPage = totalPages;
        const start = (currentPage - 1) * ps;
        const end = ps === total || pageSize === 'all' ? total : start + ps;
        const visible = filteredRows.slice(start, end);
        visible.forEach(function(r) { r.style.display = ''; });

        const info = document.getElementById('paginationInfo');
        if (total === 0) {
            info.textContent = 'Tiada rekod ditemui';
        } else {
            info.textContent = 'Memaparkan ' + (start + 1) + '–' + Math.min(end, total) + ' daripada ' + total + ' rekod';
        }

        const controls = document.getElementById('paginationControls');
        controls.innerHTML = '';
        if (pageSize === 'all' || totalPages <= 1) return;

        const btnStyle = 'padding:6px 10px; border:1px solid #e5e7eb; background:white; border-radius:6px; cursor:pointer; font-size:13px;';
        const activeStyle = btnStyle + ' background:#667eea; color:white; border-color:#667eea;';

        const mkBtn = (label, page, disabled, active) => {
            const b = document.createElement('button');
            b.textContent = label;
            b.style.cssText = active ? activeStyle : btnStyle;
            if (disabled) { b.disabled = true; b.style.opacity = '0.5'; b.style.cursor = 'not-allowed'; }
            b.addEventListener('click', function() {
                if (disabled || active) return;
                currentPage = page;
                renderPage();
            });
            return b;
        };

        controls.appendChild(mkBtn('‹ Sebelumnya', currentPage - 1, currentPage === 1, false));

        // Page numbers (max 7 visible)
        const maxVisible = 7;
        let startPg = Math.max(1, currentPage - 3);
        let endPg = Math.min(totalPages, startPg + maxVisible - 1);
        if (endPg - startPg < maxVisible - 1) startPg = Math.max(1, endPg - maxVisible + 1);
        for (let i = startPg; i <= endPg; i++) {
            controls.appendChild(mkBtn(String(i), i, false, i === currentPage));
        }

        controls.appendChild(mkBtn('Seterusnya ›', currentPage + 1, currentPage === totalPages, false));
    }

    searchInput.addEventListener('input', applyFilter);
    rowsPerPageEl.addEventListener('change', function() {
        pageSize = this.value === 'all' ? 'all' : parseInt(this.value, 10);
        currentPage = 1;
        renderPage();
    });

    // ── Sortable Table ──
    const table = document.getElementById('comparisonTable');
    const headers = table.querySelectorAll('thead th[data-sort]');
    let currentSort = { key: null, dir: 'asc' };

    headers.forEach(function(th) {
        th.addEventListener('click', function() {
            const key = this.getAttribute('data-sort');
            let dir = 'asc';
            if (currentSort.key === key && currentSort.dir === 'asc') {
                dir = 'desc';
            }
            currentSort = { key: key, dir: dir };

            // Update header classes
            headers.forEach(function(h) {
                h.classList.remove('sort-asc', 'sort-desc');
            });
            this.classList.add(dir === 'asc' ? 'sort-asc' : 'sort-desc');

            // Sort rows
            const tbody = document.getElementById('tableBody');
            const rowsArr = Array.from(tbody.querySelectorAll('.data-row'));

            rowsArr.sort(function(a, b) {
                let valA, valB;

                if (key === 'name') {
                    valA = a.getAttribute('data-name') || '';
                    valB = b.getAttribute('data-name') || '';
                    return dir === 'asc' ? valA.localeCompare(valB) : valB.localeCompare(valA);
                } else if (key === 'coach') {
                    valA = a.getAttribute('data-coach') || '';
                    valB = b.getAttribute('data-coach') || '';
                    return dir === 'asc' ? valA.localeCompare(valB) : valB.localeCompare(valA);
                } else if (key === 'trend') {
                    const order = { 'up': 3, 'flat': 2, 'down': 1, 'none': 0 };
                    valA = order[a.getAttribute('data-trend')] || 0;
                    valB = order[b.getAttribute('data-trend')] || 0;
                    return dir === 'asc' ? valA - valB : valB - valA;
                } else if (key === 'change') {
                    valA = a.getAttribute('data-change');
                    valB = b.getAttribute('data-change');
                    valA = valA !== '' ? parseFloat(valA) : (dir === 'asc' ? Infinity : -Infinity);
                    valB = valB !== '' ? parseFloat(valB) : (dir === 'asc' ? Infinity : -Infinity);
                    return dir === 'asc' ? valA - valB : valB - valA;
                } else if (key === 'counts') {
                    valA = parseFloat(a.getAttribute('data-counts')) || 0;
                    valB = parseFloat(b.getAttribute('data-counts')) || 0;
                    return dir === 'asc' ? valA - valB : valB - valA;
                } else if (key.startsWith('month-')) {
                    valA = parseFloat(a.getAttribute('data-' + key)) || 0;
                    valB = parseFloat(b.getAttribute('data-' + key)) || 0;
                    return dir === 'asc' ? valA - valB : valB - valA;
                }
                return 0;
            });

            rowsArr.forEach(function(row) {
                tbody.appendChild(row);
            });

            // Refresh filteredRows order to match new DOM order, then re-render page
            filteredRows = allRows.filter(function(r) { return filteredRows.indexOf(r) !== -1; });
            filteredRows.sort(function(a, b) {
                return rowsArr.indexOf(a) - rowsArr.indexOf(b);
            });
            renderPage();
        });
    });

    // Initial render
    renderPage();

});
</script>
{% endblock %}
