{% extends "base.html" %}
{% set active_page = "index" %}
{% block page_title %}Dashboard{% endblock %}
{% block page_sub %}<div class="topbar-sub">{{ device_count }} Geräte{{ " im Bestand" if current_user.is_authenticated else "" }}</div>{% endblock %}

{% block content %}

<div class="search-input" style="max-width:320px; margin-bottom:18px;">
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
  <input type="text" id="tileSearch" placeholder="Gerät suchen…">
</div>

{% include "_dashboard_tiles.html" %}

{% if not current_user.is_authenticated %}
<p class="text-faint mt-3" style="font-size:12px;">
  Nur Lese-Ansicht — deaktivierte Geräte werden nicht angezeigt.
  <a href="{{ url_for('login') }}" style="color:var(--accent-strong); font-weight:600;">Anmelden</a>,
  um alle Geräte zu verwalten oder einen PoE-Neustart auszulösen.
</p>
{% endif %}

{% if current_user.is_authenticated %}
<div class="modal-overlay" id="deviceModal">
  <div class="modal">
    <div class="modal-header">
      <h3 id="deviceModalTitle">Gerät</h3>
      <button type="button" class="modal-close" data-close-modal>&times;</button>
    </div>
    <div class="modal-body">
      <div class="detail-list">
        <div class="detail-row"><span class="k">IP-Adresse</span><span class="v mono" id="deviceIp">-</span></div>
        <div class="detail-row"><span class="k">Switch</span><span class="v" id="deviceSwitch">-</span></div>
        <div class="detail-row"><span class="k">Port</span><span class="v" id="devicePort">-</span></div>
        <div class="detail-row"><span class="k">Status</span><span class="v" id="deviceStatus">-</span></div>
        <div class="detail-row"><span class="k">Letzte Prüfung</span><span class="v" id="deviceChecked">-</span></div>
      </div>
    </div>
    <div class="modal-footer">
      {% if current_user.has_permission('devices.edit') %}
      <button type="button" class="btn btn-success" id="activateButton" style="display:none;">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12l5 5L20 7"/></svg>
        Aktivieren
      </button>
      {% endif %}
      {% if current_user.has_permission('devices.restart') %}
      <button type="button" class="btn btn-primary" id="restartButton" style="display:none;">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 11-3.2-6.9M21 4v5h-5"/></svg>
        Neustarten
      </button>
      {% endif %}
      <button type="button" class="btn btn-secondary" data-close-modal>Schließen</button>
    </div>
  </div>
</div>

{% if current_user.has_permission('devices.restart') %}
<div class="modal-overlay" id="restartModal">
  <div class="modal" style="max-width:400px;">
    <div class="modal-header">
      <h3 id="restartTitle">Neustart</h3>
      <button type="button" class="modal-close" data-close-modal>&times;</button>
    </div>
    <div class="modal-body">
      <p class="text-dim">Der Neustart erfolgt durch einen kurzen PoE-Reset. Das Gerät wird für wenige Sekunden vom Netzwerk getrennt.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-close-modal>Abbrechen</button>
      <button type="button" class="btn btn-primary" id="confirmRestart" style="background:var(--warning); color:#241a00;">Neustarten</button>
    </div>
  </div>
</div>
{% endif %}
{% endif %}

{% endblock %}

