<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kharma_Radar - Over-Watch Dashboard</title>

    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@0.294.0"></script>

    <!-- Leaflet Configuration -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&display=swap');

        :root {
            --bg-deep: #020617;
            --bg-panel: rgba(15, 23, 42, 0.8);
            --border: rgba(51, 65, 85, 0.4);
            --accent: #10b981;
            --accent-glow: rgba(16, 185, 129, 0.3);
            --text-main: #e2e8f0;
            --text-dim: #94a3b8;
            --danger: #ef4444;
            --danger-glow: rgba(239, 68, 68, 0.4);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'JetBrains Mono', monospace;
            background-color: var(--bg-deep);
            color: var(--text-main);
            min-height: screen;
            display: flex;
            flex-direction: column;
            overflow-x: hidden;
            padding: 1.5rem;
            gap: 1.5rem;
        }

        /* Glassmorphism Classes */
        .glass-panel {
            background: var(--bg-panel);
            backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            border-radius: 0.75rem;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1.25rem 2rem;
        }

        .brand h1 {
            font-size: 1.5rem;
            letter-spacing: 0.2em;
            font-weight: 700;
        }

        .brand h1 span {
            color: var(--accent);
        }

        .stats-grid {
            display: flex;
            gap: 2.5rem;
        }

        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.25rem;
        }

        .stat-label {
            font-size: 0.65rem;
            letter-spacing: 0.1em;
            color: var(--text-dim);
            text-transform: uppercase;
        }

        .stat-value {
            font-weight: 700;
            font-size: 1rem;
        }

        main {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1.5rem;
        }

        /* Radar Table Section */
        .dashboard-container {
            display: flex;
            flex-direction: column;
            min-height: 500px;
        }

        .panel-header {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(30, 41, 59, 0.3);
            border-top-left-radius: 0.75rem;
            border-top-right-radius: 0.75rem;
        }

        .panel-title {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-size: 0.8rem;
            letter-spacing: 0.1em;
            color: var(--text-main);
            font-weight: 700;
        }

        .search-box {
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            padding: 0.5rem 1rem;
            color: white;
            font-family: inherit;
            font-size: 0.8rem;
            width: 250px;
        }

        .search-box:focus {
            outline: none;
            border-color: var(--accent);
        }

        .table-scroll {
            flex: 1;
            overflow: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            text-align: left;
            font-size: 0.85rem;
        }

        thead {
            position: sticky;
            top: 0;
            background: #0f172a;
            z-index: 10;
        }

        th {
            padding: 1rem 1.5rem;
            color: var(--text-dim);
            font-weight: 700;
            text-transform: uppercase;
            font-size: 0.7rem;
            letter-spacing: 0.05em;
        }

        td {
            padding: 0.85rem 1.5rem;
            border-bottom: 1px solid rgba(51, 65, 85, 0.2);
        }

        .row-hover:hover {
            background: rgba(16, 185, 129, 0.05);
        }

        .threat-row {
            background: rgba(239, 68, 68, 0.05);
            border-left: 3px solid var(--danger);
        }

        .threat-row:hover {
            background: rgba(239, 68, 68, 0.1);
        }

        /* Marker & Badges */
        .status-badge {
            padding: 0.25rem 0.65rem;
            border-radius: 0.25rem;
            font-size: 0.7rem;
            font-weight: 700;
            background: #1e293b;
            border: 1px solid var(--border);
        }

        .status-malware {
            color: var(--danger);
            border-color: rgba(239, 68, 68, 0.3);
            background: rgba(239, 68, 68, 0.1);
            animation: pulse-red 2s infinite;
        }

        .status-community {
            color: #fbbf24;
            border-color: rgba(251, 191, 36, 0.3);
            background: rgba(251, 191, 36, 0.1);
        }

        .shield-active {
            border: 1px solid #6366f1 !important;
            box-shadow: 0 0 15px rgba(99, 102, 241, 0.4) !important;
            background: rgba(99, 102, 241, 0.05) !important;
        }

        .shield-btn-active {
            color: #6366f1 !important;
            border-color: #6366f1 !important;
            background: rgba(99, 102, 241, 0.1) !important;
        }

        .kill-btn {
            background: transparent;
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            padding: 0.4rem;
            cursor: pointer;
            color: var(--text-dim);
            transition: all 0.2s;
        }

        .kill-btn:hover {
            color: var(--danger);
            border-color: var(--danger);
            background: rgba(239, 68, 68, 0.1);
        }

        /* Map Section */
        .map-section {
            height: 350px;
            overflow: hidden;
        }

        /* DPI Terminal Section */
        .dpi-section {
            height: 250px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        #packet-stream {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
            font-size: 0.7rem;
            line-height: 1.4;
            background: rgba(0, 0, 0, 0.4);
            border-bottom-left-radius: 0.75rem;
            border-bottom-right-radius: 0.75rem;
        }

        .packet-line {
            display: flex;
            gap: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            padding: 0.2rem 0;
            white-space: nowrap;
        }

        .packet-time {
            color: var(--text-dim);
            min-width: 65px;
        }

        .packet-src-dst {
            color: #60a5fa;
            min-width: 200px;
        }

        .packet-proto {
            color: var(--accent);
            font-weight: bold;
            min-width: 50px;
        }

        .packet-info {
            color: var(--text-main);
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .packet-alert {
            color: var(--danger);
            font-weight: bold;
        }

        #radar-map {
            width: 100%;
            height: 100%;
            background: var(--bg-deep);
        }

        /* Leaflet Dark Theme */
        .leaflet-container {
            background: var(--bg-deep) !important;
        }

        .leaflet-layer,
        .leaflet-control-zoom-in,
        .leaflet-control-zoom-out,
        .leaflet-control-attribution {
            filter: invert(100%) hue-rotate(180deg) brightness(95%) contrast(90%);
        }

        /* Animations */
        @keyframes pulse-red {
            0% {
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4);
            }

            70% {
                box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
            }

            100% {
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
            }
        }

        .blink {
            animation: blinker 1.5s linear infinite;
        }

        @keyframes blinker {
            50% {
                opacity: 0.1;
            }
        }

        footer {
            text-align: center;
            font-size: 0.65rem;
            color: var(--text-dim);
            padding: 1rem;
        }

        /* Map Animations */
        .radar-beam {
            stroke-dasharray: 5, 10;
            animation: dash 5s linear infinite;
        }

        @keyframes dash {
            to {
                stroke-dashoffset: -100;
            }
        }

        .pulse-marker {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% {
                transform: scale(0.95);
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
            }

            70% {
                transform: scale(1);
                box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
            }

            100% {
                transform: scale(0.95);
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
            }
        }

        .map-legend {
            position: absolute;
            bottom: 20px;
            left: 20px;
            z-index: 1000;
            background: rgba(10, 15, 30, 0.85);
            border: 1px solid var(--border);
            padding: 10px 15px;
            border-radius: 6px;
            backdrop-filter: blur(5px);
            font-size: 0.7rem;
            color: var(--text-main);
            display: flex;
            flex-direction: column;
            gap: 8px;
            pointer-events: none;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            letter-spacing: 0.5px;
        }

        .legend-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            box-shadow: 0 0 5px currentColor;
        }

        @media (max-width: 1024px) {
            .stats-grid {
                display: none;
            }
        }
    </style>
