Spaces:
Running

File size: 53,442 Bytes
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ADMIN_TABS, AdminTabId, ROUTES } from '@/shared/constants/routes';
import { formatDateVi } from '@/shared/lib/format';
import { useToast } from '@/shared/hooks/useToast';
import { Button } from '@/shared/components/Button';
import { Badge, Card, MetricTile, Skeleton } from '@/shared/components/Card';
import { Input, Select, Textarea } from '@/shared/components/Input';
import { ConfirmModal, Modal } from '@/shared/components/Modal';
import { useAuthSession } from '@/features/auth';
import { PtyTerminalView } from '@/features/terminal';
import { useWorkspaceStore } from '@/features/workspace';
import {
  Activity,
  ChevronDown,
  ChevronUp,
  Cpu,
  Download,
  ExternalLink,
  FileText,
  FlaskConical,
  Globe,
  HardDrive,
  KeyRound,
  Layers,
  Mail,
  Play,
  Plus,
  RefreshCw,
  Search,
  Send,
  Settings,
  Share2,
  Shield,
  Square,
  Terminal,
  Trash2,
  Users,
} from 'lucide-react';
import { validatePasswordChange } from '../schemas/adminSchema';
import { adminService } from '../services/adminService';
import {
  AdminContactListResponse,
  AdminOverview,
  AdminSiteInfo,
  AdminTelemetry,
  AdminUserRow,
  AdminZonesResponse,
  BypassStatus,
  DEFAULT_ADMIN_SITE_INFO,
} from '../types/adminTypes';

