{% extends "base.html" %}
{% block title_suffix %} - Vulnerabilities{% endblock %}
{% block content %}
<h2>Vulnerabilities</h2>
<div class="filter-toggle vulns-filters">
    <div class="filter-checkboxes">
        <label class="filter-chip">
            <input type="checkbox" id="vulns-hide-resolved" onchange="applyVulnFilters()" checked>
            Hide resolved
        </label>
        <label class="filter-chip">
            <input type="checkbox" id="vulns-hide-fixed" onchange="applyVulnFilters()">
            Hide fixed in branch
        </label>
    </div>
    <span class="filter-sep"></span>
    <button class="outline filter-sev" data-sev="critical" onclick="toggleSev(this)">Critical</button>
    <button class="outline filter-sev" data-sev="high" onclick="toggleSev(this)">High</button>
    <button class="outline filter-sev" data-sev="medium" onclick="toggleSev(this)">Medium</button>
    <button class="outline filter-sev" data-sev="low" onclick="toggleSev(this)">Low</button>
</div>
<div id="vulns-content"
     hx-get="/fragment/vulns"
     hx-trigger="load, do-refresh, every 10s"
     hx-swap="innerHTML"
>
<p class="htmx-indicator-inline" aria-busy="true">Loading from cache…</p>
</div>
<script>
function getVulnFilter() {
    var parts = [];
    var hideResolved = document.getElementById("vulns-hide-resolved");
    if (hideResolved && hideResolved.checked) parts.push("active");
    var hideFixed = document.getElementById("vulns-hide-fixed");
    if (hideFixed && hideFixed.checked) parts.push("hide-fixed");
    document.querySelectorAll(".filter-sev.filter-active").forEach(function(btn) {
        parts.push(btn.dataset.sev);
    });
    return parts.length ? parts.join(",") : "all";
}
window.getVulnFilter = getVulnFilter;

function toggleSev(btn) {
    btn.classList.toggle("filter-active");
    applyVulnFilters();
}

function applyVulnFilters() {
    window.tableSorted = false;
    var filter = getVulnFilter();
    localStorage.setItem("vulns_filter", filter);
    htmx.ajax("GET", "/fragment/vulns?filter=" + encodeURIComponent(filter), {target: "#vulns-content", swap: "innerHTML"});
}

// Restore filters from localStorage
(function() {
    var saved = localStorage.getItem("vulns_filter");
    if (!saved) return;
    var parts = saved.split(",");
    var hideResolved = document.getElementById("vulns-hide-resolved");
    if (hideResolved) hideResolved.checked = parts.indexOf("active") !== -1;
    var hideFixed = document.getElementById("vulns-hide-fixed");
    if (hideFixed) hideFixed.checked = parts.indexOf("hide-fixed") !== -1;
    document.querySelectorAll(".filter-sev").forEach(function(btn) {
        btn.classList.toggle("filter-active", parts.indexOf(btn.dataset.sev) !== -1);
    });
})();
</script>
{% endblock %}
