@extends('layout.app')

@section('content')
<div id="diag-app">
    {{-- Header --}}
    <div class="diag-header">
        <div class="d-flex align-items-center justify-content-between flex-wrap" style="gap:12px;">
            <div class="d-flex align-items-center" style="gap:16px;">
                <div class="diag-icon-box">
                    <i class="fa-solid fa-satellite-dish"></i>
                </div>
                <div>
                    <h2 class="diag-title">Network Diagnostic</h2>
                    <div class="diag-subtitle">
                        <span class="diag-chip"><i class="fa-solid fa-server"></i> {{ $nas->shortname }}</span>
                        <span class="diag-chip"><i class="fa-solid fa-network-wired"></i> {{ $nas->nasname }}</span>
                        <span class="diag-chip" id="diag-time"><i class="fa-regular fa-clock"></i> --</span>
                    </div>
                </div>
            </div>
            <div class="d-flex align-items-center" style="gap:10px;">
                <span id="diag-global-status" class="diag-status-badge diag-status-scanning">
                    <span class="diag-pulse"></span> Initializing...
                </span>
                <button id="btn-rerun" class="diag-btn-rerun" onclick="runDiagnostics()" disabled>
                    <i class="fa-solid fa-arrows-rotate"></i> Re-run All
                </button>
                <a href="{{ route('mikrotiks.index') }}" class="diag-btn-back">
                    <i class="fa-solid fa-arrow-left"></i> Back
                </a>
            </div>
        </div>
    </div>

    {{-- Quality Score Hero --}}
    <div class="diag-quality-hero" id="card-quality">
        <div class="diag-quality-inner">
            <div class="diag-quality-gauge-wrap">
                <svg class="diag-gauge" viewBox="0 0 200 120" id="quality-gauge-svg">
                    <defs>
                        <linearGradient id="gaugeGrad" x1="0%" y1="0%" x2="100%" y2="0%">
                            <stop offset="0%" style="stop-color:#ef4444"/>
                            <stop offset="25%" style="stop-color:#f59e0b"/>
                            <stop offset="50%" style="stop-color:#eab308"/>
                            <stop offset="75%" style="stop-color:#22c55e"/>
                            <stop offset="100%" style="stop-color:#06b6d4"/>
                        </linearGradient>
                    </defs>
                    <path d="M 20 100 A 80 80 0 0 1 180 100" fill="none" stroke="#1e293b" stroke-width="12" stroke-linecap="round"/>
                    <path d="M 20 100 A 80 80 0 0 1 180 100" fill="none" stroke="url(#gaugeGrad)" stroke-width="12" stroke-linecap="round"
                          stroke-dasharray="251.2" stroke-dashoffset="251.2" id="gauge-arc"/>
                    <text x="100" y="85" text-anchor="middle" class="diag-gauge-score" id="gauge-score">--</text>
                    <text x="100" y="108" text-anchor="middle" class="diag-gauge-label" id="gauge-label">SCANNING</text>
                </svg>
            </div>
            <div class="diag-quality-factors" id="quality-factors">
                <div class="diag-factor">
                    <div class="diag-factor-label">Latency</div>
                    <div class="diag-factor-value" id="qf-latency">--</div>
                </div>
                <div class="diag-factor">
                    <div class="diag-factor-label">Packet Loss</div>
                    <div class="diag-factor-value" id="qf-loss">--</div>
                </div>
                <div class="diag-factor">
                    <div class="diag-factor-label">Jitter</div>
                    <div class="diag-factor-value" id="qf-jitter">--</div>
                </div>
            </div>
        </div>
    </div>

    {{-- Diagnostic Grid --}}
    <div class="diag-grid">

        {{-- Ping Card --}}
        <div class="diag-card" id="card-ping">
            <div class="diag-card-header">
                <div class="diag-card-icon" style="background:rgba(6,182,212,0.15);color:#22d3ee;">
                    <i class="fa-solid fa-signal"></i>
                </div>
                <div>
                    <div class="diag-card-title">ICMP Ping Analysis</div>
                    <div class="diag-card-desc">10-packet ping with latency distribution</div>
                </div>
                <span class="diag-card-status diag-card-scanning" id="status-ping"><span class="diag-pulse-sm"></span></span>
            </div>
            <div class="diag-card-body">
                <div class="diag-loading" id="loading-ping">
                    <div class="diag-scanner-line"></div>
                    <span>Sending ICMP packets...</span>
                </div>
                <div class="diag-result d-none" id="result-ping">
                    <div class="diag-ping-stats">
                        <div class="diag-stat-box">
                            <span class="diag-stat-num" id="ping-avg">--</span>
                            <span class="diag-stat-label">Avg (ms)</span>
                        </div>
                        <div class="diag-stat-box">
                            <span class="diag-stat-num" id="ping-min">--</span>
                            <span class="diag-stat-label">Min (ms)</span>
                        </div>
                        <div class="diag-stat-box">
                            <span class="diag-stat-num" id="ping-max">--</span>
                            <span class="diag-stat-label">Max (ms)</span>
                        </div>
                        <div class="diag-stat-box">
                            <span class="diag-stat-num" id="ping-loss">--</span>
                            <span class="diag-stat-label">Loss %</span>
                        </div>
                        <div class="diag-stat-box">
                            <span class="diag-stat-num" id="ping-jitter">--</span>
                            <span class="diag-stat-label">Jitter (ms)</span>
                        </div>
                    </div>
                    <div class="diag-sparkline-wrap">
                        <canvas id="ping-chart" height="80"></canvas>
                    </div>
                    <div class="diag-ping-bar-wrap" id="ping-bars"></div>
                </div>
            </div>
        </div>

        {{-- Traceroute Card --}}
        <div class="diag-card" id="card-traceroute">
            <div class="diag-card-header">
                <div class="diag-card-icon" style="background:rgba(139,92,246,0.15);color:#a78bfa;">
                    <i class="fa-solid fa-route"></i>
                </div>
                <div>
                    <div class="diag-card-title">Traceroute</div>
                    <div class="diag-card-desc">Network path with hop-by-hop latency</div>
                </div>
                <span class="diag-card-status diag-card-scanning" id="status-traceroute"><span class="diag-pulse-sm"></span></span>
            </div>
            <div class="diag-card-body">
                <div class="diag-loading" id="loading-traceroute">
                    <div class="diag-scanner-line"></div>
                    <span>Tracing route to {{ $nas->nasname }}...</span>
                </div>
                <div class="diag-result d-none" id="result-traceroute">
                    <div class="diag-trace-table-wrap">
                        <table class="diag-trace-table">
                            <thead>
                                <tr>
                                    <th>Hop</th>
                                    <th>Host</th>
                                    <th>IP</th>
                                    <th>RTT 1</th>
                                    <th>RTT 2</th>
                                    <th>RTT 3</th>
                                </tr>
                            </thead>
                            <tbody id="trace-body"></tbody>
                        </table>
                    </div>
                    <div class="diag-trace-footer" id="trace-footer"></div>
                </div>
            </div>
        </div>

        {{-- Port Scan Card --}}
        <div class="diag-card" id="card-ports">
            <div class="diag-card-header">
                <div class="diag-card-icon" style="background:rgba(234,179,8,0.15);color:#facc15;">
                    <i class="fa-solid fa-ethernet"></i>
                </div>
                <div>
                    <div class="diag-card-title">Port Scanner</div>
                    <div class="diag-card-desc">Service availability on key ports</div>
                </div>
                <span class="diag-card-status diag-card-scanning" id="status-ports"><span class="diag-pulse-sm"></span></span>
            </div>
            <div class="diag-card-body">
                <div class="diag-loading" id="loading-ports">
                    <div class="diag-scanner-line"></div>
                    <span>Scanning ports...</span>
                </div>
                <div class="diag-result d-none" id="result-ports">
                    <div id="port-results"></div>
                </div>
            </div>
        </div>

        {{-- DNS Card --}}
        <div class="diag-card" id="card-dns">
            <div class="diag-card-header">
                <div class="diag-card-icon" style="background:rgba(34,197,94,0.15);color:#4ade80;">
                    <i class="fa-solid fa-globe"></i>
                </div>
                <div>
                    <div class="diag-card-title">DNS Resolution</div>
                    <div class="diag-card-desc">Forward & reverse DNS lookup</div>
                </div>
                <span class="diag-card-status diag-card-scanning" id="status-dns"><span class="diag-pulse-sm"></span></span>
            </div>
            <div class="diag-card-body">
                <div class="diag-loading" id="loading-dns">
                    <div class="diag-scanner-line"></div>
                    <span>Resolving DNS records...</span>
                </div>
                <div class="diag-result d-none" id="result-dns">
                    <div id="dns-results"></div>
                </div>
            </div>
        </div>

        {{-- MTU Card --}}
        <div class="diag-card" id="card-mtu">
            <div class="diag-card-header">
                <div class="diag-card-icon" style="background:rgba(251,146,60,0.15);color:#fb923c;">
                    <i class="fa-solid fa-maximize"></i>
                </div>
                <div>
                    <div class="diag-card-title">MTU Discovery</div>
                    <div class="diag-card-desc">Maximum transmission unit path test</div>
                </div>
                <span class="diag-card-status diag-card-scanning" id="status-mtu"><span class="diag-pulse-sm"></span></span>
            </div>
            <div class="diag-card-body">
                <div class="diag-loading" id="loading-mtu">
                    <div class="diag-scanner-line"></div>
                    <span>Binary search for max MTU...</span>
                </div>
                <div class="diag-result d-none" id="result-mtu">
                    <div id="mtu-results"></div>
                </div>
            </div>
        </div>

        {{-- RouterOS Health Card --}}
        <div class="diag-card" id="card-routeros">
            <div class="diag-card-header">
                <div class="diag-card-icon" style="background:rgba(236,72,153,0.15);color:#f472b6;">
                    <i class="fa-solid fa-microchip"></i>
                </div>
                <div>
                    <div class="diag-card-title">RouterOS System Health</div>
                    <div class="diag-card-desc">Device identity, resources & uptime</div>
                </div>
                <span class="diag-card-status diag-card-scanning" id="status-routeros"><span class="diag-pulse-sm"></span></span>
            </div>
            <div class="diag-card-body">
                <div class="diag-loading" id="loading-routeros">
                    <div class="diag-scanner-line"></div>
                    <span>Connecting to RouterOS API...</span>
                </div>
                <div class="diag-result d-none" id="result-routeros">
                    <div id="routeros-results"></div>
                </div>
            </div>
        </div>

    </div>
