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86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bot Admin</title>
<style>
:root {
  --bg:#0d0f15; --bg2:#141720; --bg3:#1c2030; --bg4:#252a3d;
  --border:#2a2f42; --border2:#353c54;
  --text:#e8eaf2; --text2:#8a91a8; --text3:#5c637a;
  --accent:#6366f1; --accent2:#818cf8;
  --success:#22c55e; --warn:#f59e0b; --error:#ef4444; --info:#3b82f6;
  --radius:8px;
}
* { box-sizing:border-box; margin:0; padding:0; }
body {
  font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
  background:var(--bg); color:var(--text); font-size:14px; line-height:1.5;
}
button {
  cursor:pointer; border:none; border-radius:var(--radius);
  font-family:inherit; font-size:13px; font-weight:500;
  padding:8px 14px; transition:all .15s;
}
button:hover { opacity:.85; }
button:disabled { opacity:.4; cursor:not-allowed; }
input, select, textarea {
  background:var(--bg3); border:1px solid var(--border);
  color:var(--text); padding:8px 12px; border-radius:var(--radius);
  font-family:inherit; font-size:13px; width:100%;
}
input:focus, select:focus, textarea:focus {
  outline:none; border-color:var(--accent);
}
.hidden { display:none !important; }
.badge {
  display:inline-block; padding:2px 8px; border-radius:4px;
  font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:.03em;
}
.badge.info { background:rgba(59,130,246,.15); color:#60a5fa; }
.badge.warn { background:rgba(245,158,11,.15); color:#fbbf24; }
.badge.error { background:rgba(239,68,68,.15); color:#f87171; }
.badge.critical { background:rgba(239,68,68,.3); color:#fca5a5; }
.badge.audit { background:rgba(99,102,241,.15); color:#a5b4fc; }
.badge.on { background:rgba(34,197,94,.15); color:#4ade80; }
.badge.off { background:rgba(107,114,128,.15); color:#9ca3af; }

/* ---------- Login ---------- */
.login {
  min-height:100vh; display:flex; align-items:center; justify-content:center;
  background:radial-gradient(circle at 50% 30%, rgba(99,102,241,.12), transparent 60%);
}
.login-box {
  background:var(--bg2); border:1px solid var(--border); border-radius:12px;
  padding:36px; width:100%; max-width:380px; text-align:center;
}
.login-box h1 { font-size:22px; margin-bottom:6px; }
.login-box p { color:var(--text2); font-size:12px; margin-bottom:22px; }
.login-box input { margin-bottom:12px; text-align:center; }
.login-box button { width:100%; background:var(--accent); color:#fff; padding:10px; font-size:14px; }
.err { color:var(--error); font-size:12px; min-height:16px; margin-top:8px; }

/* ---------- Layout ---------- */
.app { display:flex; min-height:100vh; }
.sidebar {
  width:220px; background:var(--bg2); border-right:1px solid var(--border);
  padding:20px 0; position:fixed; top:0; bottom:0; overflow-y:auto;
  display:flex; flex-direction:column;
}
.brand { padding:0 20px 20px; font-size:16px; font-weight:700; border-bottom:1px solid var(--border); margin-bottom:12px; }
.nav { flex:1; }
.nav a {
  display:flex; align-items:center; gap:10px; padding:10px 20px;
  color:var(--text2); text-decoration:none; font-size:13px; cursor:pointer;
  border-left:3px solid transparent; transition:all .15s;
}
.nav a:hover { background:var(--bg3); color:var(--text); }
.nav a.active { background:var(--bg3); color:var(--accent2); border-left-color:var(--accent); }
.logout-btn { margin:12px 20px 0; background:var(--bg4); color:var(--text); }
.main { flex:1; margin-left:220px; padding:20px 28px; max-width:calc(100vw - 220px); }
header {
  display:flex; justify-content:space-between; align-items:center;
  padding-bottom:16px; margin-bottom:20px; border-bottom:1px solid var(--border);
}
header h1 { font-size:20px; }
.header-actions { display:flex; gap:10px; align-items:center; }

/* ---------- Cards ---------- */
.cards { display:grid; grid-template-columns:repeat(auto-fit, minmax(160px,1fr)); gap:14px; margin-bottom:24px; }
.card {
  background:var(--bg2); border:1px solid var(--border);
  border-radius:var(--radius); padding:16px;
}
.card .label { color:var(--text2); font-size:11px; text-transform:uppercase; letter-spacing:.05em; margin-bottom:6px; }
.card .value { font-size:24px; font-weight:700; }
.card .value.sm { font-size:18px; }

/* ---------- Charts ---------- */
.chart-row { display:grid; grid-template-columns:2fr 1fr; gap:16px; margin-bottom:20px; }
.chart-box { background:var(--bg2); border:1px solid var(--border); border-radius:var(--radius); padding:16px; }
.chart-box h3 { font-size:13px; color:var(--text2); margin-bottom:12px; text-transform:uppercase; letter-spacing:.05em; }
.bars { display:flex; align-items:flex-end; gap:6px; height:140px; }
.bar-wrap { flex:1; display:flex; flex-direction:column; justify-content:flex-end; align-items:center; height:100%; }
.bar { width:100%; background:linear-gradient(to top, var(--accent), var(--accent2)); border-radius:3px 3px 0 0; min-height:2px; }
.bar-label { font-size:10px; color:var(--text3); margin-top:6px; }
.target-list .row { display:flex; justify-content:space-between; padding:6px 0; border-bottom:1px solid var(--border); font-size:12px; }
.target-list .row:last-child { border-bottom:none; }
.target-list .target { font-family:monospace; color:var(--text); }
.target-list .count { color:var(--accent2); font-weight:600; }

/* ---------- Tables ---------- */
table { width:100%; border-collapse:collapse; background:var(--bg2); border-radius:var(--radius); overflow:hidden; }
th, td { padding:10px 12px; text-align:left; font-size:13px; border-bottom:1px solid var(--border); }
th { background:var(--bg3); color:var(--text2); font-weight:600; font-size:11px; text-transform:uppercase; letter-spacing:.05em; }
tr:hover td { background:var(--bg3); }
tr.user-row { cursor:pointer; }
td.mono, .mono { font-family:'SF Mono', Menlo, monospace; font-size:12px; }
.actions-cell { display:flex; gap:4px; flex-wrap:wrap; }
.btn-sm { padding:4px 8px; font-size:11px; }
.btn-primary { background:var(--accent); color:#fff; }
.btn-danger { background:var(--error); color:#fff; }
.btn-warn { background:var(--warn); color:#000; }
.btn-success { background:var(--success); color:#000; }
.btn-ghost { background:var(--bg3); color:var(--text); }

/* ---------- Forms ---------- */
.form-row { display:flex; gap:10px; margin-bottom:14px; align-items:center; flex-wrap:wrap; }
.form-row label { color:var(--text2); font-size:12px; min-width:80px; }
.form-row input, .form-row select { flex:1; min-width:120px; }
textarea { resize:vertical; min-height:100px; }

/* ---------- Logs ---------- */
.log-controls { display:flex; gap:10px; margin-bottom:14px; flex-wrap:wrap; align-items:center; }
.log-controls input, .log-controls select { flex:1; min-width:120px; }
.log-table-wrap { max-height:calc(100vh - 280px); overflow-y:auto; border:1px solid var(--border); border-radius:var(--radius); }
.log-table { font-size:12px; }
.log-table td { padding:6px 10px; }
.log-table .level-cell { text-align:center; }
.log-row.info { }
.log-row.warn td { background:rgba(245,158,11,.04); }
.log-row.error td, .log-row.critical td { background:rgba(239,68,68,.06); }
.log-row.audit td { background:rgba(99,102,241,.05); }

/* ---------- Drawer ---------- */
.drawer-bg {
  position:fixed; inset:0; background:rgba(0,0,0,.6); z-index:100;
  display:none;
}
.drawer-bg.open { display:block; }
.drawer {
  position:fixed; top:0; right:0; bottom:0; width:min(560px, 100vw);
  background:var(--bg2); border-left:1px solid var(--border);
  z-index:101; display:flex; flex-direction:column;
  transform:translateX(100%); transition:transform .2s;
}
.drawer.open { transform:translateX(0); }
.drawer-head { padding:20px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; }
.drawer-body { flex:1; overflow-y:auto; padding:20px; }
.drawer-foot { padding:16px 20px; border-top:1px solid var(--border); background:var(--bg3); }
.sec-title { font-size:11px; color:var(--text2); text-transform:uppercase; letter-spacing:.05em; margin:20px 0 10px; }
.sec-title:first-child { margin-top:0; }
.kv { display:grid; grid-template-columns:120px 1fr; gap:6px 12px; font-size:13px; }
.kv dt { color:var(--text2); }
.kv dd { color:var(--text); }

/* ---------- Toast ---------- */
#toast {
  position:fixed; bottom:24px; right:24px; padding:12px 20px;
  background:var(--bg4); border:1px solid var(--border2); border-radius:var(--radius);
  color:var(--text); font-size:13px; z-index:200;
  opacity:0; transform:translateY(10px); transition:all .2s;
  pointer-events:none; max-width:320px;
}
#toast.show { opacity:1; transform:translateY(0); }
#toast.ok { border-color:var(--success); }
#toast.err { border-color:var(--error); }

/* ---------- Modal ---------- */
.modal-bg {
  position:fixed; inset:0; background:rgba(0,0,0,.7); z-index:300;
  display:none; align-items:center; justify-content:center;
}
.modal-bg.open { display:flex; }
.modal {
  background:var(--bg2); border:1px solid var(--border2); border-radius:12px;
  padding:24px; width:100%; max-width:440px;
}
.modal h3 { margin-bottom:8px; }
.modal p { color:var(--text2); font-size:13px; margin-bottom:18px; }
.modal input { margin-bottom:12px; }
.modal-actions { display:flex; gap:10px; justify-content:flex-end; margin-top:16px; }

@media (max-width:800px) {
  .sidebar { width:60px; }
  .brand, .nav a span:not(.nav-icon) { display:none; }
  .nav a { justify-content:center; padding:12px 0; }
  .main { margin-left:60px; max-width:calc(100vw - 60px); padding:16px; }
  .chart-row { grid-template-columns:1fr; }
}
</style>
</head>
<body>

<!-- ============ LOGIN ============ -->
<div id="login" class="login">
  <div class="login-box">
    <h1>🤖 Bot Admin</h1>
    <p>Enter your admin password</p>
    <input id="pwd" type="password" placeholder="Password" onkeydown="if(event.key==='Enter')doLogin()">
    <button onclick="doLogin()">Login</button>
    <div id="loginErr" class="err"></div>
  </div>
</div>

<!-- ============ APP ============ -->
<div id="app" class="app hidden">
  <aside class="sidebar">
    <div class="brand">🤖 Bot Admin</div>
    <nav class="nav">
      <a onclick="showTab('dashboard')" class="active" data-tab="dashboard"><span class="nav-icon">📊</span><span>Dashboard</span></a>
      <a onclick="showTab('users')" data-tab="users"><span class="nav-icon">👥</span><span>Users</span></a>
      <a onclick="showTab('logs')" data-tab="logs"><span class="nav-icon">📜</span><span>Live Logs</span></a>
      <a onclick="showTab('audit')" data-tab="audit"><span class="nav-icon">🔍</span><span>Audit</span></a>
      <a onclick="showTab('broadcast')" data-tab="broadcast"><span class="nav-icon">📢</span><span>Broadcast</span></a>
      <a onclick="showTab('system')" data-tab="system"><span class="nav-icon">⚙️</span><span>System</span></a>
    </nav>
    <button class="logout-btn" onclick="logout()">Logout</button>
  </aside>

  <main class="main">
    <header>
      <h1 id="pageTitle">Dashboard</h1>
      <div class="header-actions">
        <span id="maintBadge" class="badge off">Maintenance: ?</span>
        <span id="meBadge" class="badge info">admin</span>
      </div>
    </header>

    <!-- DASHBOARD -->
    <section id="tab-dashboard" class="tab">
      <div class="cards" id="statCards"></div>
      <div class="chart-row">
        <div class="chart-box">
          <h3>Attacks · last 7 days</h3>
          <div id="tsChart" class="bars"></div>
        </div>
        <div class="chart-box">
          <h3>Top targets</h3>
          <div id="targetsList" class="target-list"></div>
        </div>
      </div>
    </section>

    <!-- USERS -->
    <section id="tab-users" class="tab hidden">
      <div class="form-row">
        <input id="userSearch" placeholder="Search ID or username..." oninput="loadUsers()">
        <select id="userFilter" onchange="loadUsers()">
          <option value="">All users</option>
          <option value="banned=1">Banned only</option>
          <option value="vip=1">VIP only</option>
        </select>
        <button class="btn-ghost" onclick="loadUsers()">Refresh</button>
      </div>
      <div class="log-table-wrap">
        <table class="log-table">
          <thead><tr>
            <th>ID</th><th>Username</th><th>Status</th><th>Daily</th>
            <th>Attacks</th><th>Last seen</th><th>Actions</th>
          </tr></thead>
          <tbody id="usersTbody"></tbody>
        </table>
      </div>
    </section>

    <!-- LOGS -->
    <section id="tab-logs" class="tab hidden">
      <div class="log-controls">
        <input id="logSearch" placeholder="Search data..." oninput="resetLogs(); startLogPolling()">
        <select id="logLevel" onchange="resetLogs(); startLogPolling()">
          <option value="">All levels</option>
          <option value="info">info</option>
          <option value="warn">warn</option>
          <option value="error">error</option>
          <option value="critical">critical</option>
          <option value="audit">audit</option>
        </select>
        <select id="logEvent" onchange="resetLogs(); startLogPolling()">
          <option value="">All events</option>
          <option value="attack_start">attack_start</option>
          <option value="attack_ok">attack_ok</option>
          <option value="attack_fail">attack_fail</option>
          <option value="command">command</option>
          <option value="callback">callback</option>
          <option value="new_user">new_user</option>
          <option value="ban">ban</option>
          <option value="warn">warn</option>
          <option value="admin_login">admin_login</option>
        </select>
        <button id="logPauseBtn" class="btn-ghost" onclick="toggleLogPause()">⏸ Pause</button>
        <button class="btn-ghost" onclick="exportLogs()">⬇ Export CSV</button>
      </div>
      <div class="log-table-wrap">
        <table class="log-table">
          <thead><tr>
            <th style="width:80px">Time</th>
            <th style="width:80px">User</th>
            <th style="width:130px">Event</th>
            <th style="width:80px">Level</th>
            <th>Data</th>
          </tr></thead>
          <tbody id="logsTbody"></tbody>
        </table>
      </div>
    </section>

    <!-- AUDIT -->
    <section id="tab-audit" class="tab hidden">
      <div class="log-controls">
        <button class="btn-ghost" onclick="loadAudit()">Refresh</button>
        <span style="color:var(--text2); font-size:12px">All admin actions (bans, toggles, broadcasts, logins)</span>
      </div>
      <div class="log-table-wrap">
        <table class="log-table">
          <thead><tr>
            <th style="width:80px">Time</th>
            <th style="width:80px">Admin</th>
            <th style="width:140px">Action</th>
            <th>Details</th>
          </tr></thead>
          <tbody id="auditTbody"></tbody>
        </table>
      </div>
    </section>

    <!-- BROADCAST -->
    <section id="tab-broadcast" class="tab hidden">
      <div class="chart-box" style="max-width:640px">
        <h3>Send broadcast</h3>
        <textarea id="bcText" placeholder="Message text (HTML allowed)" style="min-height:140px; margin-bottom:14px"></textarea>
        <div class="form-row">
          <label>Filter</label>
          <select id="bcFilter">
            <option value="all">All users</option>
            <option value="nonbanned">Non-banned</option>
            <option value="vip">VIP only</option>
          </select>
        </div>
        <button class="btn-primary" onclick="doBroadcast()" style="width:100%; margin-top:8px">📢 Send Broadcast</button>
        <p id="bcStatus" style="color:var(--text2); font-size:12px; margin-top:10px"></p>
      </div>
    </section>

    <!-- SYSTEM -->
    <section id="tab-system" class="tab hidden">
      <div class="chart-row" style="grid-template-columns:1fr 1fr">
        <div class="chart-box">
          <h3>Health</h3>
          <div id="sysHealth">Loading...</div>
          <button class="btn-ghost" onclick="loadHealth()" style="margin-top:12px">Refresh</button>
        </div>
        <div class="chart-box">
          <h3>Webhook</h3>
          <div id="sysWebhook">Loading...</div>
          <div class="form-row" style="margin-top:12px">
            <input id="whUrl" placeholder="https://.../webhook">
            <button class="btn-ghost" onclick="setWebhook()">Set</button>
          </div>
        </div>
      </div>
      <div class="chart-box" style="margin-top:16px">
        <h3>Actions</h3>
        <div class="actions-cell">
          <button class="btn-ghost" onclick="testLog()">🧪 Test Log Channel</button>
          <button class="btn-ghost" onclick="exportUsers()">⬇ Export Users</button>
        </div>
      </div>
    </section>
  </main>
</div>

<!-- Drawer -->
<div id="drawerBg" class="drawer-bg" onclick="closeDrawer()"></div>
<div id="drawer" class="drawer">
  <div class="drawer-head">
    <h2 id="drawerTitle">User</h2>
    <button class="btn-ghost btn-sm" onclick="closeDrawer()">✕</button>
  </div>
  <div class="drawer-body" id="drawerBody"></div>
  <div class="drawer-foot" id="drawerFoot"></div>
</div>

<!-- Modal -->
<div id="modalBg" class="modal-bg">
  <div class="modal">
    <h3 id="modalTitle">Confirm</h3>
    <p id="modalText"></p>
    <input id="modalInput" placeholder="" class="hidden">
    <div class="modal-actions">
      <button class="btn-ghost" onclick="closeModal()">Cancel</button>
      <button id="modalConfirm" class="btn-primary" onclick="modalOK()">Confirm</button>
    </div>
  </div>
</div>

<!-- Toast -->
<div id="toast"></div>

<script>
// ==================== CONFIG ====================
const API = "/api/admin";
let TOKEN = localStorage.getItem("adminToken") || "";
let _modalResolve = null;

// ==================== HELPERS ====================
function $(id) { return document.getElementById(id); }
function esc(s) {
  return String(s ?? "").replace(/[&<>"']/g, c => ({
    '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
  }[c]));
}
function fmtTime(ts) {
  if (!ts) return '—';
  const d = new Date(ts * 1000);
  return d.toLocaleString('en-US', {month:'short', day:'2-digit', hour:'2-digit', minute:'2-digit', second:'2-digit'});
}
function relTime(ts) {
  if (!ts) return 'never';
  const s = Math.floor(Date.now()/1000 - ts);
  if (s < 60) return s + 's ago';
  if (s < 3600) return Math.floor(s/60) + 'm ago';
  if (s < 86400) return Math.floor(s/3600) + 'h ago';
  return Math.floor(s/86400) + 'd ago';
}
function toast(msg, type='') {
  const el = $('toast');
  el.textContent = msg;
  el.className = 'show ' + type;
  setTimeout(() => el.className = '', 2600);
}

async function api(path, opts={}) {
  const headers = { "Content-Type": "application/json", ...(opts.headers||{}) };
  if (TOKEN) headers["Authorization"] = "Bearer " + TOKEN;
  const res = await fetch(API + path, {
    method: opts.method || "GET",
    headers,
    body: opts.body ? JSON.stringify(opts.body) : undefined,
  });
  if (res.status === 401) { logout(); throw new Error("unauthorized"); }
  if (!res.ok) {
    let msg = await res.text();
    try { msg = JSON.parse(msg).detail || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

// ==================== AUTH ====================
async function doLogin() {
  const pw = $('pwd').value;
  $('loginErr').textContent = '';
  if (!pw) return;
  try {
    const r = await api('/login', {method:'POST', body:{password:pw}});
    TOKEN = r.token;
    localStorage.setItem('adminToken', TOKEN);
    startApp();
  } catch(e) {
    $('loginErr').textContent = e.message;
  }
}
function logout() {
  TOKEN = '';
  localStorage.removeItem('adminToken');
  $('app').classList.add('hidden');
  $('login').classList.remove('hidden');
}
function startApp() {
  $('login').classList.add('hidden');
  $('app').classList.remove('hidden');
  showTab('dashboard');
  refreshMaint();
  setInterval(refreshMaint, 20000);
}

// Token from URL ?t=
(function checkUrlToken() {
  const url = new URL(location.href);
  const t = url.searchParams.get('t');
  if (t) {
    TOKEN = t;
    localStorage.setItem('adminToken', TOKEN);
    url.searchParams.delete('t');
    history.replaceState(null, '', url);
  }
})();

// Try to start
(async function boot() {
  if (!TOKEN) return;
  try {
    await api('/me');
    startApp();
  } catch { /* show login */ }
})();

// ==================== TABS ====================
const TITLES = {dashboard:'Dashboard', users:'Users', logs:'Live Logs', audit:'Audit Log', broadcast:'Broadcast', system:'System'};
let currentTab = 'dashboard';
function showTab(name) {
  currentTab = name;
  document.querySelectorAll('.tab').forEach(t => t.classList.add('hidden'));
  document.querySelectorAll('.nav a').forEach(a => a.classList.toggle('active', a.dataset.tab === name));
  $('tab-' + name).classList.remove('hidden');
  $('pageTitle').textContent = TITLES[name] || name;
  if (name === 'dashboard') loadDashboard();
  if (name === 'users') loadUsers();
  if (name === 'logs') { resetLogs(); startLogPolling(); } else stopLogPolling();
  if (name === 'audit') loadAudit();
  if (name === 'system') { loadHealth(); loadWebhookInfo(); }
}

// ==================== MAINT ====================
async function refreshMaint() {
  try {
    const r = await api('/maintenance');
    const b = $('maintBadge');
    b.textContent = r.maintenance ? "Maintenance: ON" : "Maintenance: OFF";
    b.className = 'badge ' + (r.maintenance ? 'warn' : 'off');
    b.style.cursor = 'pointer';
    b.onclick = () => toggleMaintenance(!r.maintenance);
  } catch {}
}
async function toggleMaintenance(v) {
  try {
    await api('/maintenance', {method:'POST', body:{value: v}});
    toast("Maintenance " + (v ? "ON" : "OFF"), "ok");
    refreshMaint();
  } catch(e) { toast(e.message, "err"); }
}

// ==================== DASHBOARD ====================
async function loadDashboard() {
  try {
    const [stats, ts, targets] = await Promise.all([
      api('/stats'), api('/stats/timeseries?days=7'), api('/stats/targets?limit=5')
    ]);
    $('statCards').innerHTML = [
      ['Users', stats.users_total, ''],
      ['Active 24h', stats.active_24h, ''],
      ['Banned', stats.banned, ''],
      ['VIP', stats.vip, ''],
      ['Attacks 24h', stats.attacks_24h, ''],
      ['Msgs 24h', stats.msgs_24h, ''],
    ].map(([l, v]) => `<div class="card"><div class="label">${l}</div><div class="value">${v}</div></div>`).join('');

    const max = Math.max(1, ...ts.map(t => t.count));
    $('tsChart').innerHTML = ts.length
      ? ts.map(t => {
          const h = Math.max(4, (t.count / max) * 100);
          const lbl = new Date(t.date).toLocaleDateString('en-US', {month:'short', day:'numeric'});
          return `<div class="bar-wrap" title="${lbl}: ${t.count}">
            <div class="bar" style="height:${h}%"></div>
            <div class="bar-label">${lbl}</div>
          </div>`;
        }).join('')
      : '<div style="color:var(--text2); align-self:center; width:100%; text-align:center">No data yet</div>';

    $('targetsList').innerHTML = targets.length
      ? targets.map(t => `<div class="row"><span class="target">${esc(t.target || '?')}</span><span class="count">${t.count}</span></div>`).join('')
      : '<div style="color:var(--text2); font-size:12px">No attacks yet</div>';
  } catch(e) { toast(e.message, "err"); }
}

// ==================== USERS ====================
async function loadUsers() {
  const q = $('userSearch').value.trim();
  const filter = $('userFilter').value;
  try {
    const r = await api(`/users?q=${encodeURIComponent(q)}&${filter}`);
    const tb = $('usersTbody');
    if (!r.users.length) {
      tb.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text2); padding:30px">No users</td></tr>';
      return;
    }
    tb.innerHTML = r.users.map(u => {
      const status = u.banned ? '<span class="badge error">Banned</span>'
        : u.is_vip ? '<span class="badge warn">VIP</span>'
        : '<span class="badge info">User</span>';
      return `<tr class="user-row" onclick="openUser(${u.id})">
        <td class="mono">${u.id}</td>
        <td>${esc(u.username || '—')}</td>
        <td>${status}</td>
        <td>${u.daily_requests}/5</td>
        <td>${u.stats?.requests ?? 0}</td>
        <td>${relTime(u.last_attack_time)}</td>
        <td class="actions-cell" onclick="event.stopPropagation()">
          ${u.banned
            ? `<button class="btn-sm btn-success" onclick="userAction(${u.id}, 'unban', {})">Unban</button>`
            : `<button class="btn-sm btn-danger" onclick="userAction(${u.id}, 'ban', {reason: prompt('Reason')})">Ban</button>`}
          <button class="btn-sm btn-ghost" onclick="openUser(${u.id})">Open</button>
        </td>
      </tr>`;
    }).join('');
  } catch(e) { toast(e.message, "err"); }
}

async function openUser(uid) {
  try {
    const r = await api('/users/' + uid);
    const u = r.user;
    $('drawerTitle').textContent = `User ${uid}`;
    const recs = r.recent.slice(0, 40).map(x => `
      <div style="padding:6px 0; border-bottom:1px solid var(--border); font-size:12px">
        <span style="color:var(--text3); font-family:monospace">${new Date(x.ts*1000).toLocaleTimeString()}</span>
        <span class="badge ${x.level}" style="margin:0 6px">${x.event}</span>
        <span style="color:var(--text2)">${esc(JSON.stringify(x.data).slice(0,120))}</span>
      </div>`).join('');
    $('drawerBody').innerHTML = `
      <dl class="kv">
        <dt>Username</dt><dd>${esc(u.username || '—')}</dd>
        <dt>Status</dt><dd>${u.banned ? '🚫 Banned — ' + esc(u.ban_reason||'') : u.is_vip ? '👑 VIP' : '👤 Standard'}</dd>
        <dt>Warnings</dt><dd>${u.warnings}/3</dd>
        <dt>Attacks</dt><dd>${u.stats?.requests ?? 0}</dd>
        <dt>Messages</dt><dd>${u.stats?.sent ?? 0}</dd>
        <dt>Daily</dt><dd>${u.daily_requests}/5</dd>
        <dt>Last attack</dt><dd>${relTime(u.last_attack_time)}</dd>
        <dt>Last claim</dt><dd>${relTime(u.claim_time)}</dd>
        <dt>Admin</dt><dd>${u.is_admin ? 'yes' : 'no'}</dd>
      </dl>
      <div class="sec-title">Recent activity</div>
      <div>${recs || '<div style="color:var(--text2)">No activity</div>'}</div>
    `;
    $('drawerFoot').innerHTML = `
      <div class="actions-cell">
        <button class="btn-sm btn-ghost" onclick="userAction(${uid}, 'vip', {value: ${!u.is_vip}})">
          ${u.is_vip ? '❌ Remove VIP' : '👑 Make VIP'}
        </button>
        <button class="btn-sm btn-warn" onclick="userAction(${uid}, 'warn', {reason: prompt('Reason') || 'No reason'})">⚠ Warn</button>
        <button class="btn-sm btn-ghost" onclick="userAction(${uid}, 'message', {text: prompt('Message to user')})">💬 DM</button>
        <button class="btn-sm btn-ghost" onclick="userAction(${uid}, 'reset-cooldown', {})">Reset CD</button>
        <button class="btn-sm btn-ghost" onclick="userAction(${uid}, 'reset-daily', {})">Reset daily</button>
        <button class="btn-sm btn-ghost" onclick="userAction(${uid}, 'clear-state', {})">Clear state</button>
        ${u.banned
          ? `<button class="btn-sm btn-success" onclick="userAction(${uid}, 'unban', {})">Unban</button>`
          : `<button class="btn-sm btn-danger" onclick="userAction(${uid}, 'ban', {reason: prompt('Reason') || 'No reason'})">Ban</button>`}
        <button class="btn-sm btn-danger" onclick="deleteUser(${uid})">Delete</button>
      </div>`;
    $('drawerBg').classList.add('open');
    $('drawer').classList.add('open');
  } catch(e) { toast(e.message, "err"); }
}

function closeDrawer() {
  $('drawerBg').classList.remove('open');
  $('drawer').classList.remove('open');
}

async function userAction(uid, action, body) {
  if (action === 'message' && (!body.text)) return;
  if (action === 'warn' && !body.reason) return;
  try {
    await api(`/users/${uid}/${action}`, {method:'POST', body});
    toast('✓ ' + action, 'ok');
    loadUsers();
    if ($('drawer').classList.contains('open')) openUser(uid);
  } catch(e) { toast(e.message, 'err'); }
}

async function deleteUser(uid) {
  const ok = await confirmModal("Delete user?", "This cannot be undone. Type DELETE to confirm.", "DELETE");
  if (!ok) return;
  try {
    await api('/users/' + uid, {method:'DELETE', body:{confirm:'DELETE'}});
    toast('✓ deleted', 'ok');
    closeDrawer(); loadUsers();
  } catch(e) { toast(e.message, 'err'); }
}

// ==================== LOGS ====================
let lastLogId = 0;
let logPaused = false;
let logTimer = null;

function resetLogs() {
  lastLogId = 0;
  $('logsTbody').innerHTML = '';
}

function stopLogPolling() {
  if (logTimer) { clearTimeout(logTimer); logTimer = null; }
}

function startLogPolling() {
  stopLogPolling();
  if (logPaused) return;
  pollLogs();
}

async function pollLogs() {
  if (currentTab !== 'logs') return;
  try {
    const q = $('logSearch').value.trim();
    const lvl = $('logLevel').value;
    const ev = $('logEvent').value;
    const params = new URLSearchParams();
    if (lastLogId === 0) {
      // first load: get recent 100
      if (lvl) params.set('level', lvl);
      if (ev) params.set('event', ev);
      if (q) params.set('q', q);
      params.set('per_page', 100);
      const rows = await api('/logs?' + params);
      rows.reverse().forEach(appendLogRow);
      if (rows.length) lastLogId = Math.max(...rows.map(r => r.id));
    } else {
      const rows = await api('/logs/stream?since_id=' + lastLogId);
      const filtered = rows.filter(r => {
        if (lvl && r.level !== lvl) return false;
        if (ev && r.event !== ev) return false;
        if (q && !JSON.stringify(r.data).toLowerCase().includes(q.toLowerCase())) return false;
        return true;
      });
      filtered.forEach(appendLogRow);
      if (rows.length) lastLogId = Math.max(lastLogId, ...rows.map(r => r.id));
    }
  } catch(e) { console.error(e); }
  logTimer = setTimeout(pollLogs, 3000);
}

function appendLogRow(r) {
  const tb = $('logsTbody');
  const tr = document.createElement('tr');
  tr.className = 'log-row ' + r.level;
  const data = JSON.stringify(r.data).slice(0, 220);
  tr.innerHTML = `
    <td class="mono" style="color:var(--text3)">${new Date(r.ts*1000).toLocaleTimeString()}</td>
    <td class="mono">${r.user_id || '—'}</td>
    <td>${esc(r.event)}</td>
    <td><span class="badge ${r.level}">${r.level}</span></td>
    <td class="mono" style="color:var(--text2)">${esc(data)}</td>
  `;
  tb.insertBefore(tr, tb.firstChild);
  // cap rows
  while (tb.children.length > 300) tb.removeChild(tb.lastChild);
}

function toggleLogPause() {
  logPaused = !logPaused;
  $('logPauseBtn').textContent = logPaused ? '▶ Resume' : '⏸ Pause';
  if (logPaused) stopLogPolling(); else startLogPolling();
}

async function exportLogs() {
  const w = window.open('about:blank');
  const res = await fetch(API + '/logs/export', {headers:{Authorization:'Bearer '+TOKEN}});
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = 'logs.csv'; a.click();
  URL.revokeObjectURL(url);
}

// ==================== AUDIT ====================
async function loadAudit() {
  try {
    const rows = await api('/audit');
    const tb = $('auditTbody');
    if (!rows.length) {
      tb.innerHTML = '<tr><td colspan="4" style="text-align:center; color:var(--text2); padding:30px">No admin actions yet</td></tr>';
      return;
    }
    tb.innerHTML = rows.map(r => `
      <tr class="log-row audit">
        <td class="mono" style="color:var(--text3)">${new Date(r.ts*1000).toLocaleTimeString()}</td>
        <td class="mono">${r.admin_id || '—'}</td>
        <td><b>${esc(r.event)}</b></td>
        <td class="mono" style="color:var(--text2)">${esc(JSON.stringify(r.data).slice(0, 200))}</td>
      </tr>`).join('');
  } catch(e) { toast(e.message, 'err'); }
}

// ==================== BROADCAST ====================
async function doBroadcast() {
  const text = $('bcText').value.trim();
  if (!text) { toast('Empty message', 'err'); return; }
  const filter = $('bcFilter').value;
  const ok = await confirmModal('Send broadcast?', `This will message users matching filter "${filter}". Continue?`);
  if (!ok) return;
  $('bcStatus').textContent = 'Sending...';
  try {
    const r = await api('/broadcast', {method:'POST', body:{text, filter}});
    $('bcStatus').textContent = `✓ Sent to ${r.sent} / ${r.targeted}`;
    toast('Broadcast sent', 'ok');
  } catch(e) { toast(e.message, 'err'); $('bcStatus').textContent = ''; }
}

// ==================== SYSTEM ====================
async function loadHealth() {
  try {
    const r = await api('/health');
    $('sysHealth').innerHTML = r.ok
      ? `<span class="badge on">online</span><pre class="mono" style="font-size:11px; margin-top:8px; color:var(--text2); overflow:auto">${esc(JSON.stringify(r.data, null, 2))}</pre>`
      : `<span class="badge error">offline</span><div style="color:var(--error); font-size:12px; margin-top:6px">${esc(r.error)}</div>`;
  } catch(e) { $('sysHealth').innerHTML = '<span class="badge error">error</span>'; }
}

async function loadWebhookInfo() {
  try {
    const r = await api('/bot/webhook-info');
    $('sysWebhook').innerHTML = `
      <dl class="kv" style="font-size:12px">
        <dt>URL</dt><dd class="mono">${esc(r.url || '(none)')}</dd>
        <dt>Pending</dt><dd>${r.pending_update_count}</dd>
        <dt>Last error</dt><dd>${r.last_error_message ? esc(r.last_error_message) : '—'}</dd>
      </dl>`;
    $('whUrl').value = r.url || '';
  } catch(e) { $('sysWebhook').innerHTML = '<span class="badge error">error</span>'; }
}

async function setWebhook() {
  const url = $('whUrl').value.trim();
  if (!url) return;
  try {
    await api('/bot/set-webhook', {method:'POST', body:{url}});
    toast('Webhook set', 'ok');
    loadWebhookInfo();
  } catch(e) { toast(e.message, 'err'); }
}

async function testLog() {
  try {
    await api('/bot/test-log', {method:'POST'});
    toast('Sent to log channel', 'ok');
  } catch(e) { toast(e.message, 'err'); }
}

async function exportUsers() {
  const res = await fetch(API + '/users?per_page=10000', {headers:{Authorization:'Bearer '+TOKEN}});
  const data = await res.json();
  const blob = new Blob([JSON.stringify(data, null, 2)], {type:'application/json'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href = url; a.download = 'users.json'; a.click();
  URL.revokeObjectURL(url);
}

// ==================== MODAL ====================
function confirmModal(title, text, requireInput = null) {
  return new Promise(resolve => {
    $('modalTitle').textContent = title;
    $('modalText').textContent = text;
    const inp = $('modalInput');
    if (requireInput) {
      inp.classList.remove('hidden');
      inp.value = '';
      inp.placeholder = `Type "${requireInput}" to confirm`;
    } else {
      inp.classList.add('hidden');
    }
    $('modalBg').classList.add('open');
    _modalResolve = (val) => {
      if (requireInput && inp.value !== requireInput) return;
      resolve(val);
      closeModal();
    };
  });
}
function modalOK() { if (_modalResolve) _modalResolve(true); }
function closeModal() {
  $('modalBg').classList.remove('open');
  _modalResolve = null;
}

// auto-refresh dashboard every 30s
setInterval(() => { if (currentTab === 'dashboard' && TOKEN) loadDashboard(); }, 30000);
</script>
</body>
</html>