</head>

<body>

    <header class="glass-panel">
        <div class="brand">
            <h1 class="flex items-center gap-3">
                KHARMA<span>_RADAR</span>
            </h1>
            <div style="font-size: 0.6rem; color: var(--text-dim); margin-top: 2px;">V9.0.0 ENTERPRISE ENDPOINT
                PROTECTION</div>
        </div>

        <div class="stats-grid">
            <div class="stat-item">
                <span class="stat-label">System Status</span>
                <span class="stat-value" style="color: var(--accent); display: flex; align-items: center; gap: 8px;">
                    <div
                        style="width: 8px; height: 8px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 10px var(--accent);">
                    </div>
                    ONLINE
                </span>
            </div>
            <div class="stat-item">
                <span class="stat-label">Active Sockets</span>
                <span id="conn-count" class="stat-value">0</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">VT Engine</span>
                <span id="vt-status" class="stat-value" style="color: var(--text-dim);">INIT...</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">Community Score</span>
                <span id="comm-status" class="stat-value" style="color: var(--accent);">0 FLAGS</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">Automated Shield</span>
                <span id="shield-status" class="stat-value" style="color: var(--accent); cursor: pointer;"
                    onclick="toggleBlocklist()">0 BLOCKED</span>
            </div>
            <div class="stat-item" style="cursor: pointer;" onclick="toggleGuardian()"
                title="Configure Guardian Bot Alerts">
                <span class="stat-label">Guardian Bot</span>
                <span class="stat-value" style="color: #a78bfa;">⚙ CONFIG</span>
            </div>
            <div class="stat-item" style="cursor: pointer;" onclick="toggleHistory()"
                title="View Security Event History">
                <span class="stat-label">History</span>
                <span id="history-count" class="stat-value" style="color: #34d399;">📋 VIEW</span>
            </div>
        </div>
    </header>

    <main>
        <!-- Table Area -->
        <section class="glass-panel dashboard-container">
            <div class="panel-header">
                <div class="panel-title">
                    <i data-lucide="shield-check" style="color: var(--accent); width: 1.25rem;"></i>
                    LIVE PROCESS RADAR
                </div>
                <input type="text" id="filter-input" placeholder="Search processes, IPs, or locations..."
                    class="search-box">
            </div>

            <div class="table-scroll">
                <table>
                    <thead>
                        <tr>
                            <th>Process</th>
                            <th>PID</th>
                            <th>Remote Target</th>
                            <th>Geo-Location</th>
                            <th style="text-align: center;">VT Scan</th>
                            <th>Security Status</th>
                            <th style="text-align: right;">Action</th>
                        </tr>
                    </thead>
                    <tbody id="radar-body">
                        <!-- Polled Data -->
                    </tbody>
                </table>
            </div>
        </section>

        <!-- Map Area -->
        <section class="glass-panel map-section" style="position: relative;">
            <div class="panel-header"
                style="position: absolute; top: 0; left: 0; right: 0; z-index: 1000; background: linear-gradient(180deg, rgba(5,8,15,0.9) 0%, rgba(5,8,15,0) 100%); border-bottom: none;">
                <div class="panel-title">
                    <i data-lucide="globe" style="color: var(--accent); width: 1.25rem;"></i>
                    LIVE NETWORK TELEMETRY
                </div>
            </div>
            <div id="radar-map" style="height: 100%; border-radius: 8px;"></div>

            <!-- Map Legend -->
            <div class="map-legend">
                <div class="legend-item" style="color: #10b981;">
                    <div class="legend-dot" style="background:#10b981;"></div> SECURE CONNECTION
                </div>
                <div class="legend-item" style="color: #f59e0b;">
                    <div class="legend-dot" style="background:#f59e0b;"></div> COMMUNITY FLAGGED
                </div>
                <div class="legend-item" style="color: #6366f1;">
                    <div class="legend-dot" style="background:#6366f1;"></div> BLOCKED / SHIELDED
                </div>
                <div class="legend-item" style="color: #ef4444;">
                    <div class="legend-dot pulse-marker" style="background:#ef4444; width:8px; height:8px;"></div>
                    ACTIVE THREAT (MALWARE)
                </div>
            </div>
        </section>

        <!-- DPI Terminal Area -->
        <section class="glass-panel dpi-section">
            <div class="panel-header">
                <div class="panel-title">
                    <i data-lucide="terminal" style="color: var(--accent); width: 1.25rem;"></i>
                    DEEP PACKET INSPECTION (REAL-TIME STREAM)
                </div>
                <div style="font-size: 0.65rem; color: var(--text-dim);">SNIFFER: ACTIVE | BUFFER: 50/50</div>
            </div>
            <div id="packet-stream">
                <!-- Packets injected here -->
            </div>
        </section>

        <!-- Blocklist Management Panel -->
        <section id="shield-panel" class="glass-panel" style="margin-top: 1.5rem; display: none;">
            <div class="panel-header">
                <div class="panel-title">
                    <i data-lucide="shield" style="color: #6366f1; width: 1.25rem;"></i>
                    ACTIVE FIREWALL BLOCKLIST
                </div>
                <button class="kill-btn" onclick="toggleBlocklist()">CLOSE</button>
            </div>
            <div id="blocklist-content" style="padding: 1rem; color: var(--text-dim); font-size: 0.8rem;">
                <!-- Blocked IPs list -->
            </div>
        </section>

        <!-- Guardian Bot Settings Panel -->
        <section id="guardian-panel" class="glass-panel" style="margin-top: 1.5rem; display: none;">
            <div class="panel-header">
                <div class="panel-title">
                    <i data-lucide="bot" style="color: #a78bfa; width: 1.25rem;"></i>
                    GUARDIAN BOT — EXTERNAL ALERTING
                </div>
                <button class="kill-btn" onclick="toggleGuardian()">CLOSE</button>
            </div>
            <div style="padding: 1.5rem; display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                <div>
                    <label
                        style="display: block; font-size: 0.7rem; color: var(--text-dim); margin-bottom: 0.3rem; font-weight: 600;">TELEGRAM
                        BOT TOKEN</label>
                    <input type="text" id="tg-token" placeholder="e.g. 1234567890:ABCdef..."
                        style="width: 100%; background: rgba(0,0,0,0.4); border: 1px solid var(--border); color: var(--text-main); padding: 0.5rem 0.75rem; border-radius: 6px; font-size: 0.8rem;">
                </div>
                <div>
                    <label
                        style="display: block; font-size: 0.7rem; color: var(--text-dim); margin-bottom: 0.3rem; font-weight: 600;">TELEGRAM
                        CHAT ID</label>
                    <input type="text" id="tg-chat-id" placeholder="e.g. -1001234567890"
                        style="width: 100%; background: rgba(0,0,0,0.4); border: 1px solid var(--border); color: var(--text-main); padding: 0.5rem 0.75rem; border-radius: 6px; font-size: 0.8rem;">
                </div>
                <div style="grid-column: 1 / -1;">
                    <label
                        style="display: block; font-size: 0.7rem; color: var(--text-dim); margin-bottom: 0.3rem; font-weight: 600;">DISCORD
                        WEBHOOK URL</label>
                    <input type="text" id="discord-webhook" placeholder="https://discord.com/api/webhooks/..."
                        style="width: 100%; background: rgba(0,0,0,0.4); border: 1px solid var(--border); color: var(--text-main); padding: 0.5rem 0.75rem; border-radius: 6px; font-size: 0.8rem;">
                </div>
                <div style="grid-column: 1 / -1; display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;">
                    <label style="display: flex; gap: 0.4rem; align-items: center; font-size: 0.8rem;"><input
                            type="checkbox" id="alert-threat" checked> Alert on Threat</label>
                    <label style="display: flex; gap: 0.4rem; align-items: center; font-size: 0.8rem;"><input
                            type="checkbox" id="alert-block" checked> Alert on Block</label>
                    <label style="display: flex; gap: 0.4rem; align-items: center; font-size: 0.8rem;"><input
                            type="checkbox" id="alert-dpi" checked> Alert on DPI</label>
                    <div style="margin-left: auto; display: flex; gap: 0.5rem;">
                        <button onclick="sendTestAlert()"
                            style="background: transparent; border: 1px solid #a78bfa; color: #a78bfa; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.8rem; font-weight: 600;">🔔
                            TEST ALERT</button>
                        <button onclick="saveGuardianSettings()"
                            style="background: linear-gradient(135deg, #6366f1, #a78bfa); border: none; color: white; padding: 0.5rem 1.5rem; border-radius: 6px; cursor: pointer; font-size: 0.8rem; font-weight: 600;">SAVE
                            & ACTIVATE</button>
                    </div>
                </div>
            </div>
        </section>

        <!-- Forensics History Panel -->
        <section id="history-panel" class="glass-panel" style="margin-top: 1.5rem; display: none;">
            <div class="panel-header">
                <div class="panel-title">
                    <i data-lucide="archive" style="color: #34d399; width: 1.25rem;"></i>
                    SECURITY EVENT HISTORY
                </div>
                <div style="display: flex; gap: 0.5rem; align-items: center;">
                    <span id="history-stats" style="font-size: 0.7rem; color: var(--text-dim);"></span>
                    <select id="history-filter" onchange="updateHistory()"
                        style="background: rgba(0,0,0,0.4); border: 1px solid var(--border); color: var(--text-main); padding: 0.3rem 0.5rem; border-radius: 4px; font-size: 0.75rem;">
                        <option value="">ALL EVENTS</option>
                        <option value="THREAT">THREATS</option>
                        <option value="BLOCKED">BLOCKS</option>
                        <option value="COMMUNITY_FLAG">COMMUNITY FLAGS</option>
                        <option value="DPI_ALERT">DPI ALERTS</option>
                    </select>
                    <a href="/api/history/export?format=csv"
                        style="background: transparent; border: 1px solid #34d399; color: #34d399; padding: 0.3rem 0.75rem; border-radius: 4px; font-size: 0.75rem; text-decoration: none; font-weight: 600;">⬇
                        CSV</a>
                    <a href="/api/history/export?format=json"
                        style="background: transparent; border: 1px solid #6366f1; color: #6366f1; padding: 0.3rem 0.75rem; border-radius: 4px; font-size: 0.75rem; text-decoration: none; font-weight: 600;">⬇
                        JSON</a>
                    <button onclick="addDemoEvents()"
                        style="background: transparent; border: 1px solid #f59e0b; color: #f59e0b; padding: 0.3rem 0.75rem; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">🧪
                        DEMO</button>
                    <button onclick="clearHistory()"
                        style="background: transparent; border: 1px solid var(--danger); color: var(--danger); padding: 0.3rem 0.75rem; border-radius: 4px; font-size: 0.75rem; cursor: pointer;">🗑
                        CLEAR</button>
                    <button class="kill-btn" onclick="toggleHistory()">CLOSE</button>
                </div>
            </div>
            <div style="overflow-x: auto;">
                <table style="width: 100%; border-collapse: collapse; font-size: 0.78rem;">
                    <thead>
                        <tr
                            style="border-bottom: 1px solid var(--border); color: var(--text-dim); font-size: 0.65rem; letter-spacing: 0.08em;">
                            <th style="padding: 0.6rem 1rem; text-align: left;">TIME</th>
                            <th style="padding: 0.6rem 1rem; text-align: left;">EVENT</th>
                            <th style="padding: 0.6rem 1rem; text-align: left;">IP</th>
                            <th style="padding: 0.6rem 1rem; text-align: left;">PROCESS</th>
                            <th style="padding: 0.6rem 1rem; text-align: left;">LOCATION</th>
                            <th style="padding: 0.6rem 1rem; text-align: left;">DETAIL</th>
                        </tr>
                    </thead>
                    <tbody id="history-body">
                        <tr>
                            <td colspan="6" style="text-align: center; padding: 2rem; color: var(--text-dim);">No events
                                recorded yet.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>
    </main>

    <footer>
        KHARMA RADAR v9.0.0 &copy; 2026 INTERNAL ENDPOINT MONITOR. ALL SENSORS ACTIVE.
    </footer>

    <script>
        var radarBody = document.getElementById('radar-body');
        var connCountElement = document.getElementById('conn-count');
        var filterInput = document.getElementById('filter-input');
        var vtStatusElement = document.getElementById('vt-status');
        var packetStream = document.getElementById('packet-stream');

        var allConnections = [];
        var lastPacketsJson = ""; // For diffing
        var map;
        var severityColors = { critical: '#ef4444', high: '#f97316', medium: '#f59e0b', info: '#6366f1' };
        var eventIcons = { THREAT: '🚨', BLOCKED: '🛡️', COMMUNITY_FLAG: '👥', DPI_ALERT: '⚠️' };
        var mapMarkers = [];

        try {
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            } else {
                console.warn("Lucide icons failed to load.");
            }
        } catch (e) {
            console.error(e);
        }

        // Map Setup
        function initMap() {
            map = L.map('radar-map', {
                zoomControl: false,
                attributionControl: false
            }).setView([20, 0], 2);

            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
        }

        // Fetch API
        async function updateRadar() {
            try {
                const response = await fetch('/api/radar');
                const json = await response.json();
                if (json.status === 'success') {
                    allConnections = json.data;
                    renderUI();
                }
            } catch (e) {
                console.error("API Leak Error:", e);
            }
        }

        function renderUI() {
            const filter = filterInput.value.toLowerCase();
            let html = "";
            let counter = 0;
            let vtActive = false;

            // Clear Markers
            mapMarkers.forEach(m => map.removeLayer(m));
            mapMarkers = [];

            allConnections.forEach(conn => {
                const searchStr = `${conn.process_name} ${conn.remote_address} ${conn.location}`.toLowerCase();
                if (filter && !searchStr.includes(filter)) return;

                counter++;
                const isThreat = conn.is_malware;
                const isCommunity = conn.is_community_flagged;
                const isShielded = conn.is_shielded;
                const rowClass = `${isThreat ? "threat-row" : "row-hover"} ${isShielded ? 'shield-active' : ''}`;

                let vtHtml = '<span style="color: var(--text-dim);">-</span>';
                if (conn.vt_total > 0) {
                    vtActive = true;
                    if (conn.vt_malicious > 0) {
                        vtHtml = `<span style="color: var(--danger); font-weight: bold;" class="blink">${conn.vt_malicious}/${conn.vt_total}</span>`;
                    } else {
                        vtHtml = `<span style="color: var(--accent);">${conn.vt_total} Checks Path</span>`;
                    }
                }

                let statusLabel = isThreat ? "THREAT DETECTED" : conn.status;
                let statusClass = isThreat ? "status-malware" : "";

                if (isCommunity && !isThreat) {
                    statusLabel = `FLAGGED (${conn.community_reports})`;
                    statusClass = "status-community";
                }

                if (isShielded) {
                    statusLabel = "SHIELDED (BLOCKED)";
                    statusClass = "status-community"; // Using yellow/orange for shield too
                }

                const rowId = `row-${conn.pid}-${conn.remote_ip.split('.').join('-')}`;
                html += `
                    <tr id="${rowId}" class="${rowClass}">
                        <td style="font-weight: 700; color: ${isThreat ? 'var(--danger)' : 'var(--accent)'}">${conn.process_name}</td>
                        <td style="color: var(--text-dim); font-size: 0.75rem;">${conn.pid}</td>
                        <td style="font-family: monospace;">${conn.remote_address}</td>
                        <td style="color: var(--text-dim); font-size: 0.75rem;">${conn.location}</td>
                        <td style="text-align: center;">${vtHtml}</td>
                        <td><span class="status-badge ${statusClass}">${statusLabel}</span></td>
                        <td style="text-align: right; display: flex; gap: 8px; justify-content: flex-end;">
                            <button class="kill-btn ${isShielded ? 'shield-btn-active' : ''}" onclick="toggleShield('${conn.remote_ip}', ${isShielded})" title="${isShielded ? 'Unblock IP' : 'Block IP via Firewall'}">
                                <i data-lucide="shield${isShielded ? '-off' : ''}" style="width: 14px; height: 14px;"></i>
                            </button>
                            <button class="kill-btn" onclick="reportIP('${conn.remote_ip}')" title="Report to Community">
                                <i data-lucide="flag" style="width: 14px; height: 14px; color: #fbbf24;"></i>
                            </button>
                            <button class="kill-btn" onclick="killPID(${conn.pid})" title="Active Defense">
                                <i data-lucide="zap" style="width: 14px; height: 14px;"></i>
                            </button>
                        </td>
                    </tr>
                `;

                // Add to Map
                if (conn.lat && conn.lon) {
                    let color = isThreat ? '#ef4444' : '#10b981';
                    if (isCommunity && !isThreat) color = '#fbbf24'; // Warning Orange
                    if (isShielded) color = '#6366f1';

                    // 1. Draw connection line from "Home" [20,0] to Target
                    const latlngs = [[20, 0], [conn.lat, conn.lon]];
                    const polyline = L.polyline(latlngs, {
                        color: color,
                        weight: isThreat ? 2 : 1,
                        opacity: 0.4,
                        className: 'radar-beam'
                    }).addTo(map);
                    mapMarkers.push(polyline);

                    // 2. Draw Node Marker
                    let iconHtml = `<div class="legend-dot" style="background:${color}; box-shadow: 0 0 8px ${color};"></div>`;
                    let iconSize = [8, 8];
                    let iconAnchor = [4, 4];

                    if (isThreat) {
                        iconHtml = `<div class="pulse-marker" style="background:${color};"></div>`;
                        iconSize = [12, 12];
                        iconAnchor = [6, 6];
                    }

                    const customIcon = L.divIcon({
                        className: 'custom-div-icon',
                        html: iconHtml,
                        iconSize: iconSize,
                        iconAnchor: iconAnchor
                    });

                    const marker = L.marker([conn.lat, conn.lon], { icon: customIcon }).addTo(map);

                    if (isThreat) marker.bindPopup(`<b style="color: red;">MALWARE: ${conn.process_name}</b>`);
                    if (isCommunity && !isThreat) marker.bindPopup(`<b>COMMUNITY FLAG: ${conn.remote_ip}</b><br>Reports: ${conn.community_reports}`);
                    if (isShielded) marker.bindPopup(`<b style="color: #6366f1;">SHIELDED: ${conn.remote_ip}</b>`);

                    marker.on('click', () => {
                        const rowEl = document.getElementById(rowId);
                        if (rowEl) {
                            rowEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
                            rowEl.style.transition = 'background-color 0.3s';
                            rowEl.style.backgroundColor = 'rgba(99, 102, 241, 0.4)';
                            setTimeout(() => { rowEl.style.backgroundColor = ''; }, 2000);
                        }
                    });

                    mapMarkers.push(marker);
                }
            });

            radarBody.innerHTML = html || '<tr><td colspan="7" style="text-align:center; padding: 3rem; color: var(--text-dim);">No active external connections detected. Monitoring sensors idle...</td></tr>';
            connCountElement.innerText = counter;
            vtStatusElement.innerText = vtActive ? "LINKED" : "STANDBY";
            vtStatusElement.style.color = vtActive ? "var(--accent)" : "var(--text-dim)";

            // Update Community Flag count
            const flaggedCount = allConnections.filter(c => c.is_community_flagged).length;
            document.getElementById('comm-status').innerText = `${flaggedCount} FLAGS`;
            document.getElementById('comm-status').style.color = flaggedCount > 0 ? '#fbbf24' : 'var(--accent)';

            // Update Shield count
            const shieldedCount = allConnections.filter(c => c.is_shielded).length;
            document.getElementById('shield-status').innerText = `${shieldedCount} BLOCKED`;
            document.getElementById('shield-status').style.color = shieldedCount > 0 ? '#6366f1' : 'var(--accent)';
            try { if (typeof lucide !== 'undefined') lucide.createIcons(); } catch (e) { }
        }

        async function reportIP(ip) {
            if (!confirm(`CONFIRM COMMUNITY REPORT:\nDo you want to flag IP ${ip} as malicious?`)) return;

            try {
                const res = await fetch('/api/report', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ ip: ip, reason: "Manual UI Flag" })
                });
                const data = await res.json();
                alert(data.message);
                updateRadar();
            } catch (e) {
                alert("Report failed.");
            }
        }

        async function killPID(pid) {
            if (!confirm("COMMAND CONFIRMATION: Terminate and isolate process " + pid + "?")) return;
            const res = await fetch(`/api/kill/${pid}`, { method: 'DELETE' });
            const data = await res.json();
            alert(data.message);
            updateRadar();
        }


        function toggleHistory() {
            const panel = document.getElementById('history-panel');
            panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
            if (panel.style.display === 'block') updateHistory();
        }

        async function updateHistory() {
            var SC = { critical: '#ef4444', high: '#f97316', medium: '#f59e0b', info: '#6366f1' };
            var EI = { THREAT: '🚨', BLOCKED: '🛡️', COMMUNITY_FLAG: '👥', DPI_ALERT: '⚠️' };
            var tbody = document.getElementById('history-body');
            var statsEl = document.getElementById('history-stats');
            var countEl = document.getElementById('history-count');
            if (!tbody) { console.error('[History] Cannot find #history-body element'); return; }

            var filterEl = document.getElementById('history-filter');
            var filter = filterEl ? filterEl.value : '';
            var url = '/api/history' + (filter ? '?type=' + filter : '') + '?_=' + Date.now();

            tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:1rem;color:#6366f1;">⏳ Loading...</td></tr>';
            try {
                var res = await fetch(url);
                var json = await res.json();
                if (json.status !== 'success') {
                    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:1rem;color:#ef4444;">API error: ' + (json.message || 'Unknown') + '</td></tr>';
                    return;
                }
                var events = json.data;
                var stats = json.stats || {};
                var statsStr = Object.keys(stats).map(function (k) { return (EI[k] || '•') + ' ' + k + ': ' + stats[k]; }).join(' | ');
                if (statsEl) statsEl.textContent = statsStr;
                if (countEl) countEl.textContent = '📋 ' + events.length + ' EVENTS';
                if (events.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:2rem;color:var(--text-dim);">No events recorded yet.</td></tr>';
                    return;
                }
                var html = '';
                for (var i = 0; i < events.length; i++) {
                    var ev = events[i];
                    var color = SC[ev.severity] || '#6366f1';
                    var icon = EI[ev.event_type] || '•';
                    html += '<tr style="border-bottom:1px solid rgba(255,255,255,0.04);">'
                        + '<td style="padding:0.6rem 1rem;color:var(--text-dim);font-size:0.7rem;">' + (ev.timestamp || '—') + '</td>'
                        + '<td style="padding:0.6rem 1rem;"><span style="background:' + color + '22;color:' + color + ';padding:2px 8px;border-radius:4px;font-size:0.7rem;font-weight:700;">' + icon + ' ' + ev.event_type + '</span></td>'
                        + '<td style="padding:0.6rem 1rem;font-family:monospace;color:' + color + ';">' + (ev.ip || '—') + '</td>'
                        + '<td style="padding:0.6rem 1rem;color:var(--text-main);">' + (ev.process || '—') + '</td>'
                        + '<td style="padding:0.6rem 1rem;color:var(--text-dim);">' + (ev.location || '—') + '</td>'
                        + '<td style="padding:0.6rem 1rem;color:var(--text-dim);font-size:0.75rem;">' + (ev.detail || '—') + '</td>'
                        + '</tr>';
                }
                tbody.innerHTML = html;
            } catch (e) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:1rem;color:#ef4444;">JS Error: ' + e.message + '</td></tr>';
            }
        }

        async function clearHistory() {
            if (!confirm("Clear all security event history? This cannot be undone.")) return;
            const res = await fetch('/api/history', { method: 'DELETE' });
            const data = await res.json();
            alert(data.message);
            updateHistory();
        }

        async function toggleGuardian() {
            const panel = document.getElementById('guardian-panel');
            if (panel.style.display === 'none') {
                panel.style.display = 'block';
                // Load existing settings
                const res = await fetch('/api/settings');
                const json = await res.json();
                if (json.status === 'success') {
                    document.getElementById('tg-token').value = json.data.telegram_bot_token || '';
                    document.getElementById('tg-chat-id').value = json.data.telegram_chat_id || '';
                    document.getElementById('discord-webhook').value = json.data.discord_webhook_url || '';
                    document.getElementById('alert-threat').checked = json.data.alert_on_threat !== false;
                    document.getElementById('alert-block').checked = json.data.alert_on_block !== false;
                    document.getElementById('alert-dpi').checked = json.data.alert_on_dpi !== false;
                }
            } else {
                panel.style.display = 'none';
            }
        }

        async function saveGuardianSettings() {
            const config = {
                telegram_bot_token: document.getElementById('tg-token').value,
                telegram_chat_id: document.getElementById('tg-chat-id').value,
                discord_webhook_url: document.getElementById('discord-webhook').value,
                alert_on_threat: document.getElementById('alert-threat').checked,
                alert_on_block: document.getElementById('alert-block').checked,
                alert_on_dpi: document.getElementById('alert-dpi').checked,
            };
            const res = await fetch('/api/settings', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(config)
            });
            const data = await res.json();
            alert(data.message);
        }

        async function sendTestAlert() {
            try {
                const res = await fetch('/api/settings/test', { method: 'POST' });
                const data = await res.json();
                alert(data.message);
            } catch (e) {
                alert("Test failed. Is the server running?");
            }
        }

        async function addDemoEvents() {
            await fetch('/api/history/demo', { method: 'POST' });
            await updateHistory();
        }

        async function toggleShield(ip, currentlyBlocked) {
            const method = currentlyBlocked ? 'DELETE' : 'POST';
            const action = currentlyBlocked ? 'UNBLOCK' : 'BLOCK';
            if (!confirm(`CONFIRM FIREWALL ${action}:\nTargets: ${ip}\nReason: Malicious Activity Detected.`)) return;

            try {
                const res = await fetch('/api/shield', {
                    method: method,
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ ip: ip })
                });
                const data = await res.json();
                alert(data.message);
                updateRadar();
                updateBlocklist();
            } catch (e) {
                alert("Shield operation failed. Ensure you have Admin rights.");
            }
        }

        async function updateBlocklist() {
            try {
                const res = await fetch('/api/shield');
                const json = await res.json();
                if (json.status === 'success') {
                    const container = document.getElementById('blocklist-content');
                    if (json.data.length === 0) {
                        container.innerHTML = "No IPs represent a block condition.";
                        return;
                    }
                    let html = '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px;">';
                    json.data.forEach(ip => {
                        html += `
                            <div style="background: rgba(99, 102, 241, 0.1); border: 1px solid rgba(99, 102, 241, 0.3); padding: 5px 10px; border-radius: 4px; display: flex; justify-content: space-between; align-items: center;">
                                <span>${ip}</span>
                                <button onclick="toggleShield('${ip}', true)" style="background: none; border: none; color: var(--danger); cursor: pointer;">×</button>
                            </div>
                        `;
                    });
                    html += '</div>';
                    container.innerHTML = html;
                }
            } catch (e) { }
        }

        function toggleBlocklist() {
            const panel = document.getElementById('shield-panel');
            panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
            if (panel.style.display === 'block') updateBlocklist();
        }

        // DPI Logic: Poll every 1 second
        async function updatePackets() {
            try {
                const response = await fetch('/api/packets');
                const json = await response.json();

                // Only update if data changed
                const currentJson = JSON.stringify(json.data);
                if (currentJson === lastPacketsJson) return;
                lastPacketsJson = currentJson;

                if (json.status === 'success') {
                    let html = '';
                    json.data.reverse().forEach(pkt => {
                        const alertHtml = pkt.alert ? `<span class="packet-alert blink"> [ALERT: ${pkt.alert}]</span>` : '';
                        html += `
                            <div class="packet-line">
                                <span class="packet-time">${pkt.time}</span>
                                <span class="packet-src-dst">${pkt.src} ➔ ${pkt.dst}</span>
                                <span class="packet-proto">${pkt.proto}</span>
                                <span class="packet-info">${pkt.info}${alertHtml}</span>
                            </div>
                        `;
                    });
                    packetStream.innerHTML = html;
                }
            } catch (e) {
                console.error("DPI Stream Error:", e);
            }
        }

        try { initMap(); } catch (e) { console.error("initMap error", e); }
        try { filterInput.addEventListener('input', renderUI); } catch (e) { console.error("filter input error", e); }
        try { updateRadar(); setInterval(updateRadar, 2000); } catch (e) { console.error("radar loop error", e); }
        try { updatePackets(); setInterval(updatePackets, 1000); } catch (e) { console.error("packet loop error", e); }
    </script>
</body>

</html>