<?php
// ============================================================
// index.php — Main entry point: Login gate + Dashboard
// ============================================================
require_once 'config.php';
session_name(SESSION_NAME);
session_start();

$isLoggedIn  = !empty($_SESSION['user_id']);
$userRole    = $_SESSION['role'] ?? '';
$userName    = $_SESSION['full_name'] ?? $_SESSION['username'] ?? '';
$trialExp    = $_SESSION['trial_exp'] ?? null;

// Hitung sisa trial
$trialLeft   = '';
$trialWarn   = false;
if ($isLoggedIn && $userRole === 'trial' && $trialExp) {
    $secs = strtotime($trialExp) - time();
    if ($secs < 0) {
        // Expired — force logout
        session_unset(); session_destroy();
        header('Location: index.php?expired=1');
        exit;
    }
    $hrs  = floor($secs / 3600);
    $mins = floor(($secs % 3600) / 60);
    $trialLeft = "{$hrs}j {$mins}m";
    $trialWarn = $secs < 3600; // < 1 jam
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= APP_TITLE ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
:root{
  --bg:#0F1117;--bg2:#1A1D26;--bg3:#1E2535;
  --border:#1E2535;--border2:#2D3748;
  --text:#E2E8F0;--text2:#94A3B8;--text3:#64748B;
  --accent:#3B82F6;--accent2:#2563EB;
  --green:#34D399;--green-bg:#022C22;
  --yellow:#FBBF24;--yellow-bg:#451A03;
  --red:#F87171;--red-bg:#3B0606;
  --orange:#FB923C;
}
body{font-family:'Inter',sans-serif;background:var(--bg);color:var(--text);min-height:100vh}

/* ── LOGIN PAGE ── */
.login-page{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:20px;background:radial-gradient(ellipse at 60% 40%,#0F2A4A 0%,var(--bg) 60%)}
.login-box{background:var(--bg2);border:1px solid var(--border2);border-radius:16px;padding:40px;width:100%;max-width:420px;box-shadow:0 20px 60px rgba(0,0,0,.5)}
.login-logo{display:flex;align-items:center;gap:12px;margin-bottom:28px}
.logo-badge{width:44px;height:44px;background:linear-gradient(135deg,#E65100,#FB923C);border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:22px;box-shadow:0 4px 12px rgba(230,81,0,.3)}
.login-box h1{font-size:22px;font-weight:600;margin-bottom:4px}
.login-box .sub{font-size:13px;color:var(--text3);margin-bottom:28px}
.form-group{margin-bottom:14px}
.form-group label{display:block;font-size:12px;color:var(--text2);margin-bottom:5px;font-weight:500}
.form-group input{width:100%;background:var(--bg);border:1px solid var(--border2);border-radius:8px;padding:10px 12px;font-size:14px;color:var(--text);font-family:inherit;transition:.15s}
.form-group input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(59,130,246,.15)}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:10px 18px;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer;border:none;transition:.15s;font-family:inherit}
.btn-full{width:100%}
.btn-primary{background:var(--accent2);color:#fff}
.btn-primary:hover{background:#1D4ED8}
.btn-outline{background:transparent;border:1px solid var(--border2);color:var(--text2)}
.btn-outline:hover{background:var(--bg3);color:var(--text)}
.divider{display:flex;align-items:center;gap:10px;color:var(--text3);font-size:12px;margin:16px 0}
.divider::before,.divider::after{content:'';flex:1;height:1px;background:var(--border2)}
.alert{padding:10px 12px;border-radius:8px;font-size:13px;margin-bottom:14px}
.alert-ok{background:var(--green-bg);border:1px solid #065F46;color:#6EE7B7}
.alert-err{background:var(--red-bg);border:1px solid #7F1D1D;color:#FCA5A5}
.alert-warn{background:var(--yellow-bg);border:1px solid #78350F;color:var(--yellow)}
.tabs-auth{display:flex;border:1px solid var(--border2);border-radius:8px;overflow:hidden;margin-bottom:20px}
.tab-auth{flex:1;padding:9px;font-size:13px;text-align:center;cursor:pointer;color:var(--text2);transition:.15s}
.tab-auth.active{background:var(--accent2);color:#fff}
.auth-panel{display:none}.auth-panel.active{display:block}

/* ── DASHBOARD ── */
.app{display:flex;flex-direction:column;min-height:100vh}
.appbar{background:var(--bg2);border-bottom:1px solid var(--border);padding:0 20px;height:52px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;position:sticky;top:0;z-index:50}
.appbar-left{display:flex;align-items:center;gap:10px}
.appbar h2{font-size:14px;font-weight:600}
.appbar .device-tag{font-size:11px;background:var(--bg3);border:1px solid var(--border2);padding:2px 8px;border-radius:4px;color:var(--text3)}
.user-pill{display:flex;align-items:center;gap:8px;font-size:13px}
.role-badge{font-size:11px;padding:2px 8px;border-radius:4px;font-weight:500}
.rb-trial{background:var(--yellow-bg);color:var(--yellow)}
.rb-registered{background:var(--green-bg);color:var(--green)}
.trial-timer{font-size:12px;color:var(--yellow);font-family:'JetBrains Mono',monospace}
.trial-timer.warn{color:var(--red);animation:pulse 1.5s infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.5}}
.content{flex:1;padding:20px;max-width:1100px;width:100%;margin:0 auto}

/* nav tabs */
.nav-tabs{display:flex;gap:4px;flex-wrap:wrap;margin-bottom:20px}
.ntab{padding:7px 14px;border:1px solid var(--border2);border-radius:7px;font-size:13px;cursor:pointer;background:var(--bg);color:var(--text2);transition:.15s}
.ntab:hover{background:var(--bg3)}
.ntab.active{background:#1E3A5F;color:#93C5FD;border-color:#1D4ED8}

/* panel */
.panel{display:none}.panel.active{display:block}

/* cards */
.grid-stat{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin-bottom:16px}
.scard{background:var(--bg2);border:1px solid var(--border);border-radius:10px;padding:14px 16px}
.scard .slabel{font-size:11px;color:var(--text3);margin-bottom:4px;text-transform:uppercase;letter-spacing:.04em}
.scard .sval{font-size:20px;font-weight:600;color:var(--text)}
.scard .ssub{font-size:11px;color:var(--text2);margin-top:3px}
.bcard{background:var(--bg2);border:1px solid var(--border);border-radius:10px;padding:16px;margin-bottom:12px}
.section-h{font-size:13px;font-weight:600;color:var(--text2);margin:18px 0 8px;text-transform:uppercase;letter-spacing:.06em}

/* table */
.dtable{width:100%;border-collapse:collapse;font-size:13px}
.dtable th{padding:8px 12px;text-align:left;font-size:11px;color:var(--text3);border-bottom:1px solid var(--border);font-weight:500;text-transform:uppercase;letter-spacing:.04em}
.dtable td{padding:9px 12px;border-bottom:1px solid var(--bg);color:var(--text2)}
.dtable tr:last-child td{border-bottom:none}
.dtable tr:hover td{background:var(--bg3)}
.badge{display:inline-block;font-size:11px;padding:2px 7px;border-radius:4px;font-weight:500}
.b-up{background:#022C22;color:#34D399}
.b-wan{background:#1E3A5F;color:#93C5FD}
.b-lan{background:#022C22;color:#34D399}
.b-dmz{background:#422006;color:#FDBA74}
.b-vlan{background:#2E1065;color:#C4B5FD}
.b-other{background:var(--bg3);color:var(--text3)}
.mrow{display:flex;align-items:center;justify-content:space-between;padding:9px 0;border-bottom:1px solid var(--border)}
.mrow:last-child{border-bottom:none}
.mrow .ml{font-size:13px;color:var(--text2)}
.mrow .mr{font-size:13px;font-weight:500;color:var(--text)}

/* alert rows */
.arow{display:flex;gap:10px;padding:10px 12px;border-radius:8px;margin-bottom:8px;font-size:13px;line-height:1.5}
.a-warn{background:#422006;color:#FDBA74;border:1px solid #78350F}
.a-info{background:#1E3A5F;color:#93C5FD;border:1px solid #1D4ED8}
.a-ok{background:var(--green-bg);color:var(--green);border:1px solid #065F46}
.a-err{background:var(--red-bg);color:var(--red);border:1px solid #7F1D1D}

/* cmd box */
.cmdbox{background:var(--bg);border:1px solid var(--border2);border-radius:8px;padding:10px 14px;font-family:'JetBrains Mono',monospace;font-size:12px;color:#93C5FD;margin-bottom:8px;position:relative;white-space:pre-wrap;line-height:1.5}
.cmdlabel{font-size:11px;color:var(--text3);font-family:'Inter',sans-serif;margin-bottom:4px}
.cpybtn{position:absolute;right:8px;top:8px;font-size:11px;padding:3px 10px;border:1px solid var(--border2);border-radius:4px;cursor:pointer;background:var(--bg2);color:var(--text2);font-family:'Inter',sans-serif}
.cpybtn:hover{background:var(--bg3)}

/* QoS bars */
.qbar{margin-bottom:10px}
.qbar-row{display:flex;justify-content:space-between;font-size:12px;color:var(--text2);margin-bottom:4px}
.qbar-track{height:5px;background:var(--bg3);border-radius:3px;overflow:hidden}
.qbar-fill{height:5px;border-radius:3px;transition:width .5s}

/* AI */
.ai-box{background:var(--bg2);border:1px solid var(--border2);border-radius:10px;padding:16px}
.ai-box textarea{width:100%;background:var(--bg);border:1px solid var(--border2);border-radius:8px;padding:10px;font-size:13px;color:var(--text);font-family:'Inter',sans-serif;resize:vertical;min-height:72px}
.ai-box textarea:focus{outline:none;border-color:var(--accent)}
.ai-qbtns{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px;margin-bottom:8px}
.ai-qbtn{padding:5px 12px;border:1px solid var(--border2);border-radius:6px;font-size:12px;cursor:pointer;background:var(--bg3);color:var(--text2);font-family:'Inter',sans-serif}
.ai-qbtn:hover{border-color:var(--accent);color:var(--text)}
.ai-resp{background:var(--bg);border:1px solid var(--border2);border-radius:8px;padding:14px;font-size:13px;line-height:1.7;color:var(--text2);margin-top:10px;display:none;white-space:pre-wrap}
.ai-resp.show{display:block}
.ai-typing{color:var(--accent);font-style:italic}

/* Read-only overlay */
.readonly-note{display:flex;align-items:center;gap:8px;background:#1E3A5F;border:1px solid #1D4ED8;border-radius:8px;padding:10px 14px;font-size:13px;color:#93C5FD;margin-bottom:16px}

/* topo svg */
.topo-wrap{overflow-x:auto}
.topo-svg{min-width:580px;width:100%}
/* script templates */
.script-cat{margin-bottom:24px}
.script-cat-title{font-size:11px;font-weight:600;color:var(--text3);text-transform:uppercase;letter-spacing:.08em;margin-bottom:8px;display:flex;align-items:center;gap:6px}
.script-card{background:var(--bg2);border:1px solid var(--border);border-radius:10px;margin-bottom:8px;overflow:hidden;transition:.15s}
.script-card:hover{border-color:var(--border2)}
.script-header{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;cursor:pointer}
.script-header-left{display:flex;align-items:center;gap:8px}
.script-title{font-size:13px;font-weight:500;color:var(--text)}
.script-desc{font-size:11px;color:var(--text3);margin-top:1px}
.script-body{display:none;border-top:1px solid var(--border);padding:12px 14px}
.script-body.open{display:block}
.script-code{background:var(--bg);border:1px solid var(--border2);border-radius:6px;padding:10px 12px;font-family:'JetBrains Mono',monospace;font-size:12px;color:#93C5FD;white-space:pre;overflow-x:auto;position:relative;line-height:1.6}
.script-actions{display:flex;gap:6px;margin-top:8px}
.script-btn{padding:5px 12px;border:1px solid var(--border2);border-radius:5px;font-size:12px;cursor:pointer;font-family:inherit;transition:.15s}
.script-btn-copy{background:var(--bg3);color:var(--text2)}
.script-btn-copy:hover{background:#1E3A5F;color:#93C5FD;border-color:#1D4ED8}
.script-btn-ai{background:#1E2A1E;color:#34D399;border-color:#065F46}
.script-btn-ai:hover{background:#022C22}
.script-tag{font-size:10px;padding:2px 7px;border-radius:3px;font-weight:500}
.tag-diag{background:#1E3A5F;color:#93C5FD}
.tag-user{background:#2E1065;color:#C4B5FD}
.tag-sec{background:#3B0606;color:#FCA5A5}
.tag-net{background:#022C22;color:#34D399}
.tag-sys{background:#422006;color:#FDBA74}
.script-search{width:100%;background:var(--bg2);border:1px solid var(--border2);border-radius:8px;padding:9px 14px;font-size:13px;color:var(--text);font-family:inherit;margin-bottom:16px}
.script-search:focus{outline:none;border-color:var(--accent)}
.script-filter{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:16px}
.filter-btn{padding:5px 12px;border:1px solid var(--border2);border-radius:6px;font-size:12px;cursor:pointer;background:var(--bg2);color:var(--text2);font-family:inherit}
.filter-btn.active{background:#1E3A5F;color:#93C5FD;border-color:#1D4ED8}
.copy-toast{position:fixed;bottom:20px;right:20px;background:#022C22;border:1px solid #065F46;color:#34D399;padding:10px 16px;border-radius:8px;font-size:13px;z-index:999;display:none}
</style>
</head>
<body>

<?php if (!$isLoggedIn): ?>
<!-- ══════════════════════════════════════════════
     LOGIN / REGISTER PAGE
════════════════════════════════════════════════ -->
<div class="login-page">
  <div class="login-box">
    <div class="login-logo">
      <div class="logo-badge">🛡</div>
      <div>
        <div style="font-size:16px;font-weight:600">FortiGate Dashboard</div>
        <div style="font-size:12px;color:var(--text3)">Firewall - FortiGate-100F</div>
      </div>
    </div>

    <?php if (isset($_GET['expired'])): ?>
    <div class="alert alert-warn">⏰ Masa trial Anda sudah berakhir. Hubungi administrator.</div>
    <?php endif ?>

    <div class="tabs-auth">
      <div class="tab-auth active" id="tab-login" onclick="switchTab('login')">Masuk</div>
      <?php if (ALLOW_SELF_REGISTER): ?>
      <div class="tab-auth" id="tab-reg" onclick="switchTab('reg')">Daftar Trial</div>
      <?php endif ?>
    </div>

    <!-- Login -->
    <div class="auth-panel active" id="ap-login">
      <div id="login-alert"></div>
      <div class="form-group">
        <label>Username atau Email</label>
        <input type="text" id="l-user" placeholder="username / email" autocomplete="username">
      </div>
      <div class="form-group">
        <label>Password</label>
        <input type="password" id="l-pass" placeholder="••••••••" autocomplete="current-password" onkeydown="if(event.key==='Enter')doLogin()">
      </div>
      <button class="btn btn-primary btn-full" id="login-btn" onclick="doLogin()">Masuk ke Dashboard →</button>
      <p style="font-size:12px;color:var(--text3);margin-top:14px;text-align:center">
        Dashboard hanya untuk monitoring & troubleshooting.<br>Tidak ada perubahan konfigurasi.
      </p>
    </div>

    <!-- Register -->
    <?php if (ALLOW_SELF_REGISTER): ?>
    <div class="auth-panel" id="ap-reg">
      <div id="reg-alert"></div>
      <div class="form-group"><label>Username *</label><input type="text" id="r-user" placeholder="john_doe"></div>
      <div class="form-group"><label>Email *</label><input type="email" id="r-email" placeholder="email@perusahaan.com"></div>
      <div class="form-group"><label>Password *</label><input type="password" id="r-pass" placeholder="min 8 karakter"></div>
      <div class="form-group"><label>Nama Lengkap</label><input type="text" id="r-name" placeholder="John Doe"></div>
      <div class="form-group"><label>Perusahaan</label><input type="text" id="r-co" placeholder="PT Contoh"></div>
      <button class="btn btn-primary btn-full" onclick="doRegister()">Daftar Trial Gratis →</button>
      <p style="font-size:12px;color:var(--text3);margin-top:12px;text-align:center">Akun trial aktif <?= TRIAL_DURATION_HOURS ?> jam setelah registrasi</p>
    </div>
    <?php endif ?>
  </div>
</div>

<?php else: ?>
<!-- ══════════════════════════════════════════════
     DASHBOARD (after login)
════════════════════════════════════════════════ -->
<div class="app">
  <header class="appbar">
    <div class="appbar-left">
      <span style="font-size:20px">🛡</span>
      <h2>FortiGate Dashboard</h2>
      <span class="device-tag">Fortigate · 100F</span>
    </div>
    <div class="user-pill">
      <?php if ($trialLeft): ?>
        <span class="trial-timer <?= $trialWarn ? 'warn' : '' ?>" title="Sisa trial">⏱ <?= $trialLeft ?></span>
      <?php endif ?>
      <span style="font-size:13px;color:var(--text2)"><?= htmlspecialchars($userName) ?></span>
      <span class="role-badge <?= $userRole === 'trial' ? 'rb-trial' : 'rb-registered' ?>"><?= $userRole ?></span>
      <button class="btn btn-outline" style="padding:5px 12px;font-size:12px" onclick="doLogout()">Logout</button>
    </div>
  </header>

  <div class="content">
    <div class="readonly-note">
      🔒 <strong>Mode Read-Only</strong> — Dashboard ini hanya untuk monitoring & troubleshooting. Perubahan konfigurasi hanya dapat dilakukan langsung melalui FortiGate.
    </div>

    <nav class="nav-tabs">
      <button class="ntab active" onclick="showPanel('overview',this)">📊 Overview</button>
      <button class="ntab" onclick="showPanel('interfaces',this)">🔌 Interfaces</button>
      <button class="ntab" onclick="showPanel('topology',this)">🗺 Topology</button>
      <button class="ntab" onclick="showPanel('qos',this)">⚖️ QoS</button>
      <button class="ntab" onclick="showPanel('users',this)">👥 Users</button>
      <button class="ntab" onclick="showPanel('security',this)">🔐 Security</button>
      <button class="ntab" onclick="showPanel('troubleshoot',this)">🔧 Troubleshoot</button>
      <button class="ntab" onclick="showPanel('ai',this)">🤖 AI Assist</button>
      <button class="ntab" onclick="showPanel('scripts',this)">📜 Script Templates</button>
    </nav>

    <!-- OVERVIEW -->
    <div class="panel active" id="p-overview">
      <div class="grid-stat">
        <div class="scard"><div class="slabel">Hostname</div><div class="sval" style="font-size:15px">Fortigate Firewall</div><div class="ssub">FortiGate-100F</div></div>
        <div class="scard"><div class="slabel">Firmware</div><div class="sval" style="font-size:14px">7.4.11</div><div class="ssub">build 2878</div></div>
        <div class="scard"><div class="slabel">WAN links</div><div class="sval">3</div><div class="ssub">VSAT + 2× Starlink</div></div>
        <div class="scard"><div class="slabel">Segmen LAN</div><div class="sval">7</div><div class="ssub">incl. 5 VLAN WiFi</div></div>
        <div class="scard"><div class="slabel">Local users</div><div class="sval">82</div><div class="ssub">marine001–081 + guest</div></div>
      </div>
      <div class="section-h">WAN status</div>
      <div class="bcard">
        <div class="mrow"><span class="ml">wan1 — VSAT2</span><span class="badge b-up">UP</span></div>
        <div class="mrow"><span class="ml">wan2 — Starlink2-KIT-357</span><span class="badge b-up">UP</span></div>
        <div class="mrow"><span class="ml">port2 — Starlink1-KIT355</span><span class="badge b-up">UP</span></div>
      </div>
      <div class="section-h">Alerts</div>
      <div class="arow a-warn">⚠️ <div><strong>Telnet port 23 aktif</strong> — Risiko keamanan. Disable via: <code>config system global → set admin-telnet disable</code></div></div>
      <div class="arow a-warn">⚠️ <div><strong>HTTP admin port 80</strong> — Akses admin plaintext. Disable port 80, gunakan HTTPS port 3443 saja.</div></div>
      <div class="arow a-info">ℹ️ <div><strong>Tidak ada SD-WAN</strong> — 3 WAN link terdeteksi tanpa SD-WAN. Failover manual. Pertimbangkan konfigurasi SD-WAN.</div></div>
      <div class="arow a-ok">✅ <div><strong>IPS sensor aktif</strong> — Profile "default" terkonfigurasi.</div></div>
      <div class="arow a-ok">✅ <div><strong>FortiToken Cloud aktif</strong> — Infrastruktur 2FA tersedia (belum diaktifkan per-user).</div></div>
    </div>

    <!-- INTERFACES -->
    <div class="panel" id="p-interfaces">
      <div class="section-h">Interface list</div>
      <div class="bcard" style="padding:0;overflow:hidden">
        <div style="overflow-x:auto">
        <table class="dtable">
          <thead><tr><th>Interface</th><th>Alias</th><th>IP Address</th><th>Type</th><th>Status</th></tr></thead>
          <tbody>
            <tr><td><strong>wan1</strong></td><td>VSAT2</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">DHCP/PPPoE</td><td><span class="badge b-wan">WAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>wan2</strong></td><td>Starlink2-KIT-357</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">DHCP</td><td><span class="badge b-wan">WAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>port2</strong></td><td>Starlink1-KIT355</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">DHCP</td><td><span class="badge b-wan">WAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>lan</strong></td><td>LAN (hard-switch)</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.20.11.254/23</td><td><span class="badge b-lan">LAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>dmz</strong></td><td>DMZ</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.10.10.1/24</td><td><span class="badge b-dmz">DMZ</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>mgmt</strong></td><td>Management</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">192.168.1.99/24</td><td><span class="badge b-lan">LAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>port12</strong></td><td>PABX-System</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.30.10.254/24</td><td><span class="badge b-lan">LAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>port20</strong></td><td>SWMGMT</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.20.12.254/24</td><td><span class="badge b-lan">LAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>MarineCrewWifi</strong></td><td>Marine Crew WiFi</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.30.11.254/24</td><td><span class="badge b-vlan">VLAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>ClientCrewWifi</strong></td><td>Client Crew WiFi</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.40.11.254/24</td><td><span class="badge b-vlan">VLAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>PMT Wifi</strong></td><td>PMT Wifi</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.50.11.254/24</td><td><span class="badge b-vlan">VLAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>Client Office</strong></td><td>Client Office</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.60.11.254/24</td><td><span class="badge b-vlan">VLAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>AppUpdate</strong></td><td>App Update</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.70.11.254/24</td><td><span class="badge b-vlan">VLAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>Resiliant-Wifi</strong></td><td>Temporary</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.9.10.254/24</td><td><span class="badge b-vlan">VLAN</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>fortilink</strong></td><td>FortiSwitch</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">10.255.1.1/24</td><td><span class="badge b-other">Aggregate</span></td><td><span class="badge b-up">UP</span></td></tr>
            <tr><td><strong>ssl.root</strong></td><td>SSL VPN</td><td style="font-family:'JetBrains Mono',monospace;font-size:12px">—</td><td><span class="badge b-other">Tunnel</span></td><td><span class="badge b-up">UP</span></td></tr>
          </tbody>
        </table>
        </div>
      </div>
    </div>

    <!-- TOPOLOGY -->
    <div class="panel" id="p-topology">
      <div class="section-h">Network topology</div>
      <div class="bcard">
        <div class="topo-wrap">
        <svg class="topo-svg" viewBox="0 0 620 500" xmlns="http://www.w3.org/2000/svg">
          <defs><marker id="ar" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M2 1L8 5L2 9" fill="none" stroke="#4B5563" stroke-width="1.5" stroke-linecap="round"/></marker></defs>
          <rect x="220" y="8" width="180" height="34" rx="17" fill="#1E3A5F" stroke="#3B82F6" stroke-width="0.5"/><text x="310" y="29" text-anchor="middle" font-size="13" font-family="Inter,sans-serif" font-weight="500" fill="#93C5FD">Internet</text>
          <line x1="265" y1="42" x2="190" y2="92" stroke="#3B82F6" stroke-width="1" marker-end="url(#ar)"/>
          <line x1="310" y1="42" x2="310" y2="92" stroke="#3B82F6" stroke-width="1" marker-end="url(#ar)"/>
          <line x1="358" y1="42" x2="428" y2="92" stroke="#3B82F6" stroke-width="1" marker-end="url(#ar)"/>
          <text x="145" y="88" text-anchor="middle" font-size="10" fill="#60A5FA" font-family="Inter,sans-serif">wan1/VSAT2</text>
          <text x="310" y="88" text-anchor="middle" font-size="10" fill="#60A5FA" font-family="Inter,sans-serif">port2/Starlink1</text>
          <text x="468" y="88" text-anchor="middle" font-size="10" fill="#60A5FA" font-family="Inter,sans-serif">wan2/Starlink2</text>
          <rect x="185" y="100" width="250" height="50" rx="10" fill="#2E1065" stroke="#7C3AED" stroke-width="1"/>
          <text x="310" y="120" text-anchor="middle" font-size="13" font-weight="600" fill="#DDD6FE" font-family="Inter,sans-serif">FortiGate-100F</text>
          <text x="310" y="137" text-anchor="middle" font-size="11" fill="#A78BFA" font-family="Inter,sans-serif">Fortigate · 7.4.11</text>
          <line x1="255" y1="150" x2="100" y2="205" stroke="#34D399" stroke-width="1" marker-end="url(#ar)"/>
          <line x1="285" y1="150" x2="210" y2="205" stroke="#FB923C" stroke-width="1" marker-end="url(#ar)"/>
          <line x1="310" y1="150" x2="310" y2="205" stroke="#6B7280" stroke-width="1" marker-end="url(#ar)"/>
          <line x1="335" y1="150" x2="398" y2="205" stroke="#34D399" stroke-width="1" marker-end="url(#ar)"/>
          <line x1="368" y1="150" x2="510" y2="205" stroke="#8B5CF6" stroke-width="1" marker-end="url(#ar)"/>
          <rect x="30" y="207" width="140" height="40" rx="8" fill="#022C22" stroke="#065F46" stroke-width="0.5"/>
          <text x="100" y="224" text-anchor="middle" font-size="12" font-weight="500" fill="#34D399" font-family="Inter,sans-serif">LAN</text>
          <text x="100" y="238" text-anchor="middle" font-size="10" fill="#6EE7B7" font-family="Inter,sans-serif">10.20.11.0/23</text>
          <rect x="148" y="207" width="124" height="40" rx="8" fill="#422006" stroke="#9A3412" stroke-width="0.5"/>
          <text x="210" y="224" text-anchor="middle" font-size="12" font-weight="500" fill="#FDBA74" font-family="Inter,sans-serif">DMZ</text>
          <text x="210" y="238" text-anchor="middle" font-size="10" fill="#FED7AA" font-family="Inter,sans-serif">10.10.10.0/24</text>
          <rect x="250" y="207" width="120" height="40" rx="8" fill="#1F2937" stroke="#374151" stroke-width="0.5"/>
          <text x="310" y="224" text-anchor="middle" font-size="12" font-weight="500" fill="#D1D5DB" font-family="Inter,sans-serif">MGMT</text>
          <text x="310" y="238" text-anchor="middle" font-size="10" fill="#9CA3AF" font-family="Inter,sans-serif">192.168.1.99</text>
          <rect x="340" y="207" width="116" height="40" rx="8" fill="#022C22" stroke="#065F46" stroke-width="0.5"/>
          <text x="398" y="224" text-anchor="middle" font-size="12" font-weight="500" fill="#34D399" font-family="Inter,sans-serif">PABX</text>
          <text x="398" y="238" text-anchor="middle" font-size="10" fill="#6EE7B7" font-family="Inter,sans-serif">10.30.10.0/24</text>
          <rect x="436" y="207" width="150" height="40" rx="8" fill="#2E1065" stroke="#5B21B6" stroke-width="0.5"/>
          <text x="511" y="224" text-anchor="middle" font-size="12" font-weight="500" fill="#C4B5FD" font-family="Inter,sans-serif">WiFi VLANs</text>
          <text x="511" y="238" text-anchor="middle" font-size="10" fill="#DDD6FE" font-family="Inter,sans-serif">5 SSIDs</text>
          <line x1="100" y1="247" x2="100" y2="295" stroke="#34D399" stroke-width="0.5" marker-end="url(#ar)"/>
          <rect x="30" y="297" width="140" height="36" rx="6" fill="#022C22" stroke="#065F46" stroke-width="0.5"/>
          <text x="100" y="313" text-anchor="middle" font-size="11" fill="#34D399" font-family="Inter,sans-serif">FortiSwitch</text>
          <text x="100" y="326" text-anchor="middle" font-size="9" fill="#6EE7B7" font-family="Inter,sans-serif">FortiLink 10.255.1.x</text>
          <line x1="460" y1="247" x2="410" y2="295" stroke="#8B5CF6" stroke-width="0.5" marker-end="url(#ar)"/>
          <line x1="490" y1="247" x2="475" y2="295" stroke="#8B5CF6" stroke-width="0.5" marker-end="url(#ar)"/>
          <line x1="511" y1="247" x2="511" y2="295" stroke="#8B5CF6" stroke-width="0.5" marker-end="url(#ar)"/>
          <line x1="540" y1="247" x2="550" y2="295" stroke="#8B5CF6" stroke-width="0.5" marker-end="url(#ar)"/>
          <line x1="568" y1="247" x2="580" y2="295" stroke="#8B5CF6" stroke-width="0.5" marker-end="url(#ar)"/>
          <rect x="355" y="297" width="108" height="34" rx="5" fill="#1E1B4B" stroke="#3730A3" stroke-width="0.5"/>
          <text x="409" y="313" text-anchor="middle" font-size="10" fill="#A5B4FC" font-family="Inter,sans-serif">MarineCrew</text>
          <text x="409" y="325" text-anchor="middle" font-size="9" fill="#818CF8" font-family="Inter,sans-serif">10.30.11.0/24</text>
          <rect x="421" y="336" width="100" height="34" rx="5" fill="#1E1B4B" stroke="#3730A3" stroke-width="0.5"/>
          <text x="471" y="352" text-anchor="middle" font-size="10" fill="#A5B4FC" font-family="Inter,sans-serif">ClientCrew</text>
          <text x="471" y="364" text-anchor="middle" font-size="9" fill="#818CF8" font-family="Inter,sans-serif">10.40.11.0/24</text>
          <rect x="461" y="297" width="100" height="34" rx="5" fill="#1E1B4B" stroke="#3730A3" stroke-width="0.5"/>
          <text x="511" y="313" text-anchor="middle" font-size="10" fill="#A5B4FC" font-family="Inter,sans-serif">PMT Wifi</text>
          <text x="511" y="325" text-anchor="middle" font-size="9" fill="#818CF8" font-family="Inter,sans-serif">10.50.11.0/24</text>
          <rect x="519" y="336" width="104" height="34" rx="5" fill="#1E1B4B" stroke="#3730A3" stroke-width="0.5"/>
          <text x="571" y="352" text-anchor="middle" font-size="10" fill="#A5B4FC" font-family="Inter,sans-serif">Client Office</text>
          <text x="571" y="364" text-anchor="middle" font-size="9" fill="#818CF8" font-family="Inter,sans-serif">10.60.11.0/24</text>
          <rect x="557" y="297" width="60" height="34" rx="5" fill="#1E1B4B" stroke="#3730A3" stroke-width="0.5"/>
          <text x="587" y="313" text-anchor="middle" font-size="10" fill="#A5B4FC" font-family="Inter,sans-serif">AppUpd</text>
          <text x="587" y="325" text-anchor="middle" font-size="9" fill="#818CF8" font-family="Inter,sans-serif">10.70.x</text>
        </svg>
        </div>
      </div>
    </div>

    <!-- QoS -->
    <div class="panel" id="p-qos">
      <div class="section-h">Traffic shapers</div>
      <div class="bcard">
        <p style="font-size:12px;color:var(--text3);margin-bottom:14px">Bar menunjukkan guaranteed bandwidth relatif terhadap total WAN simulasi</p>
        <label style="font-size:12px;color:var(--text2)">Simulasi total WAN: <span id="bwv">10</span> Mbps</label>
        <input type="range" id="bwsl" min="1" max="50" value="10" style="width:100%;margin:8px 0 16px" oninput="updateBW(this.value)">
        <div id="bwbars"></div>
      </div>
      <div class="section-h">Address groups (policy objects)</div>
      <div class="bcard">
        <div class="mrow"><span class="ml">Marine-WorkPC</span><span class="mr">22 hosts</span></div>
        <div class="mrow"><span class="ml">Microsoft Office 365</span><span class="mr">3 FQDNs</span></div>
        <div class="mrow"><span class="ml">G Suite</span><span class="mr">2 FQDNs</span></div>
        <div class="mrow"><span class="ml">possible-vpn (block list)</span><span class="mr">~50 ISP ranges</span></div>
      </div>
    </div>

    <!-- USERS -->
    <div class="panel" id="p-users">
      <div class="section-h">Admin accounts</div>
      <div class="bcard">
        <div class="mrow"><span class="ml">carlo.l</span><span class="badge b-up">super_admin</span></div>
        <div class="mrow"><span class="ml">eto.resiliant</span><span class="badge b-up">super_admin</span></div>
      </div>
      <div class="section-h">Local user accounts</div>
      <div class="bcard">
        <div class="mrow"><span class="ml">Total akun</span><span class="mr">82</span></div>
        <div class="mrow"><span class="ml">Crew (marine001–081)</span><span class="mr">81</span></div>
        <div class="mrow"><span class="ml">Guest</span><span class="mr">1</span></div>
        <div class="mrow"><span class="ml">2FA FortiToken Cloud</span><span class="mr" style="color:var(--yellow)">Aktif (infrastruktur) / Belum per-user</span></div>
      </div>
      <div class="section-h">WiFi SSIDs</div>
      <?php
      $ssids = [
        ['MarineCrewWifi','10.30.11.0/24','Active'],
        ['ClientCrewWifi','10.40.11.0/24','Active'],
        ['PMT Wifi','10.50.11.0/24','Active'],
        ['Client Office','10.60.11.0/24','Active'],
        ['AppUpdate','10.70.11.0/24','Active'],
        ['Resiliant-Wifi','10.9.10.0/24','Temporary'],
      ];
      foreach ($ssids as $s): ?>
      <div class="bcard" style="padding:12px 16px;margin-bottom:6px;display:flex;align-items:center;justify-content:space-between">
        <div><strong style="font-size:13px"><?= $s[0] ?></strong><div style="font-size:11px;color:var(--text3);font-family:'JetBrains Mono',monospace;margin-top:2px"><?= $s[1] ?></div></div>
        <span class="badge <?= $s[2]==='Temporary'?'b-dmz':'b-up' ?>"><?= $s[2] ?></span>
      </div>
      <?php endforeach ?>
    </div>

    <!-- SECURITY -->
    <div class="panel" id="p-security">
      <div class="section-h">Security posture</div>
      <div class="bcard">
        <div class="mrow"><span class="ml">✅ HTTPS redirect aktif</span><span class="badge b-up">OK</span></div>
        <div class="mrow"><span class="ml">✅ TLS 1.2/1.3 only</span><span class="badge b-up">OK</span></div>
        <div class="mrow"><span class="ml">✅ SSH v1 disabled</span><span class="badge b-up">OK</span></div>
        <div class="mrow"><span class="ml">✅ Admin lockout 3x/60s</span><span class="badge b-up">OK</span></div>
        <div class="mrow"><span class="ml">✅ IPS sensor "default" aktif</span><span class="badge b-up">OK</span></div>
        <div class="mrow"><span class="ml">⚠️ Telnet port 23 aktif</span><span class="badge" style="background:#422006;color:#FDBA74">RISK</span></div>
        <div class="mrow"><span class="ml">⚠️ HTTP admin port 80</span><span class="badge" style="background:#422006;color:#FDBA74">RISK</span></div>
        <div class="mrow"><span class="ml">⚠️ 2FA tidak aktif per-user</span><span class="badge" style="background:var(--red-bg);color:var(--red)">RISK</span></div>
        <div class="mrow"><span class="ml">✅ Anti-replay strict</span><span class="badge b-up">OK</span></div>
      </div>
      <div class="section-h">DNS</div>
      <div class="bcard">
        <div class="mrow"><span class="ml">Primary DNS</span><span class="mr" style="font-family:'JetBrains Mono',monospace;font-size:12px">96.45.45.45 (FortiGuard)</span></div>
        <div class="mrow"><span class="ml">Secondary DNS</span><span class="mr" style="font-family:'JetBrains Mono',monospace;font-size:12px">96.45.46.46</span></div>
        <div class="mrow"><span class="ml">Protokol</span><span class="mr">Cleartext + DoT (TLS)</span></div>
        <div class="mrow"><span class="ml">DNS interface</span><span class="mr">port2 (Starlink1)</span></div>
      </div>
    </div>

    <!-- TROUBLESHOOT -->
    <div class="panel" id="p-troubleshoot">
      <div class="arow a-info" style="margin-bottom:14px">ℹ️ Copy commands below and run in FortiGate CLI (SSH port 22 or console) &nbsp;|&nbsp; Salin perintah dan jalankan di FortiGate CLI (SSH port 22 atau console).</div>

      <div class="section-h">Interface & routing</div>
      <div class="cmdbox"><div class="cmdlabel">Status semua interface</div>get system interface physical<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Tabel routing</div>get router info routing-table all<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Ping dari FortiGate via wan1</div>execute ping-options source wan1
execute ping 8.8.8.8<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Cek link detail wan1 (VSAT)</div>diagnose netlink interface list wan1<button class="cpybtn" onclick="cpy(this)">Copy</button></div>

      <div class="section-h">DNS & konektivitas</div>
      <div class="cmdbox"><div class="cmdlabel">Status DNS proxy</div>diagnose test application dnsproxy 6<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Traceroute ke internet</div>execute traceroute 8.8.8.8<button class="cpybtn" onclick="cpy(this)">Copy</button></div>

      <div class="section-h">Session & firewall</div>
      <div class="cmdbox"><div class="cmdlabel">Statistik session aktif</div>diagnose sys session stat<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Session dari IP tertentu (ganti IP)</div>diagnose sys session filter src 10.20.11.100
diagnose sys session list<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Policy lookup (packet test)</div>diagnose firewall iprope lookup 10.20.11.100 8.8.8.8 6 1024 443<button class="cpybtn" onclick="cpy(this)">Copy</button></div>

      <div class="section-h">Performance & sistem</div>
      <div class="cmdbox"><div class="cmdlabel">CPU & memory</div>get system performance status<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Status sistem & uptime</div>get system status<button class="cpybtn" onclick="cpy(this)">Copy</button></div>

      <div class="section-h">User & auth</div>
      <div class="cmdbox"><div class="cmdlabel">User yang sedang terautentikasi</div>diagnose firewall auth list<button class="cpybtn" onclick="cpy(this)">Copy</button></div>
      <div class="cmdbox"><div class="cmdlabel">Status FortiToken</div>diagnose fortitoken status<button class="cpybtn" onclick="cpy(this)">Copy</button></div>

      <div id="cpy-ok" style="display:none;margin-top:10px" class="arow a-ok">✅ Tersalin ke clipboard</div>
    </div>

    <!-- SCRIPT TEMPLATES -->
    <div class="panel" id="p-scripts">
      <div class="section-h">Script Templates — FortiGate CLI</div>
      <p style="font-size:13px;color:var(--text3);margin-bottom:12px">Koleksi script CLI siap pakai untuk troubleshoot, manage user, dan monitoring FortiGate Firewall.</p>

      <input class="script-search" type="text" id="script-search" placeholder="🔍 Cari script... (contoh: session, user, routing, wan)" oninput="filterScripts()">

      <div class="script-filter">
        <button class="filter-btn active" onclick="filterCat('all',this)">Semua</button>
        <button class="filter-btn" onclick="filterCat('diag',this)">🔍 Diagnostik</button>
        <button class="filter-btn" onclick="filterCat('user',this)">👥 User Mgmt</button>
        <button class="filter-btn" onclick="filterCat('sec',this)">🔐 Security</button>
        <button class="filter-btn" onclick="filterCat('net',this)">🌐 Network</button>
        <button class="filter-btn" onclick="filterCat('sys',this)">⚙️ System</button>
      </div>

      <div id="scripts-container"></div>
    </div>

    <!-- AI ASSIST -->
    <div class="panel" id="p-ai">
      <div class="section-h">AI Network Troubleshoot Assistant</div>
      <div class="ai-box">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px">
          <span style="font-size:12px;color:var(--text3)">Language / Bahasa:</span>
          <div style="display:flex;border:1px solid var(--border2);border-radius:6px;overflow:hidden">
            <button id="lang-id" onclick="setLang('id')" style="padding:5px 14px;font-size:12px;cursor:pointer;background:#2563EB;color:#fff;border:none;font-family:inherit">🇮🇩 Indonesia</button>
            <button id="lang-en" onclick="setLang('en')" style="padding:5px 14px;font-size:12px;cursor:pointer;background:var(--bg3);color:var(--text2);border:none;font-family:inherit">🇬🇧 English</button>
          </div>
        </div>
        <textarea id="ai-q" placeholder="Contoh: Kenapa user MarineCrewWifi tidak bisa akses internet? / How to setup SD-WAN failover?"></textarea>
        <div class="ai-qbtns" id="ai-qbtns"></div>
        <button class="btn btn-primary" onclick="sendAI()" id="ai-btn">Kirim pertanyaan →</button>
        <div class="ai-resp" id="ai-r"></div>
      </div>
    </div>

  </div><!-- /content -->
</div><!-- /app -->
<div class="copy-toast" id="copy-toast">✅ Tersalin ke clipboard</div>
<?php endif ?>

<script>
// ── Auth ──
function switchTab(t){
  document.querySelectorAll('.tab-auth,.auth-panel').forEach(e=>e.classList.remove('active'));
  document.getElementById('tab-'+t).classList.add('active');
  document.getElementById('ap-'+t).classList.add('active');
}

async function doLogin(){
  const btn=document.getElementById('login-btn');
  btn.textContent='Memproses...';btn.disabled=true;
  const fd=new FormData();
  fd.append('action','login');
  fd.append('username',document.getElementById('l-user').value);
  fd.append('password',document.getElementById('l-pass').value);
  const r=await fetch('api/auth.php',{method:'POST',body:fd}).then(r=>r.json()).catch(()=>({ok:false,msg:'Network error'}));
  if(r.ok){location.reload();}
  else{
    document.getElementById('login-alert').innerHTML=`<div class="alert alert-err">${r.msg}</div>`;
    btn.textContent='Masuk ke Dashboard →';btn.disabled=false;
  }
}

async function doRegister(){
  const fd=new FormData();
  fd.append('action','register');
  fd.append('username',document.getElementById('r-user').value);
  fd.append('email',document.getElementById('r-email').value);
  fd.append('password',document.getElementById('r-pass').value);
  fd.append('full_name',document.getElementById('r-name').value);
  fd.append('company',document.getElementById('r-co').value);
  const r=await fetch('api/auth.php',{method:'POST',body:fd}).then(r=>r.json()).catch(()=>({ok:false,msg:'Network error'}));
  const el=document.getElementById('reg-alert');
  el.innerHTML=`<div class="alert ${r.ok?'alert-ok':'alert-err'}">${r.msg}</div>`;
  if(r.ok) setTimeout(()=>switchTab('login'),2000);
}

function doLogout(){
  // Langsung redirect ke logout endpoint
  window.location.href = 'api/auth.php?action=logout&redirect=1';
}

// ── Dashboard ──
function showPanel(id,el){
  document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
  document.querySelectorAll('.ntab').forEach(t=>t.classList.remove('active'));
  document.getElementById('p-'+id).classList.add('active');
  el.classList.add('active');
  if(id==='scripts') renderScripts(activeFilter);
}

function cpy(btn){
  const box=btn.parentElement;
  const lines=Array.from(box.childNodes).filter(n=>n.nodeType===3||n.tagName==='BR').map(n=>n.nodeType===3?n.textContent.trim():'').filter(Boolean).join('\n');
  const text=lines||box.innerText.replace('Copy','').trim();
  if(navigator.clipboard && window.isSecureContext){
    navigator.clipboard.writeText(text).catch(()=>{});
  } else {
    const ta=document.createElement('textarea');
    ta.value=text;ta.style.cssText='position:fixed;left:-9999px';
    document.body.appendChild(ta);ta.focus();ta.select();
    document.execCommand('copy');document.body.removeChild(ta);
  }
  const ok=document.getElementById('cpy-ok');ok.style.display='flex';
  setTimeout(()=>ok.style.display='none',2500);
}

// QoS bars
function updateBW(v){
  document.getElementById('bwv').textContent=v;
  const total=parseInt(v)*1024;
  const sh=[
    {n:'Microsoft-High',g:2048,m:10240,c:'#3B82F6'},
    {n:'all-other',g:4096,m:10240,c:'#F59E0B'},
    {n:'mid',g:1024,m:4096,c:'#F59E0B'},
    {n:'Sosial-Media-Low',g:1024,m:3076,c:'#EF4444'},
    {n:'quic-isakmp-low',g:512,m:2048,c:'#EF4444'},
    {n:'guarantee-100kbps',g:100,m:Infinity,c:'#10B981'},
  ];
  document.getElementById('bwbars').innerHTML=sh.map(s=>{
    const pct=Math.min(100,Math.round(s.g/total*100));
    const mpct=s.m===Infinity?100:Math.min(100,Math.round(s.m/total*100));
    const gl=s.g>=1024?s.g/1024+'M':s.g+'K';
    const ml=s.m===Infinity?'unlimited':s.m>=1024?s.m/1024+'M':s.m+'K';
    return`<div class="qbar"><div class="qbar-row"><span>${s.n}</span><span style="color:var(--text3)">Guar ${gl} · Max ${ml}</span></div><div class="qbar-track"><div style="position:relative;height:5px"><div style="position:absolute;width:${mpct}%;height:5px;background:${s.c}22;border-radius:3px"></div><div class="qbar-fill" style="width:${pct}%;background:${s.c}"></div></div></div></div>`;
  }).join('');
}
updateBW(10);
document.addEventListener('DOMContentLoaded', function(){ if(document.getElementById('ai-qbtns')) renderQ(); });

// AI
let aiLang='id';
const aiQ={
  id:[
    {l:'WAN failover',q:'WAN failover VSAT ke Starlink tidak otomatis, bagaimana troubleshoot dan setup SD-WAN?'},
    {l:'User no internet',q:'User di MarineCrewWifi tidak bisa akses internet, langkah troubleshoot?'},
    {l:'Security hardening',q:'Langkah hardening admin FortiGate, disable Telnet, tutup HTTP port 80?'},
    {l:'Enable 2FA',q:'Cara enable 2FA FortiToken untuk user marine001 sampai marine081?'},
    {l:'QoS policy',q:'Cara membuat policy QoS untuk batasi bandwidth WiFi crew vs PMT?'},
    {l:'Cek routing',q:'Bagaimana cara cek dan troubleshoot routing table di FortiGate ini?'},
  ],
  en:[
    {l:'WAN failover',q:'WAN failover from VSAT to Starlink is not automatic, how to troubleshoot and setup SD-WAN?'},
    {l:'User no internet',q:'User on MarineCrewWifi cannot access internet, what are the troubleshooting steps?'},
    {l:'Security hardening',q:'Steps to harden FortiGate admin, disable Telnet, close HTTP port 80?'},
    {l:'Enable 2FA',q:'How to enable FortiToken 2FA for users marine001 to marine081?'},
    {l:'QoS policy',q:'How to create QoS policy to limit bandwidth for crew WiFi vs PMT WiFi?'},
    {l:'Check routing',q:'How to check and troubleshoot the routing table on this FortiGate?'},
  ]
};
function setLang(l){
  aiLang=l;
  document.getElementById('lang-id').style.cssText=l==='id'?'padding:5px 14px;font-size:12px;cursor:pointer;background:#2563EB;color:#fff;border:none;font-family:inherit':'padding:5px 14px;font-size:12px;cursor:pointer;background:var(--bg3);color:var(--text2);border:none;font-family:inherit';
  document.getElementById('lang-en').style.cssText=l==='en'?'padding:5px 14px;font-size:12px;cursor:pointer;background:#2563EB;color:#fff;border:none;font-family:inherit':'padding:5px 14px;font-size:12px;cursor:pointer;background:var(--bg3);color:var(--text2);border:none;font-family:inherit';
  document.getElementById('ai-q').placeholder=l==='en'?'Example: Why cannot users on MarineCrewWifi access internet? / How to setup SD-WAN failover VSAT to Starlink?':'Contoh: Kenapa user MarineCrewWifi tidak bisa akses internet? / Bagaimana setup SD-WAN failover VSAT ke Starlink?';
  document.getElementById('ai-btn').textContent=l==='en'?'Send question →':'Kirim pertanyaan →';
}
function renderQ(){
  document.getElementById('ai-qbtns').innerHTML=aiQ[aiLang].map(x=>`<button class="ai-qbtn" onclick="qk(this.dataset.q)" data-q="${x.q.replace(/"/g,'&quot;')}">${x.l}</button>`).join('');
}
function qk(q){document.getElementById('ai-q').value=q;sendAI();}
async function sendAI(){
  const q=document.getElementById('ai-q').value.trim();
  if(!q)return;
  const r=document.getElementById('ai-r');
  const btn=document.getElementById('ai-btn');
  r.className='ai-resp show ai-typing';
  r.textContent=aiLang==='en'?'Analyzing configuration...':'Menganalisa konfigurasi...';
  btn.disabled=true;
  btn.textContent=aiLang==='en'?'Processing...':'Memproses...';
  try{
    const res=await fetch('api/ai.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({question:q,lang:aiLang})});
    const d=await res.json();
    r.className='ai-resp show';
    r.textContent=d.answer||d.error||(aiLang==='en'?'No response.':'Tidak ada respons.');
  }catch(e){r.className='ai-resp show';r.textContent='Error: '+e.message;}
  btn.disabled=false;
  btn.textContent=aiLang==='en'?'Send question →':'Kirim pertanyaan →';
}

// ── Script Templates ──────────────────────────────────────
const SCRIPTS = [
  // ── DIAGNOSTIK ──
  {cat:'diag', icon:'🔍', title:'Status semua interface', desc:'Tampilkan status, IP, dan statistik semua interface',
   code:'get system interface physical',
   note:'Output: nama interface, status up/down, IP address, speed, duplex'},

  {cat:'diag', icon:'🔍', title:'Cek WAN link detail', desc:'Diagnosa link WAN1 (VSAT), WAN2 (Starlink2), port2 (Starlink1)',
   code:'# Cek WAN1 - VSAT2\ndiagnose netlink interface list wan1\n\n# Cek WAN2 - Starlink2\ndiagnose netlink interface list wan2\n\n# Cek port2 - Starlink1\ndiagnose netlink interface list port2',
   note:'Cek speed, duplex, error counter, RX/TX bytes'},

  {cat:'diag', icon:'🔍', title:'Ping test dari FortiGate', desc:'Test konektivitas dari setiap WAN interface',
   code:'# Ping via WAN1 (VSAT)\nexecute ping-options source wan1\nexecute ping 8.8.8.8\n\n# Ping via WAN2 (Starlink2)\nexecute ping-options source wan2\nexecute ping 8.8.8.8\n\n# Ping via port2 (Starlink1)\nexecute ping-options source port2\nexecute ping 8.8.8.8',
   note:'Gunakan untuk verifikasi konektivitas per WAN link'},

  {cat:'diag', icon:'🔍', title:'Statistik session aktif', desc:'Lihat jumlah session dan statistik trafik',
   code:'# Statistik ringkas\ndiagnose sys session stat\n\n# Daftar session (filter by source IP)\ndiagnose sys session filter src 10.20.11.100\ndiagnose sys session list\n\n# Clear filter\ndiagnose sys session filter clear',
   note:'Ganti 10.20.11.100 dengan IP yang ingin dicek'},

  {cat:'diag', icon:'🔍', title:'Debug trafik real-time', desc:'Capture dan debug paket trafik',
   code:'# Enable debug flow\ndiagnose debug enable\ndiagnose debug flow filter addr 10.20.11.100\ndiagnose debug flow filter port 443\ndiagnose debug flow show function-name enable\ndiagnose debug flow trace start 100\n\n# Setelah selesai debug — WAJIB matikan\ndiagnose debug flow trace stop\ndiagnose debug reset\ndiagnose debug disable',
   note:'⚠️ Matikan debug setelah selesai — bisa membebani CPU'},

  {cat:'diag', icon:'🔍', title:'Traceroute', desc:'Trace jalur routing ke destination',
   code:'# Traceroute ke internet\nexecute traceroute 8.8.8.8\n\n# Traceroute dengan source interface\nexecute ping-options source wan1\nexecute traceroute 8.8.8.8',
   note:'Identifikasi hop dan latency di setiap jalur'},

  {cat:'diag', icon:'🔍', title:'Policy lookup (packet test)', desc:'Simulasi paket untuk cek policy yang akan dipakai',
   code:'# Format: diagnose firewall iprope lookup [src] [dst] [proto] [sport] [dport]\n# Proto: 6=TCP, 17=UDP, 1=ICMP\n\n# Test HTTP dari LAN ke internet\ndiagnose firewall iprope lookup 10.20.11.100 8.8.8.8 6 1024 80\n\n# Test HTTPS dari MarineCrewWifi ke internet\ndiagnose firewall iprope lookup 10.30.11.10 8.8.8.8 6 1024 443\n\n# Test dari DMZ\ndiagnose firewall iprope lookup 10.10.10.10 8.8.8.8 6 1024 443',
   note:'Menampilkan policy ID yang akan digunakan untuk paket tersebut'},

  {cat:'diag', icon:'🔍', title:'CPU & Memory monitor', desc:'Pantau penggunaan resource sistem',
   code:'# Status performa sistem\nget system performance status\n\n# Monitor real-time (5 detik)\ndiagnose sys top 5\n\n# CPU per-core\ndiagnose hardware sysinfo cpu\n\n# Memory detail\ndiagnose hardware sysinfo mem',
   note:'CPU ideal < 70%, Memory < 80%'},

  // ── USER MANAGEMENT ──
  {cat:'user', icon:'👥', title:'Lihat user yang sedang aktif', desc:'Tampilkan semua user yang terautentikasi di firewall',
   code:'# Semua user aktif\ndiagnose firewall auth list\n\n# Filter per IP\ndiagnose firewall auth filter src 10.20.11.100\ndiagnose firewall auth list',
   note:'Menampilkan username, IP, waktu login, policy yang diizinkan'},

  {cat:'user', icon:'👥', title:'Logout / clear user session', desc:'Force logout user tertentu',
   code:'# Clear auth session berdasarkan IP\ndiagnose firewall auth clear-by-ip 10.20.11.100\n\n# Clear semua user aktif\ndiagnose firewall auth clear\n\n# Clear user berdasarkan username\ndiagnose firewall auth clear-by-user marine001',
   note:'Ganti IP/username sesuai user yang ingin di-logout'},

  {cat:'user', icon:'👥', title:'Tambah user local baru', desc:'Buat user baru marine di FortiGate',
   code:'config user local\n    edit "marine082"\n        set type password\n        set passwd "Password@2025"\n        set two-factor disable\n    next\nend',
   note:'Ganti marine082 dan password sesuai kebutuhan'},

  {cat:'user', icon:'👥', title:'Reset password user', desc:'Ganti password user yang sudah ada',
   code:'config user local\n    edit "marine001"\n        set passwd "NewPassword@2025"\n    next\nend',
   note:'Ganti marine001 dan password baru'},

  {cat:'user', icon:'👥', title:'Enable 2FA FortiToken untuk user', desc:'Aktifkan two-factor authentication per user',
   code:'# Cek token yang tersedia\ndiagnose fortitoken status\n\n# Assign token ke user\nconfig user local\n    edit "marine001"\n        set two-factor fortitoken-cloud\n        set email-to "marine001@vessel.com"\n    next\nend\n\n# Test kirim token\nexecute fortitoken-cloud provision marine001',
   note:'Pastikan FortiToken Cloud sudah aktif dan email valid'},

  {cat:'user', icon:'👥', title:'Lihat semua user local', desc:'Tampilkan daftar semua user yang terdaftar',
   code:'# Semua user\nshow user local\n\n# User tertentu\nshow user local marine001\n\n# Total user count\nget user local | grep -c "=="',
   note:'Menampilkan username, tipe, status 2FA'},

  {cat:'user', icon:'👥', title:'Buat user group WiFi crew', desc:'Assign user ke group untuk policy WiFi',
   code:'# Lihat group yang ada\nshow user group\n\n# Edit group marine-crew\nconfig user group\n    edit "marine-crew"\n        set member "marine001" "marine002" "marine003"\n    next\nend',
   note:'Ganti nama group dan member sesuai kebutuhan'},

  // ── SECURITY ──
  {cat:'sec', icon:'🔐', title:'Disable Telnet (RISK FIX)', desc:'Matikan akses Telnet yang tidak aman — WAJIB dilakukan',
   code:'config system global\n    set admin-telnet disable\nend\n\n# Verifikasi\nshow system global | grep telnet',
   note:'⚠️ SEGERA lakukan — Telnet tidak terenkripsi, rawan sniffing'},

  {cat:'sec', icon:'🔐', title:'Disable HTTP admin port 80 (RISK FIX)', desc:'Matikan akses admin via HTTP plaintext',
   code:'config system global\n    set admin-port 0\n    set admin-sport 3443\nend\n\n# Verifikasi — akses admin hanya via HTTPS port 3443\nshow system global | grep admin-port',
   note:'⚠️ Setelah ini, akses admin hanya via https://192.168.1.99:3443'},

  {cat:'sec', icon:'🔐', title:'Cek admin login attempt', desc:'Lihat log percobaan login admin',
   code:'# Log event admin login\nexecute log filter category event\nexecute log filter field user admin\nexecute log display',
   note:'Deteksi brute force atau akses tidak sah'},

  {cat:'sec', icon:'🔐', title:'Lihat firewall policy aktif', desc:'Tampilkan semua policy yang terkonfigurasi',
   code:'# Semua policy\nshow firewall policy\n\n# Policy dengan hitungan trafik\nget firewall policy\n\n# Policy tertentu by ID\nshow firewall policy 1',
   note:'Verifikasi policy sesuai kebutuhan keamanan'},

  {cat:'sec', icon:'🔐', title:'Cek IPS sensor status', desc:'Verifikasi IPS aktif dan signature update',
   code:'# Status IPS\ndiagnose ips signature status\n\n# Cek update terakhir\ndiagnose autoupdate versions | grep -A3 "IPS"\n\n# Force update signature\nexecute update-now',
   note:'Update signature IPS secara berkala untuk proteksi optimal'},

  {cat:'sec', icon:'🔐', title:'Blocked IP list', desc:'Lihat IP yang sedang diblokir',
   code:'# Banned IP list\ndiagnose user banned-ip list\n\n# Tambah banned IP manual\ndiagnose user banned-ip add 1.2.3.4 3600\n\n# Hapus banned IP\ndiagnose user banned-ip delete 1.2.3.4',
   note:'Ganti 3600 dengan durasi ban dalam detik'},

  // ── NETWORK ──
  {cat:'net', icon:'🌐', title:'Tabel routing lengkap', desc:'Lihat semua routing yang aktif',
   code:'# Routing table aktif\nget router info routing-table all\n\n# Routing detail per prefix\nget router info routing-table details 0.0.0.0/0\n\n# Static route config\nshow router static',
   note:'Verifikasi default route dan routing antar VLAN'},

  {cat:'net', icon:'🌐', title:'Setup SD-WAN basic (VSAT + Starlink)', desc:'Konfigurasi SD-WAN untuk failover otomatis 3 WAN',
   code:'# Step 1: Enable SD-WAN\nconfig system sdwan\n    set status enable\n    config members\n        edit 1\n            set interface "wan1"\n            set gateway 0.0.0.0\n        next\n        edit 2\n            set interface "wan2"\n            set gateway 0.0.0.0\n        next\n        edit 3\n            set interface "port2"\n            set gateway 0.0.0.0\n        next\n    end\n    config health-check\n        edit "ping-check"\n            set server "8.8.8.8"\n            set members 1 2 3\n        next\n    end\n    config service\n        edit 1\n            set name "default-route"\n            set mode priority\n            set dst "0.0.0.0/0"\n            set priority-members 1 2 3\n        next\n    end\nend',
   note:'⚠️ Backup konfigurasi dulu sebelum enable SD-WAN. Ganti gateway sesuai ISP'},

  {cat:'net', icon:'🌐', title:'DNS troubleshoot', desc:'Diagnosa masalah resolusi DNS',
   code:'# Test DNS resolution\ndiagnose test application dnsproxy 6\n\n# Cek DNS server yang dipakai\ndiagnose ip dnsproxy-server status\n\n# Flush DNS cache\ndiagnose test application dnsproxy 1\n\n# DNS lookup manual\nexecute nslookup google.com',
   note:'DNS menggunakan FortiGuard (96.45.45.45) via port2'},

  {cat:'net', icon:'🌐', title:'ARP table', desc:'Lihat tabel ARP untuk troubleshoot L2',
   code:'# ARP table semua interface\nget system arp\n\n# ARP per interface\ndiagnose ip arp list\n\n# Flush ARP cache\ndiagnose ip arp flush',
   note:'Berguna untuk troubleshoot IP conflict atau gateway unreachable'},

  {cat:'net', icon:'🌐', title:'DHCP lease monitor', desc:'Lihat IP yang dibagikan DHCP server',
   code:'# Semua DHCP lease\ndiagnose firewall iprope lookup\n\n# DHCP lease per VLAN\nget system dhcp server\n\n# Lease aktif\ndiagnose netlink interface list',
   note:'Monitor alokasi IP di setiap segmen jaringan'},

  {cat:'net', icon:'🌐', title:'Bandwidth usage per interface', desc:'Monitor penggunaan bandwidth real-time',
   code:'# Traffic stat per interface\ndiagnose netlink interface list wan1\ndiagnose netlink interface list wan2\ndiagnose netlink interface list port2\n\n# Reset counter\ndiagnose netlink interface clear wan1',
   note:'Lihat RX/TX bytes dan error untuk setiap WAN link'},

  // ── SYSTEM ──
  {cat:'sys', icon:'⚙️', title:'System status lengkap', desc:'Informasi lengkap sistem dan uptime',
   code:'# Status sistem\nget system status\n\n# Uptime dan versi\nget system performance status\n\n# Hardware info\ndiagnose hardware sysinfo memory\ndiagnose hardware sysinfo cpu',
   note:'Verifikasi firmware, serial number, lisensi, uptime'},

  {cat:'sys', icon:'⚙️', title:'Backup konfigurasi via CLI', desc:'Download backup konfigurasi FortiGate',
   code:'# Backup ke TFTP server\nexecute backup config tftp backup_$(date +%Y%m%d).conf 192.168.1.10\n\n# Backup ke FTP\nexecute backup config ftp backup.conf 192.168.1.10 21 ftpuser ftppass\n\n# Backup full (dengan private key)\nexecute backup full-config tftp backup_full.conf 192.168.1.10',
   note:'Ganti IP TFTP/FTP sesuai server backup Anda. Lakukan sebelum setiap perubahan besar'},

  {cat:'sys', icon:'⚙️', title:'Update firmware / FortiGuard', desc:'Cek dan update signature FortiGuard',
   code:'# Cek status update\ndiagnose autoupdate versions\n\n# Update semua service sekarang\nexecute update-now\n\n# Cek lisensi\ndiagnose license list',
   note:'Jadwalkan update di luar jam kerja untuk menghindari gangguan'},

  {cat:'sys', icon:'⚙️', title:'NTP sync manual', desc:'Sinkronisasi waktu dengan NTP server',
   code:'# Cek status NTP\ndiagnose sys ntp status\n\n# Force sync NTP\nexecute date\n\n# Konfigurasi NTP\nshow system ntp',
   note:'Waktu yang akurat penting untuk log dan sertifikat SSL'},

  {cat:'sys', icon:'⚙️', title:'Reboot / shutdown', desc:'Restart atau matikan FortiGate dengan aman',
   code:'# Reboot FortiGate\nexecute reboot\n\n# Shutdown FortiGate\nexecute shutdown\n\n# Konfirmasi: ketik \'y\' saat diminta',
   note:'⚠️ Pastikan ada downtime window. Notifikasi user sebelum reboot'},

  {cat:'sys', icon:'⚙️', title:'Log & event viewer', desc:'Lihat log sistem dan event penting',
   code:'# Log trafik terbaru\nexecute log filter category traffic\nexecute log display\n\n# Log event sistem\nexecute log filter category event\nexecute log display\n\n# Log IPS/threat\nexecute log filter category attack\nexecute log display\n\n# Reset filter\nexecute log filter reset',
   note:'Monitor log secara berkala untuk deteksi anomali'},
];

let activeFilter = 'all';

function renderScripts(filter='all', search=''){
  const container = document.getElementById('scripts-container');
  if(!container) return;
  const filtered = SCRIPTS.filter(s => {
    const matchCat = filter==='all' || s.cat===filter;
    const matchSearch = !search || 
      s.title.toLowerCase().includes(search) || 
      s.desc.toLowerCase().includes(search) ||
      s.code.toLowerCase().includes(search);
    return matchCat && matchSearch;
  });

  // Group by category
  const cats = {
    diag:{icon:'🔍',label:'Diagnostik & Monitoring',items:[]},
    user:{icon:'👥',label:'User Management',items:[]},
    sec:{icon:'🔐',label:'Security',items:[]},
    net:{icon:'🌐',label:'Network & Routing',items:[]},
    sys:{icon:'⚙️',label:'System & Maintenance',items:[]},
  };
  filtered.forEach(s => cats[s.cat].items.push(s));

  let html = '';
  Object.entries(cats).forEach(([key,cat]) => {
    if(!cat.items.length) return;
    html += `<div class="script-cat" data-cat="${key}">
      <div class="script-cat-title">${cat.icon} ${cat.label} <span style="color:var(--accent);font-weight:400">(${cat.items.length})</span></div>`;
    cat.items.forEach((s,idx) => {
      const id = `sc-${key}-${idx}`;
      html += `<div class="script-card" data-cat="${s.cat}" data-title="${s.title.toLowerCase()}" data-desc="${s.desc.toLowerCase()}">
        <div class="script-header" onclick="toggleScript('${id}')">
          <div class="script-header-left">
            <span style="font-size:16px">${s.icon}</span>
            <div>
              <div class="script-title">${s.title}</div>
              <div class="script-desc">${s.desc}</div>
            </div>
          </div>
          <div style="display:flex;align-items:center;gap:6px">
            <span class="script-tag tag-${s.cat}">${{diag:'DIAG',user:'USER',sec:'SEC',net:'NET',sys:'SYS'}[s.cat]}</span>
            <span style="font-size:14px;color:var(--text3)" id="arr-${id}">›</span>
          </div>
        </div>
        <div class="script-body" id="${id}" data-code="${escAttr(s.code)}">
          <div class="script-code">${escHtml(s.code)}</div>
          ${s.note ? `<div style="font-size:12px;color:var(--text3);margin-top:8px;padding:6px 10px;background:var(--bg3);border-radius:5px">💡 ${s.note}</div>` : ''}
          <div class="script-actions">
            <button class="script-btn script-btn-copy" onclick="copyScript(this)">📋 Copy script</button>
            <button class="script-btn script-btn-ai" onclick="askAI('${escAttr(s.title)}','${escAttr(s.desc)}')">🤖 Tanya AI</button>
          </div>
        </div>
      </div>`;
    });
    html += '</div>';
  });

  if(!html) html = '<div style="text-align:center;padding:32px;color:var(--text3)">Tidak ada script yang cocok dengan pencarian.</div>';
  container.innerHTML = html;
}

function escHtml(str){ return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function escAttr(str){ return str.replace(/'/g,'&#39;').replace(/"/g,'&quot;').replace(/\n/g,'\\n'); }

function toggleScript(id){
  const body = document.getElementById(id);
  const arr = document.getElementById('arr-'+id);
  if(body.classList.contains('open')){
    body.classList.remove('open');
    arr.textContent='›';
    arr.style.transform='';
  } else {
    body.classList.add('open');
    arr.textContent='›';
    arr.style.transform='rotate(90deg)';
  }
}

function filterCat(cat, btn){
  activeFilter = cat;
  document.querySelectorAll('.filter-btn').forEach(b=>b.classList.remove('active'));
  btn.classList.add('active');
  renderScripts(cat, document.getElementById('script-search')?.value?.toLowerCase()||'');
}

function filterScripts(){
  const search = document.getElementById('script-search').value.toLowerCase();
  renderScripts(activeFilter, search);
}

function copyScript(btn){
  const body = btn.closest('.script-body');
  const raw = body ? body.getAttribute('data-code') : '';
  const decoded = raw.replace(/\\n/g,'\n').replace(/&#39;/g,"'").replace(/&quot;/g,'"');
  // Fallback untuk HTTP (non-secure context)
  function doCopy(text){
    if(navigator.clipboard && window.isSecureContext){
      return navigator.clipboard.writeText(text);
    } else {
      const ta = document.createElement('textarea');
      ta.value = text;
      ta.style.cssText='position:fixed;left:-9999px;top:-9999px';
      document.body.appendChild(ta);
      ta.focus(); ta.select();
      document.execCommand('copy');
      document.body.removeChild(ta);
      return Promise.resolve();
    }
  }
  doCopy(decoded).then(()=>{
    btn.textContent='✅ Tersalin!';
    btn.style.background='#022C22';btn.style.color='#34D399';
    const toast = document.getElementById('copy-toast');
    if(toast) toast.style.display='block';
    setTimeout(()=>{
      btn.textContent='📋 Copy script';
      btn.style.background='';btn.style.color='';
      if(toast) toast.style.display='none';
    }, 2000);
  });
}

function askAI(title, desc){
  // Pindah ke panel AI dan isi pertanyaan
  document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
  document.querySelectorAll('.ntab').forEach(t=>t.classList.remove('active'));
  document.getElementById('p-ai').classList.add('active');
  document.querySelectorAll('.ntab').forEach(t=>{
    if(t.textContent.includes('AI')) t.classList.add('active');
  });
  const q = `Jelaskan cara menggunakan script "${title}" (${desc}) pada FortiGate Firewall ini. Berikan contoh output yang diharapkan dan cara interpretasi hasilnya.`;
  document.getElementById('ai-q').value = q;
  document.getElementById('ai-q').scrollIntoView({behavior:'smooth'});
  sendAI();
}

// Render saat tab Scripts dibuka — trigger via tab click
</script>
</body>
</html>