export function AdminConsoleView({ section }: { section: AdminTabId }) {
  const router = useRouter();
  const { user } = useAuthSession();
  const { selectZone, refreshZones } = useWorkspaceStore();
  const { pushToast } = useToast();

  const [loading, setLoading] = useState(true);
  const [overview, setOverview] = useState<AdminOverview | null>(null);
  const [telemetry, setTelemetry] = useState<AdminTelemetry | null>(null);
  const [bypassStatus, setBypassStatus] = useState<BypassStatus | null>(null);
  const [users, setUsers] = useState<AdminUserRow[]>([]);
  const [zonesData, setZonesData] = useState<AdminZonesResponse | null>(null);
  const [contactsData, setContactsData] = useState<AdminContactListResponse | null>(null);
  const [siteInfo, setSiteInfo] = useState<AdminSiteInfo>(DEFAULT_ADMIN_SITE_INFO);

  // Local UI controls
  const [userSearch, setUserSearch] = useState('');
  const [zoneSearch, setZoneSearch] = useState('');
  const [zoneFilter, setZoneFilter] = useState<'all' | 'with_zones' | 'running' | 'unassigned'>('all');
  const [contactFilter, setContactFilter] = useState<'all' | 'pending' | 'replied'>('all');
  const [replyDrafts, setReplyDrafts] = useState<Record<string, string>>({});
  const [replyBusyId, setReplyBusyId] = useState<string | null>(null);

  // Bypass console
  const [bypassBusy, setBypassBusy] = useState<string | null>(null);
  const [consoleTitle, setConsoleTitle] = useState('Sẵn sàng');
  const [consoleOutput, setConsoleOutput] = useState('');
  const [consoleOk, setConsoleOk] = useState<boolean | null>(null);
  const [showMetrics, setShowMetrics] = useState(false);

  // Forms in Settings
  const [motd, setMotd] = useState('');
  const [maxZones, setMaxZones] = useState(0);
  const [disableReg, setDisableReg] = useState(false);
  const [savingSettings, setSavingSettings] = useState(false);
  const [savingSite, setSavingSite] = useState(false);

  const [curPw, setCurPw] = useState('');
  const [newPw, setNewPw] = useState('');
  const [confirmPw, setConfirmPw] = useState('');
  const [savingPw, setSavingPw] = useState(false);

  // Modals
  const [createZoneOpen, setCreateZoneOpen] = useState(false);
  const [czName, setCzName] = useState('');
  const [czDesc, setCzDesc] = useState('');
  const [czOwner, setCzOwner] = useState('');
  const [czBusy, setCzBusy] = useState(false);

  const [confirmState, setConfirmState] = useState<{
    title: string;
    desc: string;
    danger?: boolean;
    onRun: () => Promise<void>;
  } | null>(null);

  const loadSectionData = useCallback(async () => {
    if (user?.role !== 'admin') return;
    setLoading(true);
    try {
      const [ov, tel] = await Promise.all([
        adminService.getOverview().catch(() => null),
        adminService.getTelemetry().catch(() => null),
      ]);
      if (ov) setOverview(ov);
      if (tel) setTelemetry(tel);

      if (section === 'bypass') {
        const bp = await adminService.getBypassStatus().catch(() => null);
        if (bp) setBypassStatus(bp);
      } else if (section === 'users') {
        const u = await adminService.listUsers().catch(() => []);
        setUsers(u || []);
      } else if (section === 'zones') {
        const [zd, u] = await Promise.all([
          adminService.listZones().catch(() => null),
          adminService.listUsers().catch(() => []),
        ]);
        if (zd) setZonesData(zd);
        setUsers(u || []);
      } else if (section === 'contacts') {
        const cd = await adminService.listContacts().catch(() => null);
        if (cd) setContactsData(cd);
      } else if (section === 'settings') {
        const [st, si] = await Promise.all([
          adminService.getSettings().catch(() => null),
          adminService.getSiteInfo().catch(() => null),
        ]);
        if (st) {
          setMotd(st.motd || '');
          setMaxZones(st.max_zones || 0);
          setDisableReg(!!st.disable_registration);
        }
        if (si) setSiteInfo({ ...DEFAULT_ADMIN_SITE_INFO, ...si });
      } else if (section === 'overview') {
        const bp = await adminService.getBypassStatus().catch(() => null);
        if (bp) setBypassStatus(bp);
      }
    } finally {
      setLoading(false);
    }
  }, [user?.role, section]);

  useEffect(() => {
    void loadSectionData();
  }, [loadSectionData]);

  const filteredUsers = useMemo(() => {
    const q = userSearch.trim().toLowerCase();
    if (!q) return users;
    return users.filter(
      (u) => u.username.toLowerCase().includes(q) || (u.email && u.email.toLowerCase().includes(q)),
    );
  }, [users, userSearch]);

  const filteredContacts = useMemo(() => {
    const list = contactsData?.items || [];
    if (contactFilter === 'all') return list;
    return list.filter((c) => c.status === contactFilter);
  }, [contactsData, contactFilter]);

  if (user?.role !== 'admin') {
    return (
      <div className="flex-1 flex flex-col items-center justify-center p-6 text-center space-y-4">
        <Shield className="w-12 h-12 text-rose-500" aria-hidden="true" />
        <div className="space-y-1 max-w-sm">
          <h2 className="text-base font-bold text-ink-1">Không có quyền truy cập Admin</h2>
          <p className="text-xs text-ink-2">
            Khu vực này chỉ dành cho tài khoản có vai trò Quản trị viên (Admin).
          </p>
        </div>
        <Button size="sm" onClick={() => router.push(ROUTES.PANEL_FILES)}>
          Quay về Files
        </Button>
      </div>
    );
  }

  const runBypass = async (label: string, endpoint: string, body?: Record<string, unknown>) => {
    setBypassBusy(label);
    setConsoleTitle(`Đang chạy: ${label}...`);
    setConsoleOk(null);
    try {
      const res = await adminService.runBypassAction(endpoint, body);
      setConsoleOk(res.ok);
      setConsoleTitle(
        res.ran_in_terminal
          ? `${label} (đã gửi vào Terminal Admin)`
          : `${label} (exit code: ${res.exit_code})`,
      );
      setConsoleOutput(res.output || '(Không có output)');
      await loadSectionData();
    } catch (err: unknown) {
      setConsoleOk(false);
      setConsoleTitle(`${label} — Lỗi`);
      setConsoleOutput(err instanceof Error ? err.message : 'Lỗi thực thi');
    } finally {
      setBypassBusy(null);
    }
  };

  return (
    <div className="flex-1 overflow-y-auto bg-canvas">
      {/* Sub Navigation */}
      <div className="border-b border-line bg-surface-1/60 px-4 sm:px-6 py-2.5 flex flex-wrap items-center justify-between gap-3 sticky top-0 z-20 backdrop-blur-md">
        <nav aria-label="Điều hướng Quản trị Admin" className="flex items-center gap-1 overflow-x-auto">
          {ADMIN_TABS.map((tab) => {
            const active = tab.id === section;
            return (
              <Link
                key={tab.id}
                href={tab.href}
                className={`px-3 py-1.5 min-h-[36px] inline-flex items-center rounded-lg text-xs font-semibold whitespace-nowrap focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
                  active
                    ? 'bg-accent text-on-accent shadow-sm'
                    : 'text-ink-2 hover:text-ink-1 hover:bg-surface-2'
                }`}
              >
                {tab.label}
              </Link>
            );
          })}
        </nav>

        <Button size="sm" variant="secondary" onClick={() => void loadSectionData()}>
          <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} aria-hidden="true" />
          <span>Làm mới</span>
        </Button>
      </div>

      <div className="p-4 sm:p-6 max-w-6xl mx-auto space-y-6">
        {/* ── OVERVIEW ── */}
        {section === 'overview' && (
          <>
            {loading && !overview ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <Skeleton className="h-24" />
                <Skeleton className="h-24" />
                <Skeleton className="h-24" />
                <Skeleton className="h-24" />
              </div>
            ) : (
              <>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                  <MetricTile
                    label="Người dùng"
                    value={overview?.total_users ?? 0}
                    hint="Tài khoản đã đăng ký"
                    icon={<Users className="w-4 h-4" />}
                  />
                  <MetricTile
                    label="Tổng Zones"
                    value={overview?.total_zones ?? 0}
                    hint={`${telemetry?.autostart_zones ?? 0} zone bật Autostart`}
                    icon={<Layers className="w-4 h-4" />}
                  />
                  <MetricTile
                    label="Terminal đang mở"
                    value={overview?.active_terminals ?? 0}
                    hint="Phiên PTY hoạt động"
                    icon={<Terminal className="w-4 h-4" />}
                  />
                  <MetricTile
                    label="Dung lượng /data"
                    value={overview?.disk_display || `${overview?.disk_used_gb ?? 0} GB`}
                    hint={
                      overview?.disk_total_gb
                        ? `Trống ${overview.disk_free_gb ?? 0} / ${overview.disk_total_gb} GB`
                        : 'Đang theo dõi'
                    }
                    icon={<HardDrive className="w-4 h-4" />}
                  />
                </div>

                {telemetry && (
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <Card className="p-5 space-y-4">
                      <div className="flex items-center justify-between">
                        <h2 className="text-sm font-bold text-ink-1 flex items-center gap-2">
                          <Cpu className="w-4 h-4 text-accent" aria-hidden="true" />
                          <span>Tài nguyên Máy chủ</span>
                        </h2>
                        <span className="text-[11px] font-mono text-ink-3">
                          Uptime: {telemetry.uptime_display}
                        </span>
                      </div>

                      <div className="space-y-3 text-xs">
                        <div>
                          <div className="flex justify-between mb-1">
                            <span className="text-ink-2">CPU ({telemetry.cpu_cores} cores)</span>
                            <span className="font-mono tabular-nums text-ink-1">
                              {telemetry.cpu_percent}% · Load {telemetry.load_1m}
                            </span>
                          </div>
                          <div className="h-2 rounded-full bg-surface-2 overflow-hidden">
                            <div
                              className="h-full bg-accent rounded-full transition-all"
                              style={{ width: `${Math.min(100, telemetry.cpu_percent)}%` }}
                            />
                          </div>
                        </div>

                        <div>
                          <div className="flex justify-between mb-1">
                            <span className="text-ink-2">RAM</span>
                            <span className="font-mono tabular-nums text-ink-1">
                              {telemetry.ram_used_mb} / {telemetry.ram_total_mb} MB ({telemetry.ram_percent}%)
                            </span>
                          </div>
                          <div className="h-2 rounded-full bg-surface-2 overflow-hidden">
                            <div
                              className="h-full bg-amber-500 rounded-full transition-all"
                              style={{ width: `${Math.min(100, telemetry.ram_percent)}%` }}
                            />
                          </div>
                        </div>
                      </div>
                    </Card>

                    <Card className="p-5 space-y-3">
                      <h2 className="text-sm font-bold text-ink-1 flex items-center gap-2">
                        <Activity className="w-4 h-4 text-accent" aria-hidden="true" />
                        <span>Thông số Hạ tầng &amp; Bypass</span>
                      </h2>
                      <div className="grid grid-cols-2 gap-3 text-xs">
                        <div className="p-3 rounded-xl bg-surface-2 border border-line">
                          <div className="text-ink-3">Cổng đang mở</div>
                          <div className="font-mono font-bold text-base tabular-nums text-ink-1 mt-0.5">
                            {telemetry.total_ports}
                          </div>
                        </div>
                        <div className="p-3 rounded-xl bg-surface-2 border border-line">
                          <div className="text-ink-3">Custom Domains</div>
                          <div className="font-mono font-bold text-base tabular-nums text-ink-1 mt-0.5">
                            {telemetry.total_domains}
                          </div>
                        </div>
                      </div>
                      <div className="flex flex-wrap items-center justify-between gap-2 pt-1 text-xs">
                        <span className="text-ink-2">HTTPS Global Bypass:</span>
                        {bypassStatus?.running ? (
                          <Badge tone="success">Đang chạy (127.0.0.1:1443)</Badge>
                        ) : (
                          <Badge tone="warning">Chưa chạy</Badge>
                        )}
                      </div>
                      <div className="text-[11px] font-mono text-ink-3 truncate">
                        {telemetry.platform} · {telemetry.python_version}
                      </div>
                    </Card>
                  </div>
                )}
              </>
            )}
          </>
        )}

        {/* ── USERS ── */}
        {section === 'users' && (
          <Card className="overflow-hidden">
            <div className="px-5 py-4 border-b border-line flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div>
                <h2 className="text-sm font-bold text-ink-1">Quản lý Tài khoản ({users.length})</h2>
                <p className="text-xs text-ink-3">Phân quyền Admin/User và kiểm soát người dùng</p>
              </div>
              <div className="w-full sm:w-64">
                <Input
                  aria-label="Tìm kiếm tài khoản"
                  placeholder="Tìm username hoặc email..."
                  value={userSearch}
                  onChange={(e) => setUserSearch(e.target.value)}
                  leftIcon={<Search className="w-3.5 h-3.5" />}
                  className="min-h-[36px] text-xs"
                />
              </div>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse text-xs">
                <thead>
                  <tr className="border-b border-line bg-surface-2/60 font-mono text-[11px] uppercase text-ink-3">
                    <th className="px-4 py-2.5">Username</th>
                    <th className="px-4 py-2.5">Email</th>
                    <th className="px-4 py-2.5">Vai trò</th>
                    <th className="px-4 py-2.5 hidden sm:table-cell">Ngày tạo</th>
                    <th className="px-4 py-2.5 text-right">Thao tác</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-line">
                  {filteredUsers.map((u) => {
                    const isSelf = u.id === user.id;
                    const nextRole = u.role === 'admin' ? 'user' : 'admin';
                    return (
                      <tr key={u.id} className="hover:bg-surface-2/40">
                        <td className="px-4 py-3 font-mono font-semibold text-ink-1">
                          {u.username} {isSelf && <Badge tone="accent">Bạn</Badge>}
                        </td>
                        <td className="px-4 py-3 text-ink-2">{u.email || '—'}</td>
                        <td className="px-4 py-3">
                          <Badge tone={u.role === 'admin' ? 'warning' : 'neutral'}>
                            {u.role}
                          </Badge>
                        </td>
                        <td className="px-4 py-3 font-mono tabular-nums text-ink-3 hidden sm:table-cell">
                          {formatDateVi(u.created_at)}
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center justify-end gap-2">
                            <Button
                              size="sm"
                              variant="secondary"
                              disabled={isSelf}
                              onClick={() =>
                                setConfirmState({
                                  title: 'Đổi vai trò tài khoản',
                                  desc: `Đổi quyền của "${u.username}" sang ${nextRole.toUpperCase()}?`,
                                  onRun: async () => {
                                    await adminService.updateUserRole(u.id, nextRole);
                                    pushToast(`Đã đổi quyền ${u.username} → ${nextRole}`, 'success');
                                    await loadSectionData();
                                  },
                                })
                              }
                            >
                              Đặt {nextRole}
                            </Button>
                            <button
                              type="button"
                              disabled={isSelf}
                              onClick={() =>
                                setConfirmState({
                                  title: 'Xoá tài khoản',
                                  desc: `Xoá vĩnh viễn tài khoản "${u.username}"?`,
                                  danger: true,
                                  onRun: async () => {
                                    await adminService.deleteUser(u.id);
                                    pushToast(`Đã xoá tài khoản ${u.username}`, 'success');
                                    await loadSectionData();
                                  },
                                })
                              }
                              aria-label={`Xoá tài khoản ${u.username}`}
                              className="p-2 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg border border-line text-ink-3 hover:text-rose-500 hover:bg-rose-500/10 disabled:opacity-40"
                            >
                              <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>
        )}

        {/* ── ZONES BY USER ── */}
        {section === 'zones' && (
          <div className="space-y-4">
            <Card className="p-4 flex flex-col md:flex-row md:items-center justify-between gap-3">
              <div className="flex flex-wrap items-center gap-2 flex-1">
                <div className="w-full sm:w-64">
                  <Input
                    aria-label="Tìm kiếm zone hoặc user"
                    placeholder="Tìm zone hoặc tên user..."
                    value={zoneSearch}
                    onChange={(e) => setZoneSearch(e.target.value)}
                    leftIcon={<Search className="w-3.5 h-3.5" />}
                    className="min-h-[36px] text-xs"
                  />
                </div>
                <div className="w-44">
                  <Select
                    aria-label="Lọc trạng thái zone"
                    value={zoneFilter}
                    onChange={(e) => setZoneFilter(e.target.value as typeof zoneFilter)}
                    className="min-h-[36px] py-1 text-xs"
                  >
                    <option value="all">Tất cả User</option>
                    <option value="with_zones">Có Zone</option>
                    <option value="running">Đang chạy PTY</option>
                    <option value="unassigned">Chưa gán chủ</option>
                  </Select>
                </div>
              </div>
              <Button
                size="sm"
                onClick={() => {
                  setCzName('');
                  setCzDesc('');
                  setCzOwner(users[0]?.id || user.id);
                  setCreateZoneOpen(true);
                }}
              >
                <Plus className="w-4 h-4" aria-hidden="true" />
                <span>Tạo Zone cho User</span>
              </Button>
            </Card>

            {(zonesData?.users || [])
              .filter((ug) => {
                if (zoneFilter === 'with_zones' && ug.zones.length === 0) return false;
                if (zoneFilter === 'running' && !ug.zones.some((z) => z.terminal_active)) return false;
                if (zoneFilter === 'unassigned') return false;
                const q = zoneSearch.trim().toLowerCase();
                if (!q) return true;
                return (
                  ug.username.toLowerCase().includes(q) ||
                  ug.zones.some((z) => z.name.toLowerCase().includes(q))
                );
              })
              .map((ug) => (
                <Card key={ug.id} className="p-4 space-y-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="font-mono text-sm font-bold text-ink-1">{ug.username}</span>
                      <Badge tone={ug.role === 'admin' ? 'warning' : 'neutral'}>{ug.role}</Badge>
                      <span className="text-xs text-ink-3 font-mono">{ug.zones.length} zone</span>
                    </div>
                  </div>
                  {ug.zones.length === 0 ? (
                    <div className="text-xs text-ink-3 italic">User chưa có zone nào.</div>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                      {ug.zones.map((z) => (
                        <div
                          key={z.name}
                          className="rounded-xl border border-line bg-surface-2/60 p-3.5 space-y-2.5"
                        >
                          <div className="flex items-center justify-between gap-2">
                            <span className="font-mono text-xs font-bold text-ink-1 truncate">
                              {z.name}
                            </span>
                            {z.terminal_active ? (
                              <Badge tone="success">PTY Active</Badge>
                            ) : (
                              <Badge tone="neutral">Idle</Badge>
                            )}
                          </div>
                          <div className="text-[11px] text-ink-3 truncate">
                            {z.description || 'Không có mô tả'} · {z.ports.length} port
                          </div>
                          <div className="flex flex-wrap items-center gap-2 pt-1">
                            <Button
                              size="sm"
                              variant="primary"
                              onClick={() => {
                                selectZone(z.name);
                                router.push(ROUTES.PANEL_FILES);
                              }}
                              className="min-h-[30px] px-2.5"
                            >
                              <ExternalLink className="w-3 h-3" aria-hidden="true" />
                              <span>Mở Zone</span>
                            </Button>
                            <select
                              aria-label={`Chuyển chủ sở hữu zone ${z.name}`}
                              value={z.owner_id}
                              onChange={async (e) => {
                                try {
                                  await adminService.reassignZoneOwner(z.name, e.target.value);
                                  pushToast(`Đã chuyển chủ zone ${z.name}`, 'success');
                                  await loadSectionData();
                                  await refreshZones();
                                } catch (err: unknown) {
                                  pushToast(
                                    err instanceof Error ? err.message : 'Lỗi chuyển chủ',
                                    'error',
                                  );
                                }
                              }}
                              className="h-[30px] rounded-lg bg-surface-1 border border-line text-[11px] px-2 text-ink-1"
                            >
                              {users.map((opt) => (
                                <option key={opt.id} value={opt.id}>
                                  → {opt.username}
                                </option>
                              ))}
                            </select>
                            <button
                              type="button"
                              onClick={() =>
                                setConfirmState({
                                  title: 'Xoá Zone',
                                  desc: `Xoá vĩnh viễn zone "${z.name}"?`,
                                  danger: true,
                                  onRun: async () => {
                                    await adminService.deleteZoneByName(z.name);
                                    pushToast(`Đã xoá zone ${z.name}`, 'success');
                                    await loadSectionData();
                                    await refreshZones();
                                  },
                                })
                              }
                              aria-label={`Xoá zone ${z.name}`}
                              className="ml-auto p-1.5 rounded-lg text-ink-3 hover:text-rose-500 hover:bg-rose-500/10"
                            >
                              <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </Card>
              ))}
          </div>
        )}

        {/* ── BYPASS & TERMINAL ── */}
        {section === 'bypass' && (
          <Card className="p-5 space-y-4">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div>
                <h2 className="text-sm font-bold text-ink-1 flex items-center gap-2">
                  <Activity className="w-4 h-4 text-accent" aria-hidden="true" />
                  <span>Hệ thống Bypass HTTPS Toàn Cục (fb-bypass-system.sh)</span>
                </h2>
                <p className="text-xs text-ink-3 mt-1">
                  Tự đồng bộ HTTPS_PROXY, NODE_OPTIONS và SSL_CERT_FILE xuống toàn bộ shell user
                </p>
              </div>
              <div className="flex items-center gap-2">
                {bypassStatus?.running ? (
                  <Badge tone="success">Đang chạy (127.0.0.1:1443)</Badge>
                ) : bypassStatus?.installed ? (
                  <Badge tone="warning">Đã cài • Đã dừng</Badge>
                ) : (
                  <Badge tone="neutral">Chưa cài đặt</Badge>
                )}
              </div>
            </div>

            <div className="rounded-xl overflow-hidden border border-line">
              <PtyTerminalView mode="admin" heightClass="h-auto" />
            </div>

            <div className="flex flex-wrap gap-2">
              <Button
                size="sm"
                loading={bypassBusy === 'install'}
                onClick={() => void runBypass('install', '/api/admin/bypass/install')}
              >
                <Download className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Cài đặt</span>
              </Button>
              <Button
                size="sm"
                variant="secondary"
                loading={bypassBusy === 'test'}
                onClick={() => void runBypass('test', '/api/admin/bypass/test')}
              >
                <FlaskConical className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Chạy Test</span>
              </Button>
              <Button
                size="sm"
                variant="secondary"
                loading={bypassBusy === 'sync'}
                onClick={async () => {
                  setBypassBusy('sync');
                  try {
                    const res = await adminService.syncBypassEnv();
                    setConsoleOk(res.ok);
                    setConsoleTitle('Phân bổ môi trường cho User Terminals');
                    setConsoleOutput(`Đã cập nhật ${res.updated_terminals} terminal user đang mở.`);
                    pushToast('Đã đồng bộ môi trường bypass.', 'success');
                  } catch (err: unknown) {
                    pushToast(err instanceof Error ? err.message : 'Lỗi đồng bộ', 'error');
                  } finally {
                    setBypassBusy(null);
                  }
                }}
              >
                <Share2 className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Phân bổ cho User</span>
              </Button>
              {!bypassStatus?.running && bypassStatus?.installed && (
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={() => void runBypass('start', '/api/admin/bypass/action', { action: 'start' })}
                >
                  <Play className="w-3.5 h-3.5" aria-hidden="true" />
                  <span>Bật</span>
                </Button>
              )}
              <Button
                size="sm"
                variant="secondary"
                onClick={() => void runBypass('restart', '/api/admin/bypass/action', { action: 'restart' })}
              >
                <RefreshCw className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Restart</span>
              </Button>
              <Button
                size="sm"
                variant="secondary"
                onClick={() => void runBypass('stop', '/api/admin/bypass/action', { action: 'stop' })}
              >
                <Square className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Dừng</span>
              </Button>
              <Button
                size="sm"
                variant="ghost"
                onClick={async () => {
                  try {
                    const res = await adminService.getBypassLog();
                    setConsoleOk(true);
                    setConsoleTitle('fb-bypass log');
                    setConsoleOutput(res.log || 'Chưa có log.');
                  } catch {}
                }}
              >
                <FileText className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Xem Log</span>
              </Button>
              <Button
                size="sm"
                variant="danger"
                onClick={() =>
                  setConfirmState({
                    title: 'Gỡ cài đặt Bypass',
                    desc: 'Gỡ bỏ hoàn toàn fb-bypass-system.sh khỏi hệ thống?',
                    danger: true,
                    onRun: async () => {
                      await runBypass('uninstall', '/api/admin/bypass/action', { action: 'uninstall' });
                    },
                  })
                }
              >
                <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                <span>Gỡ bỏ</span>
              </Button>
            </div>

            {consoleOutput && (
              <div className="console-dark rounded-xl border border-zinc-800 overflow-hidden">
                <div className="px-3.5 py-2 border-b border-zinc-800 flex items-center justify-between text-xs font-mono">
                  <span className="text-zinc-300">{consoleTitle}</span>
                  {consoleOk !== null && (
                    <Badge tone={consoleOk ? 'success' : 'danger'}>
                      {consoleOk ? 'SUCCESS' : 'FAILED'}
                    </Badge>
                  )}
                </div>
                <pre className="p-3.5 text-xs font-mono text-zinc-200 whitespace-pre-wrap max-h-64 overflow-y-auto">
                  {consoleOutput}
                </pre>
              </div>
            )}

            {bypassStatus?.metrics && (
              <div className="border-t border-line pt-3">
                <button
                  type="button"
                  onClick={() => setShowMetrics((s) => !s)}
                  className="inline-flex items-center gap-1.5 text-xs font-medium text-ink-2 hover:text-ink-1"
                >
                  {showMetrics ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
                  <span>Prometheus Metrics (127.0.0.1:1444/metrics)</span>
                </button>
                {showMetrics && (
                  <pre className="mt-2 console-dark rounded-xl p-3 text-[11px] font-mono whitespace-pre-wrap max-h-56 overflow-y-auto">
                    {bypassStatus.metrics}
                  </pre>
                )}
              </div>
            )}
          </Card>
        )}

        {/* ── CONTACTS INBOX ── */}
        {section === 'contacts' && (
          <div className="space-y-4">
            <Card className="p-4 flex flex-wrap items-center justify-between gap-3">
              <div className="flex items-center gap-2">
                <Mail className="w-4 h-4 text-accent" aria-hidden="true" />
                <h2 className="text-sm font-bold text-ink-1">
                  Hộp thư Liên hệ ({contactsData?.total ?? 0})
                </h2>
              </div>
              <div className="flex items-center gap-1.5">
                {(['all', 'pending', 'replied'] as const).map((st) => (
                  <button
                    key={st}
                    type="button"
                    onClick={() => setContactFilter(st)}
                    className={`px-3 py-1.5 min-h-[34px] rounded-lg text-xs font-semibold ${
                      contactFilter === st
                        ? 'bg-accent text-on-accent'
                        : 'bg-surface-2 text-ink-2 hover:text-ink-1'
                    }`}
                  >
                    {st === 'all' ? 'Tất cả' : st === 'pending' ? 'Chờ trả lời' : 'Đã phản hồi'}
                  </button>
                ))}
              </div>
            </Card>

            {filteredContacts.length === 0 ? (
              <Card className="p-8 text-center text-xs text-ink-3">
                Không có yêu cầu liên hệ nào trong mục này.
              </Card>
            ) : (
              <div className="space-y-3">
                {filteredContacts.map((item) => (
                  <Card key={item.id} className="p-5 space-y-3">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-xs font-bold text-accent">#{item.id}</span>
                        <span className="text-sm font-bold text-ink-1">{item.subject}</span>
                      </div>
                      <Badge tone={item.status === 'replied' ? 'success' : 'warning'}>
                        {item.status === 'replied' ? 'Đã phản hồi' : 'Chờ xử lý'}
                      </Badge>
                    </div>
                    <div className="text-xs text-ink-3">
                      Từ <strong className="text-ink-1">{item.name}</strong> ({item.email}) ·{' '}
                      {formatDateVi(item.created_at)}
                    </div>
                    <p className="text-xs sm:text-sm text-ink-2 whitespace-pre-wrap bg-surface-2/60 border border-line rounded-xl p-3">
                      {item.message}
                    </p>
                    {item.reply && (
                      <div className="rounded-xl bg-emerald-500/10 border border-emerald-500/30 p-3 text-xs text-ink-1">
                        <div className="text-[11px] font-mono text-emerald-500 mb-1">
                          Phản hồi bởi {item.replied_by || 'Admin'}:
                        </div>
                        {item.reply}
                      </div>
                    )}
                    <div className="flex flex-col sm:flex-row gap-2 items-end">
                      <div className="flex-1 w-full">
                        <Textarea
                          aria-label={`Trả lời ticket ${item.id}`}
                          rows={2}
                          placeholder="Nhập nội dung phản hồi cho người gửi..."
                          value={replyDrafts[item.id] ?? ''}
                          onChange={(e) =>
                            setReplyDrafts((prev) => ({ ...prev, [item.id]: e.target.value }))
                          }
                        />
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          size="sm"
                          loading={replyBusyId === item.id}
                          onClick={async () => {
                            const text = (replyDrafts[item.id] || '').trim();
                            if (!text) return;
                            setReplyBusyId(item.id);
                            try {
                              await adminService.replyContact(item.id, text);
                              setReplyDrafts((prev) => ({ ...prev, [item.id]: '' }));
                              pushToast(`Đã phản hồi #${item.id}`, 'success');
                              await loadSectionData();
                            } catch (err: unknown) {
                              pushToast(
                                err instanceof Error ? err.message : 'Lỗi gửi phản hồi',
                                'error',
                              );
                            } finally {
                              setReplyBusyId(null);
                            }
                          }}
                        >
                          <Send className="w-3.5 h-3.5" aria-hidden="true" />
                          <span>Gửi trả lời</span>
                        </Button>
                        <button
                          type="button"
                          onClick={() =>
                            setConfirmState({
                              title: 'Xoá liên hệ',
                              desc: `Xoá ticket #${item.id}?`,
                              danger: true,
                              onRun: async () => {
                                await adminService.deleteContact(item.id);
                                pushToast(`Đã xoá #${item.id}`, 'success');
                                await loadSectionData();
                              },
                            })
                          }
                          aria-label={`Xoá liên hệ ${item.id}`}
                          className="p-2 min-h-[36px] min-w-[36px] flex items-center justify-center rounded-lg border border-line text-ink-3 hover:text-rose-500 hover:bg-rose-500/10"
                        >
                          <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                        </button>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            )}
          </div>
        )}

        {/* ── SETTINGS ── */}
        {section === 'settings' && (
          <div className="space-y-6">
            <Card className="p-5">
              <form
                onSubmit={async (e) => {
                  e.preventDefault();
                  setSavingSettings(true);
                  try {
                    const payload: Record<string, unknown> = {
                      motd,
                      max_zones: Number(maxZones) || 0,
                      disable_registration: disableReg,
                    };
                    await adminService.saveSettings(payload);
                    pushToast('Đã lưu cấu hình hệ thống.', 'success');
                    await loadSectionData();
                  } catch (err: unknown) {
                    pushToast(err instanceof Error ? err.message : 'Lỗi lưu cấu hình', 'error');
                  } finally {
                    setSavingSettings(false);
                  }
                }}
                className="space-y-4"
              >
                <h2 className="text-sm font-bold text-ink-1 flex items-center gap-2">
                  <Settings className="w-4 h-4 text-accent" aria-hidden="true" />
                  <span>Cấu hình Hệ thống</span>
                </h2>
                <Input
                  label="Thông báo hệ thống (MOTD)"
                  value={motd}
                  onChange={(e) => setMotd(e.target.value)}
                  placeholder="VD: Chào mừng đến với Panel ThTuanIT..."
                />
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <Input
                    label="Giới hạn Zone / User (0 = không giới hạn)"
                    type="number"
                    min={0}
                    value={String(maxZones)}
                    onChange={(e) => setMaxZones(Number.parseInt(e.target.value || '0', 10))}
                  />
                  <div className="flex items-end pb-2">
                    <label className="inline-flex items-center gap-2 text-xs text-ink-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={disableReg}
                        onChange={(e) => setDisableReg(e.target.checked)}
                        className="rounded border-line-strong text-accent focus:ring-accent"
                      />
                      <span>Tắt đăng ký tài khoản mới</span>
                    </label>
                  </div>
                </div>
                <div className="flex justify-end">
                  <Button type="submit" size="sm" loading={savingSettings}>
                    Lưu cấu hình hệ thống
                  </Button>
                </div>
              </form>
            </Card>

            <Card className="p-5">
              <form
                onSubmit={async (e) => {
                  e.preventDefault();
                  setSavingSite(true);
                  try {
                    const res = await adminService.updateSiteInfo(siteInfo);
                    setSiteInfo(res.site);
                    pushToast('Đã lưu thông tin website & thương hiệu.', 'success');
                  } catch (err: unknown) {
                    pushToast(err instanceof Error ? err.message : 'Lỗi lưu Site Info', 'error');
                  } finally {
                    setSavingSite(false);
                  }
                }}
                className="space-y-4"
              >
                <h2 className="text-sm font-bold text-ink-1 flex items-center gap-2">
                  <Globe className="w-4 h-4 text-accent" aria-hidden="true" />
                  <span>Thông tin Website &amp; Thương hiệu</span>
                </h2>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                  <Input
                    label="Tên thương hiệu"
                    required
                    value={siteInfo.brand_name}
                    onChange={(e) => setSiteInfo((p) => ({ ...p, brand_name: e.target.value }))}
                  />
                  <Input
                    label="Ký hiệu ngắn"
                    required
                    maxLength={4}
                    value={siteInfo.brand_short}
                    onChange={(e) =>
                      setSiteInfo((p) => ({ ...p, brand_short: e.target.value.toUpperCase() }))
                    }
                  />
                  <Input
                    label="Tác giả"
                    required
                    value={siteInfo.author_name}
                    onChange={(e) => setSiteInfo((p) => ({ ...p, author_name: e.target.value }))}
                  />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <Input
                    label="Khẩu hiệu (Tagline)"
                    value={siteInfo.tagline}
                    onChange={(e) => setSiteInfo((p) => ({ ...p, tagline: e.target.value }))}
                  />
                  <Input
                    label="Ghi chú Footer"
                    value={siteInfo.footer_note}
                    onChange={(e) => setSiteInfo((p) => ({ ...p, footer_note: e.target.value }))}
                  />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <Input
                    label="Email hỗ trợ công khai"
                    type="email"
                    value={siteInfo.contact_email}
                    onChange={(e) => setSiteInfo((p) => ({ ...p, contact_email: e.target.value }))}
                  />
                  <Input
                    label="Giờ hỗ trợ"
                    value={siteInfo.contact_hours}
                    onChange={(e) => setSiteInfo((p) => ({ ...p, contact_hours: e.target.value }))}
                  />
                </div>
                <Textarea
                  label="Mô tả Hero trang chủ"
                  rows={2}
                  value={siteInfo.hero_description}
                  onChange={(e) => setSiteInfo((p) => ({ ...p, hero_description: e.target.value }))}
                />
                <Textarea
                  label="Đoạn giới thiệu (About)"
                  rows={2}
                  value={siteInfo.about_intro}
                  onChange={(e) => setSiteInfo((p) => ({ ...p, about_intro: e.target.value }))}
                />
                <div className="flex justify-end">
                  <Button type="submit" size="sm" loading={savingSite}>
                    Lưu thông tin Website
                  </Button>
                </div>
              </form>
            </Card>

            <Card className="p-5 max-w-xl">
              <form
                onSubmit={async (e) => {
                  e.preventDefault();
                  const check = validatePasswordChange(curPw, newPw, confirmPw);
                  if (!check.ok || !check.data) {
                    pushToast(check.error || 'Mật khẩu không hợp lệ', 'error');
                    return;
                  }
                  setSavingPw(true);
                  try {
                    await adminService.changePassword(check.data.currentPassword, check.data.newPassword);
                    setCurPw('');
                    setNewPw('');
                    setConfirmPw('');
                    pushToast('Đã đổi mật khẩu Admin.', 'success');
                  } catch (err: unknown) {
                    pushToast(err instanceof Error ? err.message : 'Lỗi đổi mật khẩu', 'error');
                  } finally {
                    setSavingPw(false);
                  }
                }}
                className="space-y-4"
              >
                <h2 className="text-sm font-bold text-ink-1 flex items-center gap-2">
                  <KeyRound className="w-4 h-4 text-accent" aria-hidden="true" />
                  <span>Đổi mật khẩu Quản trị viên</span>
                </h2>
                <Input
                  label="Mật khẩu hiện tại"
                  type="password"
                  required
                  value={curPw}
                  onChange={(e) => setCurPw(e.target.value)}
                />
                <Input
                  label="Mật khẩu mới (tối thiểu 6 ký tự)"
                  type="password"
                  required
                  value={newPw}
                  onChange={(e) => setNewPw(e.target.value)}
                />
                <Input
                  label="Xác nhận mật khẩu mới"
                  type="password"
                  required
                  value={confirmPw}
                  onChange={(e) => setConfirmPw(e.target.value)}
                />
                <div className="flex justify-end">
                  <Button type="submit" size="sm" loading={savingPw}>
                    Cập nhật mật khẩu
                  </Button>
                </div>
              </form>
            </Card>
          </div>
        )}
      </div>

      {/* Create Zone for User Modal */}
      <Modal open={createZoneOpen} onClose={() => setCreateZoneOpen(false)} title="Tạo Zone cho User">
        <form
          onSubmit={async (e) => {
            e.preventDefault();
            if (!czName.trim()) return;
            setCzBusy(true);
            try {
              await adminService.createZoneForUser(czName.trim(), czDesc.trim(), czOwner);
              setCreateZoneOpen(false);
              pushToast(`Đã tạo zone ${czName.trim()}`, 'success');
              await loadSectionData();
              await refreshZones();
            } catch (err: unknown) {
              pushToast(err instanceof Error ? err.message : 'Lỗi tạo zone', 'error');
            } finally {
              setCzBusy(false);
            }
          }}
          className="space-y-4"
        >
          <Input label="Tên Zone" required value={czName} onChange={(e) => setCzName(e.target.value)} />
          <Input label="Mô tả" value={czDesc} onChange={(e) => setCzDesc(e.target.value)} />
          <Select label="Chủ sở hữu" value={czOwner} onChange={(e) => setCzOwner(e.target.value)}>
            {users.map((u) => (
              <option key={u.id} value={u.id}>
                {u.username} ({u.role})
              </option>
            ))}
          </Select>
          <div className="flex justify-end gap-2">
            <Button variant="secondary" size="sm" onClick={() => setCreateZoneOpen(false)}>
              Huỷ
            </Button>
            <Button type="submit" size="sm" loading={czBusy}>
              Tạo Zone
            </Button>
          </div>
        </form>
      </Modal>

      <ConfirmModal
        open={Boolean(confirmState)}
        onClose={() => setConfirmState(null)}
        onConfirm={async () => {
          if (!confirmState) return;
          try {
            await confirmState.onRun();
          } catch (err: unknown) {
            pushToast(err instanceof Error ? err.message : 'Thao tác thất bại', 'error');
          } finally {
            setConfirmState(null);
          }
        }}
        title={confirmState?.title || ''}
        description={confirmState?.desc || ''}
        danger={confirmState?.danger}
      />
    </div>
  );
}