{% block scripts %}
<script>
document.addEventListener("DOMContentLoaded", () => {
    const isAuthenticated = {{ "true" if current_user.is_authenticated else "false" }};
    let selectedCard = null, selectedMac = null, selectedName = null;
    const restartButton = document.getElementById("restartButton");
    const activateButton = document.getElementById("activateButton");
    const searchInput = document.getElementById("tileSearch");

    let activeStatusFilter = null;
    const collapsedSections = new Set();

    function applyFilters() {
        const q = (searchInput ? searchInput.value : "").trim().toLowerCase();
        let anyVisible = false;
        document.querySelectorAll(".dash-section").forEach(section => {
            const statusMatches = !activeStatusFilter || section.dataset.status === activeStatusFilter;
            let sectionHasMatch = false;
            section.querySelectorAll(".device-card").forEach(card => {
                const match = statusMatches && card.dataset.name.toLowerCase().includes(q);
                card.classList.toggle("hidden", !match);
                if (match) sectionHasMatch = true;
            });
            section.classList.toggle("hidden", !sectionHasMatch);
            if (sectionHasMatch) anyVisible = true;
        });
        const noResults = document.getElementById("noSearchResults");
        if (noResults) noResults.classList.toggle("hidden", anyVisible || (q === "" && !activeStatusFilter));
        document.querySelectorAll(".stat-card[data-status-filter]").forEach(c => {
            const isTotal = c.dataset.statusFilter === "";
            const active = activeStatusFilter === null ? isTotal : c.dataset.statusFilter === activeStatusFilter;
            c.classList.toggle("active", active);
        });
        applyCollapseState();
    }
    if (searchInput) searchInput.addEventListener("input", applyFilters);

    function applyCollapseState() {
        document.querySelectorAll(".dash-section").forEach(section => {
            section.classList.toggle("collapsed", collapsedSections.has(section.dataset.status));
        });
    }

    function bindStatCards() {
        document.querySelectorAll(".stat-card[data-status-filter]").forEach(card => {
            card.addEventListener("click", function () {
                const key = this.dataset.statusFilter;
                activeStatusFilter = (!key || activeStatusFilter === key) ? null : key;
                applyFilters();
            });
        });
    }

    function bindSectionToggles() {
        document.querySelectorAll(".dash-section-title").forEach(title => {
            title.addEventListener("click", function () {
                const key = this.closest(".dash-section").dataset.status;
                if (collapsedSections.has(key)) collapsedSections.delete(key); else collapsedSections.add(key);
                applyCollapseState();
            });
        });
    }

    function bindDeviceCards() {
        if (!isAuthenticated) return;
        document.querySelectorAll(".device-card").forEach(card => {
            const mac = card.dataset.mac;
            const restartKey = "restart_" + mac;
            if (sessionStorage.getItem(restartKey)) {
                const pill = card.querySelector(".pill");
                if (pill && pill.innerText.trim().toLowerCase() === "online") {
                    sessionStorage.removeItem(restartKey);
                } else if (pill) {
                    pill.innerHTML = '<span class="spinner"></span> Restarting…';
                }
            }
            card.addEventListener("click", function () {
                if (sessionStorage.getItem("restart_" + this.dataset.mac)) return;
                selectedCard = this;
                selectedMac = this.dataset.mac;
                selectedName = this.dataset.name;
                const isActive = this.dataset.active != "0";
                document.getElementById("deviceModalTitle").innerText = this.dataset.name;
                document.getElementById("deviceIp").innerText = this.dataset.ip || "-";
                document.getElementById("deviceSwitch").innerText = this.dataset.switch || "-";
                document.getElementById("devicePort").innerText = this.dataset.port || "-";
                document.getElementById("deviceChecked").innerText = this.dataset.checked || "-";
                const pill = this.querySelector(".pill");
                document.getElementById("deviceStatus").innerText = pill ? pill.innerText.trim() : "-";
                if (restartButton) {
                    const hasSwitchAndPort = this.dataset.switch !== "-" && this.dataset.port !== "-";
                    restartButton.style.display = (isActive && hasSwitchAndPort) ? "" : "none";
                    restartButton.disabled = false;
                    restartButton.title = "";
                }
                if (activateButton) activateButton.style.display = isActive ? "none" : "";
                PoeUI.openModal("deviceModal");
            });
        });
    }
    bindDeviceCards();
    bindStatCards();
    bindSectionToggles();
    applyFilters();

    let refreshTimer = null;

    function scheduleNextRefresh(overrideMs) {
        if (refreshTimer) clearTimeout(refreshTimer);
        if (overrideMs) { refreshTimer = setTimeout(refreshDashboardTiles, overrideMs); return; }
        const pill = document.getElementById("global-timer-pill");
        const intervalMs = pill ? parseInt(pill.dataset.intervalMs, 10) : NaN;
        if (!intervalMs) return;
        const lastRunMs = parseInt(pill.dataset.lastRunMs, 10);
        let waitMs = intervalMs + 1500;
        if (!isNaN(lastRunMs) && lastRunMs > 0) {
            const elapsed = Date.now() - lastRunMs;
            waitMs = (intervalMs - (((elapsed % intervalMs) + intervalMs) % intervalMs)) + 1500;
        }
        refreshTimer = setTimeout(refreshDashboardTiles, waitMs);
    }

    function refreshDashboardTiles() {
        fetch("{{ url_for('dashboard_tiles') }}")
            .then(r => r.text())
            .then(html => {
                const container = document.getElementById("dashboard-tiles");
                if (!container) return;
                const temp = document.createElement("div");
                temp.innerHTML = html;
                const fresh = temp.querySelector("#dashboard-tiles");
                if (!fresh) return;
                container.replaceWith(fresh);
                const pill = document.getElementById("global-timer-pill");
                if (pill) pill.dataset.lastRunMs = fresh.dataset.lastRunMs || "";
                bindDeviceCards();
                bindStatCards();
                bindSectionToggles();
                applyFilters();
                scheduleNextRefresh();
            })
            .catch(() => scheduleNextRefresh(15000));
    }

    scheduleNextRefresh();
    document.addEventListener("poe:check-triggered", refreshDashboardTiles);

    if (!isAuthenticated) {
        return;
    }

    if (restartButton) {
        restartButton.addEventListener("click", function () {
            PoeUI.closeModal(document.getElementById("deviceModal"));
            document.getElementById("restartTitle").innerText = selectedName + " neu starten?";
            PoeUI.openModal("restartModal");
        });
    }

    const confirmRestart = document.getElementById("confirmRestart");
    if (confirmRestart) {
        confirmRestart.addEventListener("click", function () {
            const button = this;
            button.disabled = true;
            fetch("/restart/" + encodeURIComponent(selectedMac), { method: "POST" })
                .then(r => r.json())
                .then(data => {
                    button.disabled = false;
                    if (!data.success) {
                        showToast(data.message || "Neustart konnte nicht gestartet werden.", "danger");
                        return;
                    }
                    PoeUI.closeModal(document.getElementById("restartModal"));
                    PoeUI.closeModal(document.getElementById("deviceModal"));
                    sessionStorage.setItem("restart_" + selectedMac, "1");
                    const pill = selectedCard.querySelector(".pill");
                    if (pill) pill.innerHTML = '<span class="spinner"></span> Restarting…';
                    showToast(`Neustart von ${data.device} gestartet.`, "success");
                })
                .catch(err => { button.disabled = false; showToast("Fehler beim Starten des Neustarts.", "danger"); });
        });
    }

    if (activateButton) {
        activateButton.addEventListener("click", function () {
            const button = this;
            button.disabled = true;
            fetch("/devices/toggle/" + encodeURIComponent(selectedMac), { method: "POST" })
                .then(r => r.json())
                .then(data => {
                    button.disabled = false;
                    if (!data.success) {
                        showToast(data.msg || "Aktivieren fehlgeschlagen.", "danger");
                        return;
                    }
                    PoeUI.closeModal(document.getElementById("deviceModal"));
                    showToast(data.msg, "success");
                    refreshDashboardTiles();
                })
                .catch(() => { button.disabled = false; showToast("Fehler beim Aktivieren.", "danger"); });
        });
    }
});
</script>
{% endblock %}