</div>


<style>
    .content-wrapper { background: #0a0e1a !important; }
    #diag-app { font-family: 'Nunito Sans', 'Source Sans Pro', -apple-system, sans-serif; max-width: 1400px; margin: 0 auto; padding: 20px 15px; }

    /* Header */
    .diag-header { background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); border: 1px solid #1e3a5f; border-radius: 16px; padding: 20px 28px; margin-bottom: 20px; position: relative; overflow: hidden; box-shadow: 0 4px 20px rgba(15,23,42,0.3); }
    .diag-header::before { content:''; position:absolute; top:0; left:0; right:0; height:2px; background: linear-gradient(90deg, transparent, #22d3ee, #a78bfa, transparent); }
    .diag-icon-box { width:52px; height:52px; border-radius:14px; background: linear-gradient(135deg, #0e7490, #0891b2); display:flex; align-items:center; justify-content:center; font-size:22px; color:#fff; box-shadow: 0 0 20px rgba(6,182,212,0.3); }
    .diag-title { color: #f1f5f9; font-size: 1.5rem; font-weight: 700; margin: 0; letter-spacing: -0.02em; }
    .diag-subtitle { display: flex; gap: 8px; margin-top: 6px; flex-wrap: wrap; }
    .diag-chip { background: rgba(30,58,95,0.6); color: #94a3b8; font-size: 0.78rem; padding: 3px 10px; border-radius: 6px; border: 1px solid #1e3a5f; font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; }
    .diag-chip i { margin-right: 4px; font-size: 0.7rem; }

    .diag-status-badge { display:inline-flex; align-items:center; gap:8px; padding:6px 14px; border-radius:20px; font-size:0.8rem; font-weight:600; letter-spacing:0.04em; }
    .diag-status-scanning { background:rgba(234,179,8,0.15); color:#facc15; border:1px solid rgba(234,179,8,0.3); }
    .diag-status-complete { background:rgba(34,197,94,0.15); color:#4ade80; border:1px solid rgba(34,197,94,0.3); }
    .diag-status-error { background:rgba(239,68,68,0.15); color:#f87171; border:1px solid rgba(239,68,68,0.3); }

    .diag-pulse { width:8px; height:8px; border-radius:50%; background:#facc15; animation: diagPulse 1.5s ease-in-out infinite; }
    .diag-pulse-sm { width:6px; height:6px; border-radius:50%; background:#facc15; animation: diagPulse 1.5s ease-in-out infinite; display:inline-block; }
    @keyframes diagPulse { 0%,100%{ opacity:1; transform:scale(1); } 50%{ opacity:0.4; transform:scale(1.4); } }

    .diag-btn-rerun { background: linear-gradient(135deg, #0e7490, #0891b2); color:#fff; border:none; padding:8px 18px; border-radius:10px; font-size:0.85rem; font-weight:600; cursor:pointer; transition:all 0.2s; display:inline-flex; align-items:center; gap:6px; }
    .diag-btn-rerun:hover:not(:disabled) { transform:translateY(-1px); box-shadow: 0 4px 15px rgba(6,182,212,0.4); }
    .diag-btn-rerun:disabled { opacity:0.5; cursor:not-allowed; }
    .diag-btn-rerun i.spin { animation: diagSpin 1s linear infinite; }
    @keyframes diagSpin { to { transform:rotate(360deg); } }
    .diag-btn-back { background: rgba(30,58,95,0.5); color:#94a3b8; border:1px solid #1e3a5f; padding:8px 18px; border-radius:10px; font-size:0.85rem; font-weight:600; cursor:pointer; transition:all 0.2s; text-decoration:none; display:inline-flex; align-items:center; gap:6px; }
    .diag-btn-back:hover { color:#e2e8f0; border-color:#334155; text-decoration:none; }

    /* Quality Hero */
    .diag-quality-hero { background: linear-gradient(135deg, #0f172a, #1a1f3a); border: 1px solid #1e3a5f; border-radius: 16px; padding: 24px 32px; margin-bottom: 20px; position:relative; overflow:hidden; box-shadow: 0 4px 20px rgba(15,23,42,0.3); }
    .diag-quality-hero::after { content:''; position:absolute; bottom:0; left:0; right:0; height:2px; background: linear-gradient(90deg, transparent, #22d3ee, transparent); }
    .diag-quality-inner { display:flex; align-items:center; justify-content:center; gap:50px; flex-wrap:wrap; }
    .diag-quality-gauge-wrap { width:200px; height:120px; }
    .diag-gauge { width:100%; height:100%; }
    .diag-gauge-score { fill:#f1f5f9; font-size:32px; font-weight:800; font-family: 'SFMono-Regular', Consolas, monospace; }
    .diag-gauge-label { fill:#64748b; font-size:11px; font-weight:700; letter-spacing:0.12em; text-transform:uppercase; }
    .diag-quality-factors { display:flex; gap:32px; }
    .diag-factor { text-align:center; }
    .diag-factor-label { color:#64748b; font-size:0.75rem; font-weight:600; text-transform:uppercase; letter-spacing:0.08em; margin-bottom:4px; }
    .diag-factor-value { font-family: 'SFMono-Regular', Consolas, monospace; font-size:0.95rem; font-weight:700; padding:4px 14px; border-radius:8px; background:rgba(30,58,95,0.5); border:1px solid #1e3a5f; color:#e2e8f0; }

    /* Grid */
    .diag-grid { display:grid; grid-template-columns:repeat(2,1fr); gap:18px; }
    @media(max-width:992px){ .diag-grid { grid-template-columns:1fr; } }

    /* Cards */
    .diag-card { background: linear-gradient(135deg, #0f172a 0%, #131b2e 100%); border:1px solid #1e3a5f; border-radius:14px; overflow:hidden; transition:all 0.3s; position:relative; box-shadow: 0 4px 15px rgba(15,23,42,0.25); }
    .diag-card::before { content:''; position:absolute; top:0; left:0; right:0; height:2px; background: linear-gradient(90deg, transparent, #1e3a5f, transparent); transition:background 0.5s; }
    .diag-card.card-success::before { background: linear-gradient(90deg, transparent, #22c55e, transparent); }
    .diag-card.card-error::before { background: linear-gradient(90deg, transparent, #ef4444, transparent); }
    .diag-card:hover { border-color:#2d4a6f; transform:translateY(-2px); box-shadow:0 8px 30px rgba(15,23,42,0.4); }

    .diag-card-header { display:flex; align-items:center; gap:12px; padding:16px 20px; border-bottom:1px solid rgba(30,58,95,0.5); }
    .diag-card-icon { width:40px; height:40px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:16px; flex-shrink:0; }
    .diag-card-title { color:#e2e8f0; font-size:0.92rem; font-weight:700; letter-spacing:-0.01em; }
    .diag-card-desc { color:#475569; font-size:0.73rem; margin-top:1px; }
    .diag-card-status { margin-left:auto; }
    .diag-card-scanning .diag-pulse-sm { background:#facc15; }
    .diag-card-ok .diag-pulse-sm { background:#4ade80; animation:none; }
    .diag-card-fail .diag-pulse-sm { background:#f87171; animation:none; }

    .diag-card-body { padding:18px 20px; min-height:120px; }

    /* Loading animation */
    .diag-loading { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:14px; min-height:100px; color:#475569; font-size:0.82rem; }
    .diag-scanner-line { width:100%; height:2px; background: linear-gradient(90deg, transparent, #22d3ee, transparent); border-radius:2px; animation: diagScan 2s ease-in-out infinite; }
    @keyframes diagScan { 0%{ opacity:0.2; transform:scaleX(0.3); } 50%{ opacity:1; transform:scaleX(1); } 100%{ opacity:0.2; transform:scaleX(0.3); } }

    /* Result sections */
    .diag-result { animation: diagFadeIn 0.5s ease-out; }
    @keyframes diagFadeIn { from { opacity:0; transform:translateY(8px); } to { opacity:1; transform:translateY(0); } }

    /* Ping stats */
    .diag-ping-stats { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:14px; }
    .diag-stat-box { flex:1; min-width:70px; text-align:center; background:rgba(30,58,95,0.35); border:1px solid #1e3a5f; border-radius:10px; padding:10px 6px; }
    .diag-stat-num { display:block; font-family:'SFMono-Regular',Consolas,monospace; font-size:1.15rem; font-weight:800; color:#22d3ee; }
    .diag-stat-label { display:block; color:#64748b; font-size:0.65rem; font-weight:600; text-transform:uppercase; letter-spacing:0.06em; margin-top:2px; }
    .diag-sparkline-wrap { margin-bottom:10px; background:rgba(30,58,95,0.2); border-radius:8px; padding:8px; }
    .diag-ping-bar-wrap { display:flex; gap:3px; align-items:flex-end; height:30px; }
    .diag-ping-bar { flex:1; border-radius:3px 3px 0 0; transition:height 0.3s; min-width:6px; position:relative; }
    .diag-ping-bar:hover::after { content:attr(data-ms); position:absolute; bottom:calc(100% + 4px); left:50%; transform:translateX(-50%); background:#1e293b; color:#e2e8f0; padding:2px 6px; border-radius:4px; font-size:0.65rem; white-space:nowrap; border:1px solid #334155; }

    /* Traceroute table */
    .diag-trace-table-wrap { max-height:320px; overflow-y:auto; border-radius:8px; }
    .diag-trace-table-wrap::-webkit-scrollbar { width:4px; }
    .diag-trace-table-wrap::-webkit-scrollbar-track { background:#0f172a; }
    .diag-trace-table-wrap::-webkit-scrollbar-thumb { background:#334155; border-radius:2px; }
    .diag-trace-table { width:100%; border-collapse:collapse; font-size:0.8rem; }
    .diag-trace-table thead th { background:rgba(30,58,95,0.5); color:#94a3b8; font-size:0.7rem; font-weight:700; text-transform:uppercase; letter-spacing:0.06em; padding:8px 10px; text-align:left; position:sticky; top:0; z-index:1; }
    .diag-trace-table tbody tr { border-bottom:1px solid rgba(30,58,95,0.3); transition:background 0.2s; }
    .diag-trace-table tbody tr:hover { background:rgba(30,58,95,0.3); }
    .diag-trace-table td { padding:7px 10px; color:#cbd5e1; font-family:'SFMono-Regular',Consolas,monospace; font-size:0.78rem; }
    .diag-trace-table .hop-num { color:#64748b; font-weight:700; text-align:center; width:40px; }
    .diag-trace-table .hop-ip { color:#22d3ee; }
    .diag-trace-table .hop-host { color:#94a3b8; max-width:180px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
    .diag-trace-table .hop-rtt { color:#a78bfa; text-align:right; }
    .diag-trace-table .hop-timeout { color:#475569; }
    .diag-trace-table .hop-target { background:rgba(34,211,238,0.06); }
    .diag-trace-footer { margin-top:10px; font-size:0.78rem; display:flex; align-items:center; gap:6px; }

    /* Port rows */
    .diag-port-row { display:flex; align-items:center; justify-content:space-between; padding:9px 14px; border-radius:8px; margin-bottom:6px; background:rgba(30,58,95,0.2); border:1px solid rgba(30,58,95,0.4); transition:all 0.2s; }
    .diag-port-row:hover { background:rgba(30,58,95,0.35); }
    .diag-port-info { display:flex; align-items:center; gap:10px; }
    .diag-port-num { font-family:'SFMono-Regular',Consolas,monospace; font-size:0.85rem; font-weight:700; color:#e2e8f0; min-width:50px; }
    .diag-port-name { color:#94a3b8; font-size:0.8rem; }
    .diag-port-badge { padding:3px 10px; border-radius:6px; font-size:0.72rem; font-weight:700; letter-spacing:0.04em; text-transform:uppercase; }
    .diag-port-open { background:rgba(34,197,94,0.15); color:#4ade80; border:1px solid rgba(34,197,94,0.3); }
    .diag-port-closed { background:rgba(239,68,68,0.1); color:#f87171; border:1px solid rgba(239,68,68,0.2); }
    .diag-port-ms { font-family:'SFMono-Regular',Consolas,monospace; font-size:0.75rem; color:#64748b; margin-left:8px; }

    /* DNS results */
    .diag-dns-row { display:flex; align-items:center; gap:12px; padding:10px 14px; border-radius:8px; margin-bottom:6px; background:rgba(30,58,95,0.2); border:1px solid rgba(30,58,95,0.4); }
    .diag-dns-type { font-size:0.7rem; font-weight:700; color:#4ade80; text-transform:uppercase; letter-spacing:0.06em; min-width:70px; }
    .diag-dns-val { font-family:'SFMono-Regular',Consolas,monospace; font-size:0.82rem; color:#e2e8f0; flex:1; }
    .diag-dns-ms { font-family:'SFMono-Regular',Consolas,monospace; font-size:0.72rem; color:#64748b; }

    /* MTU */
    .diag-mtu-display { display:flex; align-items:center; justify-content:center; flex-direction:column; gap:8px; padding:16px; }
    .diag-mtu-value { font-family:'SFMono-Regular',Consolas,monospace; font-size:2.5rem; font-weight:800; }
    .diag-mtu-label { color:#64748b; font-size:0.78rem; font-weight:600; text-transform:uppercase; letter-spacing:0.08em; }
    .diag-mtu-bar { width:100%; height:8px; background:#1e293b; border-radius:4px; overflow:hidden; margin-top:10px; }
    .diag-mtu-fill { height:100%; border-radius:4px; transition:width 1s ease-out; }

    /* RouterOS */
    .diag-ros-grid { display:grid; grid-template-columns:repeat(2,1fr); gap:8px; }
    @media(max-width:576px){ .diag-ros-grid { grid-template-columns:1fr; } }
    .diag-ros-item { background:rgba(30,58,95,0.25); border:1px solid rgba(30,58,95,0.4); border-radius:10px; padding:12px 14px; }
    .diag-ros-label { color:#64748b; font-size:0.68rem; font-weight:600; text-transform:uppercase; letter-spacing:0.06em; margin-bottom:4px; }
    .diag-ros-value { color:#e2e8f0; font-family:'SFMono-Regular',Consolas,monospace; font-size:0.88rem; font-weight:700; }
    .diag-ros-bar-wrap { margin-top:6px; }
    .diag-ros-bar-bg { width:100%; height:6px; background:#1e293b; border-radius:3px; overflow:hidden; }
    .diag-ros-bar-fill { height:100%; border-radius:3px; transition:width 1s ease-out; }
    .diag-ros-bar-label { display:flex; justify-content:space-between; margin-top:3px; font-size:0.65rem; color:#64748b; }
    .diag-ros-error { text-align:center; padding:20px; color:#f87171; }
    .diag-ros-error i { font-size:1.5rem; display:block; margin-bottom:8px; }

    /* Color helpers */
    .color-excellent { color:#22d3ee; }
    .color-good { color:#4ade80; }
    .color-fair { color:#facc15; }
    .color-poor { color:#fb923c; }
    .color-critical { color:#f87171; }

    .bg-excellent { background:rgba(34,211,238,0.15); border-color:rgba(34,211,238,0.3); }
    .bg-good { background:rgba(74,222,128,0.15); border-color:rgba(74,222,128,0.3); }
    .bg-fair { background:rgba(250,204,21,0.15); border-color:rgba(250,204,21,0.3); }
    .bg-poor { background:rgba(251,146,60,0.15); border-color:rgba(251,146,60,0.3); }
    .bg-critical { background:rgba(248,113,113,0.15); border-color:rgba(248,113,113,0.3); }
</style>
@endsection

@push('js')
<script>
const DIAG_URL = "{{ route('mikrotik.run-network-diagnostic', $nas->id) }}";
const SECTIONS = ['ping','traceroute','ports','dns','mtu','routeros'];
let diagData = null;

function runDiagnostics() {
    const btn = document.getElementById('btn-rerun');
    btn.disabled = true;
    btn.querySelector('i').classList.add('spin');

    const globalStatus = document.getElementById('diag-global-status');
    globalStatus.className = 'diag-status-badge diag-status-scanning';
    globalStatus.innerHTML = '<span class="diag-pulse"></span> Scanning...';
    document.getElementById('diag-time').innerHTML = '<i class="fa-regular fa-clock"></i> Running...';

    SECTIONS.forEach(s => {
        document.getElementById('loading-' + s).classList.remove('d-none');
        document.getElementById('result-' + s).classList.add('d-none');
        const statusEl = document.getElementById('status-' + s);
        statusEl.className = 'diag-card-status diag-card-scanning';
        statusEl.innerHTML = '<span class="diag-pulse-sm"></span>';
        document.getElementById('card-' + s).className = 'diag-card';
    });

    resetQuality();

    const startTime = Date.now();

    $.ajax({
        url: DIAG_URL,
        method: 'GET',
        dataType: 'json',
        timeout: 120000,
        success: function(data) {
            diagData = data;
            const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
            document.getElementById('diag-time').innerHTML = '<i class="fa-regular fa-clock"></i> ' + elapsed + 's';

            renderPing(data.ping);
            renderTraceroute(data.traceroute);
            renderPorts(data.ports);
            renderDns(data.dns);
            renderMtu(data.mtu);
            renderRouterOs(data.routeros);
            renderQuality(data.quality);

            globalStatus.className = 'diag-status-badge diag-status-complete';
            globalStatus.innerHTML = '<span class="diag-pulse" style="background:#4ade80;animation:none;"></span> Complete';

            btn.disabled = false;
            btn.querySelector('i').classList.remove('spin');
        },
        error: function(xhr) {
            const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
            document.getElementById('diag-time').innerHTML = '<i class="fa-regular fa-clock"></i> ' + elapsed + 's (error)';

            globalStatus.className = 'diag-status-badge diag-status-error';
            globalStatus.innerHTML = '<span class="diag-pulse" style="background:#f87171;animation:none;"></span> Error';

            SECTIONS.forEach(s => {
                document.getElementById('loading-' + s).innerHTML = '<div style="color:#f87171;"><i class="fa-solid fa-triangle-exclamation"></i> Failed to run diagnostic</div>';
            });

            btn.disabled = false;
            btn.querySelector('i').classList.remove('spin');
        }
    });
}

function showResult(section, status) {
    document.getElementById('loading-' + section).classList.add('d-none');
    document.getElementById('result-' + section).classList.remove('d-none');
    const statusEl = document.getElementById('status-' + section);
    const card = document.getElementById('card-' + section);
    if (status === 'ok') {
        statusEl.className = 'diag-card-status diag-card-ok';
        statusEl.innerHTML = '<span class="diag-pulse-sm" style="background:#4ade80;"></span>';
        card.classList.add('card-success');
    } else {
        statusEl.className = 'diag-card-status diag-card-fail';
        statusEl.innerHTML = '<span class="diag-pulse-sm" style="background:#f87171;"></span>';
        card.classList.add('card-error');
    }
}

/* ===== PING ===== */
function renderPing(d) {
    const ok = d.packets_received > 0;
    document.getElementById('ping-avg').textContent = d.rtt_avg;
    document.getElementById('ping-min').textContent = d.rtt_min;
    document.getElementById('ping-max').textContent = d.rtt_max;
    document.getElementById('ping-loss').textContent = d.loss_percent;
    document.getElementById('ping-jitter').textContent = d.rtt_stddev;

    const avgEl = document.getElementById('ping-avg');
    if (d.rtt_avg <= 30) avgEl.style.color = '#4ade80';
    else if (d.rtt_avg <= 100) avgEl.style.color = '#facc15';
    else avgEl.style.color = '#f87171';

    const lossEl = document.getElementById('ping-loss');
    if (d.loss_percent == 0) lossEl.style.color = '#4ade80';
    else if (d.loss_percent <= 5) lossEl.style.color = '#facc15';
    else lossEl.style.color = '#f87171';

    showResult('ping', ok ? 'ok' : 'fail');

    if (d.replies && d.replies.length > 0) {
        setTimeout(function() {
            drawPingChart(d.replies);
            renderPingBars(d.replies, d.rtt_max);
        }, 60);
    }
}

function drawPingChart(replies) {
    const canvas = document.getElementById('ping-chart');
    if (!canvas) return;
    const parent = canvas.parentElement;
    const w = Math.max(parent.clientWidth - 16, 200);
    const h = 80;
    canvas.width = w;
    canvas.height = h;
    canvas.style.display = 'block';
    canvas.style.background = 'transparent';
    const ctx = canvas.getContext('2d');

    const times = replies.map(r => r.time);
    const rawMin = Math.min(...times);
    const rawMax = Math.max(...times);
    const pad = Math.max((rawMax - rawMin) * 0.3, rawMax * 0.1, 0.5);
    const lo = rawMin - pad;
    const hi = rawMax + pad;
    const range = hi - lo || 1;
    const step = w / (times.length - 1 || 1);
    const calcY = (t) => h - 10 - ((t - lo) / range) * (h - 20);

    ctx.beginPath();
    ctx.moveTo(0, h);
    times.forEach((t, i) => ctx.lineTo(i * step, calcY(t)));
    ctx.lineTo(w, h);
    ctx.closePath();
    const grad = ctx.createLinearGradient(0, 0, 0, h);
    grad.addColorStop(0, 'rgba(34,211,238,0.3)');
    grad.addColorStop(1, 'rgba(34,211,238,0.02)');
    ctx.fillStyle = grad;
    ctx.fill();

    ctx.beginPath();
    times.forEach((t, i) => {
        const x = i * step;
        if (i === 0) ctx.moveTo(x, calcY(t));
        else ctx.lineTo(x, calcY(t));
    });
    ctx.strokeStyle = '#22d3ee';
    ctx.lineWidth = 2.5;
    ctx.lineJoin = 'round';
    ctx.lineCap = 'round';
    ctx.stroke();

    times.forEach((t, i) => {
        const x = i * step;
        const y = calcY(t);
        ctx.beginPath();
        ctx.arc(x, y, 4, 0, Math.PI * 2);
        ctx.fillStyle = '#22d3ee';
        ctx.fill();
        ctx.beginPath();
        ctx.arc(x, y, 2, 0, Math.PI * 2);
        ctx.fillStyle = '#0f172a';
        ctx.fill();
    });
}

function renderPingBars(replies, maxRtt) {
    const wrap = document.getElementById('ping-bars');
    wrap.innerHTML = '';
    const max = maxRtt || 1;
    replies.forEach(r => {
        const pct = Math.max((r.time / max) * 100, 5);
        let color = '#4ade80';
        if (r.time > 100) color = '#f87171';
        else if (r.time > 50) color = '#facc15';
        else if (r.time > 20) color = '#22d3ee';
        const bar = document.createElement('div');
        bar.className = 'diag-ping-bar';
        bar.style.height = pct + '%';
        bar.style.background = color;
        bar.setAttribute('data-ms', r.time + 'ms');
        wrap.appendChild(bar);
    });
}

/* ===== TRACEROUTE ===== */
function renderTraceroute(d) {
    const body = document.getElementById('trace-body');
    body.innerHTML = '';

    d.hops.forEach(hop => {
        const isTarget = hop.ip === '{{ $nas->nasname }}';
        const tr = document.createElement('tr');
        if (isTarget) tr.className = 'hop-target';

        const rttHtml = (probes) => {
            if (!probes || probes.length === 0) return '<td class="hop-timeout">*</td><td class="hop-timeout">*</td><td class="hop-timeout">*</td>';
            let html = '';
            for (let i = 0; i < 3; i++) {
                if (probes[i] !== undefined) {
                    html += '<td class="hop-rtt">' + probes[i].toFixed(1) + ' ms</td>';
                } else {
                    html += '<td class="hop-timeout">*</td>';
                }
            }
            return html;
        };

        tr.innerHTML =
            '<td class="hop-num">' + hop.hop + '</td>' +
            '<td class="hop-host">' + (hop.hostname !== hop.ip ? hop.hostname : '--') + '</td>' +
            '<td class="hop-ip">' + hop.ip + '</td>' +
            rttHtml(hop.probes);

        body.appendChild(tr);
    });

    const footer = document.getElementById('trace-footer');
    if (d.target_reached) {
        footer.innerHTML = '<span style="color:#4ade80;"><i class="fa-solid fa-check-circle"></i> Target reached in ' + d.hops.length + ' hops</span>';
    } else {
        footer.innerHTML = '<span style="color:#fb923c;"><i class="fa-solid fa-exclamation-circle"></i> Target may not have been reached (' + d.hops.length + ' hops traced)</span>';
    }

    showResult('traceroute', d.target_reached ? 'ok' : 'fail');
}

/* ===== PORTS ===== */
function renderPorts(ports) {
    const wrap = document.getElementById('port-results');
    wrap.innerHTML = '';
    let anyOpen = false;

    ports.forEach(p => {
        if (p.status === 'open') anyOpen = true;
        const row = document.createElement('div');
        row.className = 'diag-port-row';
        row.innerHTML =
            '<div class="diag-port-info">' +
                '<span class="diag-port-num">:' + p.port + '</span>' +
                '<span class="diag-port-name">' + p.name + '</span>' +
            '</div>' +
            '<div>' +
                '<span class="diag-port-badge ' + (p.status === 'open' ? 'diag-port-open' : 'diag-port-closed') + '">' +
                    (p.status === 'open' ? '<i class="fa-solid fa-lock-open"></i> Open' : '<i class="fa-solid fa-lock"></i> Closed') +
                '</span>' +
                (p.response_ms ? '<span class="diag-port-ms">' + p.response_ms + 'ms</span>' : '') +
            '</div>';
        wrap.appendChild(row);
    });

    showResult('ports', anyOpen ? 'ok' : 'fail');
}

/* ===== DNS ===== */
function renderDns(d) {
    const wrap = document.getElementById('dns-results');
    wrap.innerHTML = '';

    const addRow = (type, value, ms) => {
        const row = document.createElement('div');
        row.className = 'diag-dns-row';
        row.innerHTML =
            '<span class="diag-dns-type">' + type + '</span>' +
            '<span class="diag-dns-val">' + (value || 'N/A') + '</span>' +
            (ms !== null ? '<span class="diag-dns-ms">' + ms + 'ms</span>' : '');
        wrap.appendChild(row);
    };

    addRow('Host', d.host, null);
    if (!d.is_ip) {
        addRow('Forward (A)', d.forward_ip, d.forward_ms);
    }
    addRow('Reverse (PTR)', d.reverse_hostname || 'No PTR record', d.reverse_ms);

    if (d.dns_records && d.dns_records.length > 0) {
        d.dns_records.forEach(r => {
            addRow(r.type, r.value + ' (TTL: ' + r.ttl + ')', null);
        });
    }

    if (d.is_ip) {
        const note = document.createElement('div');
        note.style.cssText = 'margin-top:8px;font-size:0.75rem;color:#64748b;padding:0 14px;';
        note.textContent = 'Host is an IP address — forward DNS lookup not applicable.';
        wrap.appendChild(note);
    }

    if (d.ip_owner) {
        const ownerSection = document.createElement('div');
        ownerSection.style.cssText = 'margin-top:12px;padding:14px;background:rgba(34,211,238,0.06);border:1px solid rgba(34,211,238,0.15);border-radius:10px;';
        let ownerHtml = '<div style="font-size:0.72rem;font-weight:700;color:#22d3ee;text-transform:uppercase;letter-spacing:0.06em;margin-bottom:8px;"><i class="fa-solid fa-building"></i> IP Owner Information</div>';
        const fields = [
            { label: 'Organization', value: d.ip_owner.org_name },
            { label: 'Network Name', value: d.ip_owner.net_name },
            { label: 'Country', value: d.ip_owner.country },
            { label: 'Network Range', value: d.ip_owner.network_range },
            { label: 'Description', value: d.ip_owner.description },
        ];
        fields.forEach(f => {
            if (f.value) {
                ownerHtml += '<div style="display:flex;align-items:center;gap:8px;padding:4px 0;border-bottom:1px solid rgba(30,58,95,0.3);">' +
                    '<span style="font-size:0.7rem;font-weight:600;color:#64748b;min-width:100px;">' + f.label + '</span>' +
                    '<span style="font-family:SFMono-Regular,Consolas,monospace;font-size:0.8rem;color:#e2e8f0;font-weight:600;">' + f.value + '</span>' +
                '</div>';
            }
        });
        ownerSection.innerHTML = ownerHtml;
        wrap.appendChild(ownerSection);
    }

    showResult('dns', 'ok');
}

/* ===== MTU ===== */
function renderMtu(d) {
    const wrap = document.getElementById('mtu-results');
    const pct = Math.min((d.max_mtu / 1500) * 100, 100);

    let colorClass = 'color-good';
    let barColor = '#16a34a';
    let statusText = 'Optimal';
    if (d.status === 'optimal') { colorClass = 'color-excellent'; barColor = '#22d3ee'; statusText = 'Optimal — No fragmentation'; }
    else if (d.status === 'ok') { colorClass = 'color-good'; barColor = '#4ade80'; statusText = 'Good — Minor overhead'; }
    else if (d.status === 'degraded') { colorClass = 'color-fair'; barColor = '#facc15'; statusText = 'Degraded — Possible tunnel overhead'; }
    else { colorClass = 'color-critical'; barColor = '#f87171'; statusText = 'Poor — Significant fragmentation risk'; }

    wrap.innerHTML =
        '<div class="diag-mtu-display">' +
            '<div class="diag-mtu-value ' + colorClass + '">' + d.max_mtu + '</div>' +
            '<div class="diag-mtu-label">Max MTU (bytes)</div>' +
            '<div style="font-size:0.78rem;color:#94a3b8;margin-top:4px;">' + statusText + '</div>' +
            '<div class="diag-mtu-bar"><div class="diag-mtu-fill" style="width:' + pct + '%;background:' + barColor + ';"></div></div>' +
            '<div style="display:flex;justify-content:space-between;width:100%;font-size:0.65rem;color:#475569;margin-top:3px;"><span>500</span><span>1000</span><span>1500</span></div>' +
        '</div>';

    showResult('mtu', d.status !== 'poor' ? 'ok' : 'fail');
}

/* ===== ROUTEROS ===== */
function renderRouterOs(d) {
    const wrap = document.getElementById('routeros-results');

    if (!d.connected) {
        wrap.innerHTML = '<div class="diag-ros-error"><i class="fa-solid fa-plug-circle-xmark"></i><div>Could not connect to RouterOS API</div><div style="font-size:0.75rem;color:#94a3b8;margin-top:4px;">' + (d.error || 'Connection failed') + '</div></div>';
        showResult('routeros', 'fail');
        return;
    }

    const formatBytes = (bytes) => {
        if (!bytes) return '0 B';
        const mb = bytes / (1024 * 1024);
        if (mb >= 1024) return (mb / 1024).toFixed(1) + ' GB';
        return mb.toFixed(0) + ' MB';
    };

    const cpuColor = d.cpu_load <= 50 ? '#4ade80' : (d.cpu_load <= 80 ? '#facc15' : '#f87171');
    const memColor = d.memory_used_percent <= 60 ? '#4ade80' : (d.memory_used_percent <= 85 ? '#facc15' : '#f87171');
    const hddColor = d.hdd_used_percent <= 70 ? '#4ade80' : (d.hdd_used_percent <= 90 ? '#facc15' : '#f87171');

    wrap.innerHTML =
        '<div class="diag-ros-grid">' +
            '<div class="diag-ros-item"><div class="diag-ros-label">Identity</div><div class="diag-ros-value" style="color:#22d3ee;">' + d.identity + '</div></div>' +
            '<div class="diag-ros-item"><div class="diag-ros-label">RouterOS Version</div><div class="diag-ros-value">' + d.version + '</div></div>' +
            '<div class="diag-ros-item"><div class="diag-ros-label">Uptime</div><div class="diag-ros-value" style="color:#a78bfa;">' + d.uptime + '</div></div>' +
            '<div class="diag-ros-item"><div class="diag-ros-label">Board</div><div class="diag-ros-value">' + d.board + '</div></div>' +
            '<div class="diag-ros-item"><div class="diag-ros-label">Architecture</div><div class="diag-ros-value">' + d.architecture + '</div></div>' +
            '<div class="diag-ros-item"><div class="diag-ros-label">CPU Cores</div><div class="diag-ros-value">' + d.cpu_count + '</div></div>' +
            '<div class="diag-ros-item" style="grid-column:span 2;"><div class="diag-ros-label">CPU Load</div><div class="diag-ros-value" style="color:' + cpuColor + ';">' + d.cpu_load + '%</div>' +
                '<div class="diag-ros-bar-wrap"><div class="diag-ros-bar-bg"><div class="diag-ros-bar-fill" style="width:' + d.cpu_load + '%;background:' + cpuColor + ';"></div></div></div>' +
            '</div>' +
            '<div class="diag-ros-item"><div class="diag-ros-label">Memory Usage</div><div class="diag-ros-value" style="color:' + memColor + ';">' + d.memory_used_percent + '%</div>' +
                '<div class="diag-ros-bar-wrap"><div class="diag-ros-bar-bg"><div class="diag-ros-bar-fill" style="width:' + d.memory_used_percent + '%;background:' + memColor + ';"></div></div>' +
                '<div class="diag-ros-bar-label"><span>' + formatBytes(d.memory_free) + ' free</span><span>' + formatBytes(d.memory_total) + ' total</span></div></div>' +
            '</div>' +
            '<div class="diag-ros-item"><div class="diag-ros-label">Storage Usage</div><div class="diag-ros-value" style="color:' + hddColor + ';">' + d.hdd_used_percent + '%</div>' +
                '<div class="diag-ros-bar-wrap"><div class="diag-ros-bar-bg"><div class="diag-ros-bar-fill" style="width:' + d.hdd_used_percent + '%;background:' + hddColor + ';"></div></div>' +
                '<div class="diag-ros-bar-label"><span>' + formatBytes(d.hdd_free) + ' free</span><span>' + formatBytes(d.hdd_total) + ' total</span></div></div>' +
            '</div>' +
        '</div>';

    showResult('routeros', 'ok');
}

/* ===== QUALITY ===== */
function resetQuality() {
    document.getElementById('gauge-arc').style.strokeDashoffset = '251.2';
    document.getElementById('gauge-score').textContent = '--';
    document.getElementById('gauge-label').textContent = 'SCANNING';
    document.getElementById('gauge-label').setAttribute('fill', '#64748b');
    document.getElementById('qf-latency').textContent = '--';
    document.getElementById('qf-latency').className = 'diag-factor-value';
    document.getElementById('qf-loss').textContent = '--';
    document.getElementById('qf-loss').className = 'diag-factor-value';
    document.getElementById('qf-jitter').textContent = '--';
    document.getElementById('qf-jitter').className = 'diag-factor-value';
}

function renderQuality(d) {
    const arc = document.getElementById('gauge-arc');
    const offset = 251.2 - (251.2 * d.score / 100);
    arc.style.transition = 'stroke-dashoffset 1.5s ease-out';
    arc.style.strokeDashoffset = offset;

    document.getElementById('gauge-score').textContent = d.score;
    document.getElementById('gauge-label').textContent = d.rating.toUpperCase();

    const ratingColors = { 'Excellent':'#22d3ee', 'Good':'#4ade80', 'Fair':'#facc15', 'Poor':'#fb923c', 'Critical':'#f87171' };
    document.getElementById('gauge-label').setAttribute('fill', ratingColors[d.rating] || '#64748b');

    const factorMap = {
        'perfect': { text:'Perfect', cls:'color-excellent' },
        'good': { text:'Good', cls:'color-good' },
        'fair': { text:'Fair', cls:'color-fair' },
        'poor': { text:'Poor', cls:'color-critical' },
        'N/A': { text:'N/A', cls:'color-critical' },
        'total_loss': { text:'Total Loss', cls:'color-critical' },
    };

    ['latency','loss','jitter'].forEach(f => {
        const el = document.getElementById('qf-' + f);
        const info = factorMap[d.factors[f]] || { text:d.factors[f], cls:'' };
        el.textContent = info.text;
        el.className = 'diag-factor-value ' + info.cls;
    });
}

$(document).ready(function() {
    runDiagnostics();
});
</script>
@endpush
