File size: 62,143 Bytes
bcbc028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Nine7频道助手</title>
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<style>
:root {
  --bg: var(--tg-theme-bg-color, #1a1a2e);
  --card: var(--tg-theme-secondary-bg-color, #16213e);
  --text: var(--tg-theme-text-color, #eaeaea);
  --hint: var(--tg-theme-hint-color, #8a8a9a);
  --accent: var(--tg-theme-button-color, #0f3460);
  --btn-text: var(--tg-theme-button-text-color, #ffffff);
  --link: var(--tg-theme-link-color, #e94560);
  --danger: #e94560;
  --success: #27ae60;
  --radius: 14px;
  --shadow: 0 2px 16px rgba(0,0,0,.18);
}
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; background:var(--bg); color:var(--text); min-height:100vh; padding-bottom:80px; overflow-x:hidden; }
.header { background:linear-gradient(135deg,#0f3460 0%,#533483 50%,#e94560 100%); padding:20px 20px 24px; text-align:center; position:relative; overflow:hidden; }
.header::after { content:''; position:absolute; bottom:-20px; left:-10%; right:-10%; height:40px; background:var(--bg); border-radius:50% 50% 0 0; }
.header h1 { font-size:20px; color:#fff; font-weight:700; }
.header p { font-size:12px; color:rgba(255,255,255,.7); margin-top:4px; }
.header-content { display:flex; align-items:center; justify-content:center; gap:14px; }
.avatar { width:48px; height:48px; border-radius:50%; border:2px solid rgba(255,255,255,.3); object-fit:cover; }
.avatar-placeholder { width:48px; height:48px; border-radius:50%; border:2px solid rgba(255,255,255,.3); background:rgba(255,255,255,.15); display:flex; align-items:center; justify-content:center; font-size:22px; }
.header-text { text-align:left; }
.header-text h1 { font-size:18px; }
.header-text p { font-size:11px; margin-top:2px; }
.header-greeting { font-size:13px; color:rgba(255,255,255,.85); margin-top:2px; font-weight:500; }
.bottom-nav { position:fixed; bottom:0; left:0; right:0; display:flex; background:var(--card); border-top:1px solid rgba(255,255,255,.06); z-index:100; padding-bottom:env(safe-area-inset-bottom); }
.nav-item { flex:1; text-align:center; padding:8px 0 6px; cursor:pointer; transition:all .2s; -webkit-tap-highlight-color:transparent; }
.nav-item .icon { font-size:20px; }
.nav-item .label { font-size:10px; color:var(--hint); margin-top:2px; }
.nav-item.active .label { color:var(--link); font-weight:600; }
.nav-item.active .icon { transform:scale(1.15); }
.page { display:none; padding:16px; animation:fadeUp .3s; }
.page.active { display:block; }
@keyframes fadeUp { from{opacity:0;transform:translateY(12px)} to{opacity:1;transform:translateY(0)} }
.card { background:var(--card); border-radius:var(--radius); padding:16px; margin-bottom:12px; box-shadow:var(--shadow); position:relative; border:1px solid rgba(255,255,255,.04); }
.card-title { font-size:14px; font-weight:600; margin-bottom:8px; display:flex; align-items:center; gap:8px; }
.card-body { font-size:13px; color:var(--hint); line-height:1.7; }
.card-body code { background:rgba(255,255,255,.08); padding:2px 6px; border-radius:4px; font-size:12px; color:var(--link); }
.card-body .ch-name { color:var(--text); font-weight:600; font-size:12px; }
.card-actions { display:flex; gap:8px; margin-top:12px; flex-wrap:wrap; }
.stat-row { display:flex; justify-content:space-between; padding:8px 0; border-bottom:1px solid rgba(255,255,255,.04); }
.stat-row:last-child { border:none; }
.stat-val { color:var(--link); font-weight:600; }
.btn { display:inline-flex; align-items:center; gap:6px; padding:10px 18px; border-radius:10px; border:none; font-size:13px; font-weight:600; cursor:pointer; transition:all .2s; -webkit-tap-highlight-color:transparent; }
.btn:active { transform:scale(.96); }
.btn-primary { background:linear-gradient(135deg,#0f3460,#533483); color:#fff; }
.btn-danger { background:rgba(233,69,96,.15); color:var(--danger); }
.btn-sm { padding:6px 12px; font-size:12px; border-radius:8px; }
.btn-ghost { background:rgba(255,255,255,.06); color:var(--text); }
.btn-success { background:rgba(39,174,96,.15); color:var(--success); }
.btn-block { width:100%; justify-content:center; }
.fab { position:fixed; bottom:80px; right:20px; width:52px; height:52px; border-radius:50%; background:linear-gradient(135deg,#e94560,#533483); color:#fff; font-size:24px; display:flex; align-items:center; justify-content:center; box-shadow:0 4px 20px rgba(233,69,96,.4); cursor:pointer; z-index:50; transition:all .2s; border:none; }
.fab:active { transform:scale(.9); }
.tool-grid { display:grid; grid-template-columns:1fr 1fr; gap:12px; }
.tool-card { background:var(--card); border-radius:var(--radius); padding:20px 14px; text-align:center; cursor:pointer; transition:all .2s; border:1px solid rgba(255,255,255,.04); box-shadow:var(--shadow); }
.tool-card:active { transform:scale(.96); }
.tool-card .t-icon { font-size:28px; margin-bottom:8px; }
.tool-card .t-name { font-size:13px; font-weight:600; }
.tool-card .t-desc { font-size:11px; color:var(--hint); margin-top:4px; }
.modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.65); z-index:200; display:none; align-items:flex-end; justify-content:center; animation:fadeIn .2s; }
.modal-overlay.open { display:flex; }
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
@keyframes slideUp { from{transform:translateY(100%)} to{transform:translateY(0)} }
.modal { background:var(--bg); width:100%; max-width:500px; max-height:88vh; border-radius:20px 20px 0 0; padding:20px; overflow-y:auto; animation:slideUp .3s; }
.modal-title { font-size:17px; font-weight:700; margin-bottom:16px; display:flex; align-items:center; gap:8px; }
.modal-close { margin-left:auto; background:rgba(255,255,255,.08); border:none; color:var(--hint); width:30px; height:30px; border-radius:50%; font-size:16px; cursor:pointer; }
.form-group { margin-bottom:14px; }
.form-label { font-size:12px; color:var(--hint); margin-bottom:6px; display:block; font-weight:500; }
.form-input,.form-select { width:100%; padding:12px 14px; background:var(--card); border:1px solid rgba(255,255,255,.08); border-radius:10px; color:var(--text); font-size:14px; outline:none; transition:border .2s; }
.form-input:focus { border-color:var(--link); }
.form-input::placeholder { color:var(--hint); }
.form-hint { font-size:11px; color:var(--hint); margin-top:4px; }
.channel-picker { display:flex; flex-wrap:wrap; gap:8px; margin-top:8px; }
.ch-chip { padding:6px 12px; background:rgba(255,255,255,.06); border-radius:20px; font-size:12px; cursor:pointer; transition:all .2s; border:1px solid transparent; }
.ch-chip:active,.ch-chip.picked { border-color:var(--link); background:rgba(233,69,96,.1); }
.segment { display:flex; background:var(--card); border-radius:10px; padding:3px; margin-bottom:16px; }
.seg-btn { flex:1; text-align:center; padding:8px; font-size:13px; border-radius:8px; cursor:pointer; transition:all .2s; color:var(--hint); border:none; background:transparent; }
.seg-btn.active { background:linear-gradient(135deg,#0f3460,#533483); color:#fff; font-weight:600; }
.toast { position:fixed; top:20px; left:50%; transform:translateX(-50%) translateY(-80px); background:var(--card); color:var(--text); padding:12px 24px; border-radius:12px; font-size:13px; z-index:999; box-shadow:0 4px 24px rgba(0,0,0,.3); transition:transform .3s; border:1px solid rgba(255,255,255,.06); }
.toast.show { transform:translateX(-50%) translateY(0); }
.toast.success { border-left:3px solid var(--success); }
.toast.error { border-left:3px solid var(--danger); }
.empty { text-align:center; padding:40px 20px; color:var(--hint); }
.empty .e-icon { font-size:48px; margin-bottom:12px; }
.empty .e-text { font-size:14px; }
.badge { display:inline-block; padding:2px 8px; border-radius:6px; font-size:11px; font-weight:600; }
.badge-info { background:rgba(15,52,96,.4); color:#5dade2; }
.badge-warn { background:rgba(233,69,96,.15); color:var(--danger); }
.spinner { width:24px; height:24px; border:3px solid rgba(255,255,255,.1); border-top-color:var(--link); border-radius:50%; animation:spin .6s linear infinite; margin:20px auto; }
@keyframes spin { to{transform:rotate(360deg)} }
.target-row { background:rgba(255,255,255,.03); border:1px solid rgba(255,255,255,.06); border-radius:10px; padding:12px; margin-bottom:8px; }
.target-row .form-label { margin-top:8px; }
.target-row .form-label:first-child { margin-top:0; }
.target-mini { display:flex; justify-content:space-between; align-items:center; padding:10px 12px; background:rgba(255,255,255,.03); border:1px solid rgba(255,255,255,.06); border-radius:10px; margin-bottom:8px; font-size:13px; }
.target-mini .info { color:var(--hint); flex:1; overflow:hidden; text-overflow:ellipsis; }
.target-mini .info .ch-name { color:var(--text); font-weight:600; }

/* 格式工具栏 */
.format-toolbar { display:flex; gap:4px; margin-bottom:6px; flex-wrap:wrap; }
.format-toolbar button { padding:6px 10px; border:1px solid rgba(255,255,255,.1); background:rgba(255,255,255,.05); color:var(--text); border-radius:6px; font-size:13px; cursor:pointer; transition:all .15s; min-width:34px; }
.format-toolbar button:active { background:rgba(233,69,96,.25); transform:scale(.92); }
.format-toolbar button:hover { background:rgba(255,255,255,.1); }

/* 预览区 */
.preview-box { background:var(--card); border:1px solid rgba(255,255,255,.08); border-radius:10px; padding:12px 14px; font-size:14px; min-height:50px; line-height:1.6; word-break:break-word; color:var(--text); }
.preview-box .tg-spoiler { background:var(--hint); color:transparent; border-radius:4px; padding:0 3px; cursor:pointer; transition:all .2s; }
.preview-box .tg-spoiler:hover,.preview-box .tg-spoiler.revealed { color:var(--text); background:rgba(255,255,255,.1); }
.preview-box blockquote { border-left:3px solid var(--hint); padding-left:8px; margin:6px 0; color:var(--hint); }
.preview-box pre { background:rgba(0,0,0,.3); border-radius:6px; padding:8px; font-size:12px; overflow-x:auto; }
.preview-box code { background:rgba(255,255,255,.08); padding:1px 5px; border-radius:4px; font-size:12px; color:var(--link); }
.preview-box a { color:var(--link); text-decoration:underline; }

/* 媒体预览 */
.media-preview-box { margin-top:8px; position:relative; }
.media-preview-box img,.media-preview-box video { max-width:100%; max-height:200px; border-radius:8px; display:block; }
.media-preview-box .media-clear { position:absolute; top:4px; right:4px; background:rgba(0,0,0,.7); color:#fff; border:none; border-radius:50%; width:24px; height:24px; font-size:14px; cursor:pointer; display:flex; align-items:center; justify-content:center; }
</style>
</head>
<body>

<div class="header">
  <div class="header-content">
    <div id="avatarContainer"><div class="avatar-placeholder">👤</div></div>
    <div class="header-text">
      <h1>Nine7<img src="https://lin7zhi.pages.dev/file/1777856634364_nine7.png"
         style="width:22px;height:22px;vertical-align:middle;margin-right:6px;border-radius:6px;filter:drop-shadow(0 0 6px rgba(233,69,96,.4))"
         onerror="this.style.display='none'">频道助手</h1>
      <p class="header-greeting" id="headerGreeting">你好!</p>
      <p id="headerSub">加载中...</p>
    </div>
  </div>
</div>

<div class="toast" id="toast"></div>

<!-- ===== 首页 ===== -->
<div class="page active" id="page-home">
  <div class="card"><div class="card-title">⚙️ 系统状态</div><div class="card-body" id="statusInfo"><div class="spinner"></div></div></div>
  <div class="card"><div class="card-title">📊 概览</div><div class="card-body" id="overview"><div class="spinner"></div></div></div>
</div>

<!-- ===== 同步页 ===== -->
<div class="page" id="page-sync"><div id="syncList"></div><button class="fab" onclick="openModal('modalAddSync')"></button></div>

<!-- ===== 工具箱 ===== -->
<div class="page" id="page-tools">
  <div class="tool-grid">
    <div class="tool-card" onclick="openModal('modalBtnNew')"><div class="t-icon">🆕</div><div class="t-name">发按钮消息</div><div class="t-desc">支持媒体+格式+预览</div></div>
    <div class="tool-card" onclick="openModal('modalBtnOld')"><div class="t-icon">🔘</div><div class="t-name">改旧按钮</div><div class="t-desc">给旧消息加/改/删按钮</div></div>
    <div class="tool-card" onclick="openModal('modalGenDir')"><div class="t-icon">🗂️</div><div class="t-name">手动目录</div><div class="t-desc">扫描频道生成标签目录</div></div>
    <div class="tool-card" onclick="openModal('modalReplace')"><div class="t-icon">🔄</div><div class="t-name">替换标签</div><div class="t-desc">批量替换/删除标签</div></div>
    <div class="tool-card" onclick="openModal('modalBackup')"><div class="t-icon">🚀</div><div class="t-name">智能备份</div><div class="t-desc">跨频道全量搬运</div></div>
    <div class="tool-card" onclick="openModal('modalBtnMulti')"><div class="t-icon">🔗</div><div class="t-name">多按钮消息</div><div class="t-desc">添加多个按钮行</div></div>
    <div class="tool-card" onclick="openModal('modalBatchCreate')"><div class="t-icon">🏢</div><div class="t-name">批量建频道</div><div class="t-desc">一键批量建频道</div></div>
    <div class="tool-card" onclick="openModal('modalBackupMembers')"><div class="t-icon">👥</div><div class="t-name">备份成员</div><div class="t-desc">导出频道成员ID和用户名</div></div>
  </div>
</div>

<!-- ===== 任务页 ===== -->
<div class="page" id="page-tasks">
  <div class="segment">
    <button class="seg-btn active" onclick="switchTaskTab(this,'statsList')">📈 统计任务</button>
    <button class="seg-btn" onclick="switchTaskTab(this,'dirsList')">📂 目录任务</button>
  </div>
  <div id="statsList"></div>
  <div id="dirsList" style="display:none"></div>
  <button class="fab" onclick="openAddTask()"></button>
</div>

<!-- ===== 地址簿页 ===== -->
<div class="page" id="page-addr"><div id="addrList"></div><button class="fab" onclick="openModal('modalAddAddr')"></button></div>

<!-- ===== 底栏 ===== -->
<div class="bottom-nav">
  <div class="nav-item active" onclick="switchPage('home',this)"><div class="icon">🏠</div><div class="label">首页</div></div>
  <div class="nav-item" onclick="switchPage('sync',this)"><div class="icon">🔄</div><div class="label">同步</div></div>
  <div class="nav-item" onclick="switchPage('tools',this)"><div class="icon">🧰</div><div class="label">工具箱</div></div>
  <div class="nav-item" onclick="switchPage('tasks',this)"><div class="icon">📊</div><div class="label">任务</div></div>
  <div class="nav-item" onclick="switchPage('addr',this)"><div class="icon">📔</div><div class="label">地址簿</div></div>
</div>

<!-- ========== 同步组弹窗 ========== -->
<div class="modal-overlay" id="modalAddSync"><div class="modal">
  <div class="modal-title">➕ 添加同步组 <button class="modal-close" onclick="closeModal('modalAddSync')"></button></div>
  <div class="form-group"><label class="form-label">同步组名称 (可选)</label><input class="form-input" id="syncName" placeholder="如: 主频道分发"></div>
  <div class="form-group"><label class="form-label">源频道 ID</label><input class="form-input" id="syncSrc" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerSyncSrc"></div></div>
  <p class="form-label" style="font-weight:700;color:var(--text)">目标频道 (可多个)</p>
  <div id="syncTgtContainer"><div class="form-group"><input class="form-input sync-tgt" placeholder="-100xxxxxxxxxx"><div class="channel-picker"></div></div></div>
  <button class="btn btn-ghost btn-sm" onclick="addSyncTgtRow()" style="margin-bottom:12px">➕ 添加目标频道</button>
  <button class="btn btn-primary btn-block" onclick="addSyncGroup()">✅ 创建同步组</button>
</div></div>

<!-- ========== 地址簿弹窗 ========== -->
<div class="modal-overlay" id="modalAddAddr"><div class="modal">
  <div class="modal-title">📔 添加频道 <button class="modal-close" onclick="closeModal('modalAddAddr')"></button></div>
  <div class="form-group"><label class="form-label">频道 ID</label><input class="form-input" id="addrId" placeholder="-100xxxxxxxxxx"></div>
  <div class="form-group"><label class="form-label">备注名称</label><input class="form-input" id="addrName" placeholder="如: 主频道"></div>
  <button class="btn btn-primary btn-block" onclick="addChannel()">✅ 保存</button>
</div></div>

<!-- ========== 🆕 发按钮消息(媒体+格式+预览)========== -->
<div class="modal-overlay" id="modalBtnNew"><div class="modal">
  <div class="modal-title">🆕 发送消息 <button class="modal-close" onclick="closeModal('modalBtnNew')"></button></div>
  <div class="form-group">
    <label class="form-label">频道 ID</label>
    <input class="form-input" id="bnCh" placeholder="-100xxxxxxxxxx">
    <div class="channel-picker" id="pickerBnCh"></div>
  </div>
  <div class="form-group">
    <label class="form-label">📎 附加媒体文件 (可选)</label>
    <input type="file" id="bnMedia" accept="image/*,video/*,.gif" class="form-input" style="padding:8px" onchange="previewMedia(this,'bnMediaPreview')">
    <div class="form-hint">支持图片/视频/GIF,不选则发纯文本消息</div>
    <div class="media-preview-box" id="bnMediaPreview"></div>
  </div>
  <div class="form-group">
    <label class="form-label">消息正文 (支持 HTML 格式)</label>
    <div class="format-toolbar">
      <button type="button" onclick="insertFmt('b')" title="粗体"><b>B</b></button>
      <button type="button" onclick="insertFmt('i')" title="斜体"><i>I</i></button>
      <button type="button" onclick="insertFmt('u')" title="下划线"><u>U</u></button>
      <button type="button" onclick="insertFmt('s')" title="删除线"><s>S</s></button>
      <button type="button" onclick="insertFmt('code')" title="行内代码">&lt;/&gt;</button>
      <button type="button" onclick="insertFmt('tg-spoiler')" title="遮罩文字">👁</button>
      <button type="button" onclick="insertLink()" title="超链接">🔗</button>
      <button type="button" onclick="insertFmt('blockquote')" title="引用块"></button>
      <button type="button" onclick="insertFmt('pre')" title="代码块">PRE</button>
    </div>
    <textarea class="form-input" id="bnText" rows="5" placeholder="输入消息内容,点击上方按钮快速插入格式..." oninput="updatePreview()"></textarea>
  </div>
  <div class="form-group">
    <label class="form-label">📱 实时预览</label>
    <div class="preview-box" id="bnPreview"><span style="color:var(--hint)">输入内容后预览将显示在这里</span></div>
  </div>
  <div class="form-group"><label class="form-label">按钮文字 (可选,留空则无按钮)</label><input class="form-input" id="bnBtnText" placeholder="🔗 点击进入主群"></div>
  <div class="form-group"><label class="form-label">按钮链接 (可选)</label><input class="form-input" id="bnUrl" placeholder="https://..." type="url"></div>
  <button class="btn btn-primary btn-block" onclick="sendBtnNew()">🚀 发送</button>
</div></div>

<!-- ========== 改旧按钮 ========== -->
<div class="modal-overlay" id="modalBtnOld"><div class="modal">
  <div class="modal-title">🔘 给旧消息加/改按钮 <button class="modal-close" onclick="closeModal('modalBtnOld')"></button></div>
  <div class="form-group"><label class="form-label">频道 ID</label><input class="form-input" id="boCh" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerBoCh"></div></div>
  <div class="form-group"><label class="form-label">消息 ID 或链接</label><input class="form-input" id="boMsg" placeholder="消息 ID 或链接"></div>
  <div class="form-group"><label class="form-label">按钮文字 (输入"删除"以移除按钮)</label><input class="form-input" id="boBtnText" placeholder="按钮文字 或 删除"></div>
  <div class="form-group"><label class="form-label">跳转链接</label><input class="form-input" id="boUrl" placeholder="https://..." type="url"></div>
  <button class="btn btn-primary btn-block" onclick="sendBtnOld()">✅ 提交</button>
</div></div>

<!-- ========== 多按钮消息 ========== -->
<div class="modal-overlay" id="modalBtnMulti"><div class="modal">
  <div class="modal-title">🔗 多按钮消息 <button class="modal-close" onclick="closeModal('modalBtnMulti')"></button></div>
  <div class="form-group"><label class="form-label">频道 ID</label><input class="form-input" id="bmCh" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerBmCh"></div></div>
  <div class="form-group"><label class="form-label">消息正文 (支持 HTML)</label><textarea class="form-input" id="bmText" rows="3" placeholder="消息内容..."></textarea></div>
  <div id="bmBtnsContainer"><div class="form-group" style="display:flex;gap:8px"><input class="form-input" placeholder="按钮文字" style="flex:1"><input class="form-input" placeholder="https://链接" style="flex:1"></div></div>
  <button class="btn btn-ghost btn-sm" onclick="addBtnRow()" style="margin-bottom:12px">➕ 再加一行按钮</button>
  <button class="btn btn-primary btn-block" onclick="sendBtnMulti()">🚀 发送</button>
</div></div>

<!-- ========== 手动目录 ========== -->
<div class="modal-overlay" id="modalGenDir"><div class="modal">
  <div class="modal-title">🗂️ 生成手动目录 <button class="modal-close" onclick="closeModal('modalGenDir')"></button></div>
  <div class="form-group"><label class="form-label">频道 ID</label><input class="form-input" id="gdCh" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerGdCh"></div></div>
  <p class="form-hint">⚠️ 扫描可能需要较长时间,结果将发送到机器人对话中</p>
  <button class="btn btn-primary btn-block" style="margin-top:12px" onclick="genDir()">🔍 开始扫描</button>
</div></div>

<!-- ========== 替换标签 ========== -->
<div class="modal-overlay" id="modalReplace"><div class="modal">
  <div class="modal-title">🔄 批量替换标签 <button class="modal-close" onclick="closeModal('modalReplace')"></button></div>
  <div class="form-group"><label class="form-label">频道 ID</label><input class="form-input" id="rpCh" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerRpCh"></div></div>
  <div class="form-group"><label class="form-label">旧标签 (带 #)</label><input class="form-input" id="rpOld" placeholder="#旧标签"></div>
  <div class="form-group"><label class="form-label">新标签 (输入"删除"则彻底移除)</label><input class="form-input" id="rpNew" placeholder="#新标签 或 删除"></div>
  <button class="btn btn-primary btn-block" onclick="replaceTag()">🚀 开始替换</button>
</div></div>

<!-- ========== 智能备份(多目标)========== -->
<div class="modal-overlay" id="modalBackup"><div class="modal">
  <div class="modal-title">🚀 智能备份 <button class="modal-close" onclick="closeModal('modalBackup')"></button></div>
  <div id="backupGroupBtns" style="margin-bottom:12px"></div>
  <hr style="border-color:rgba(255,255,255,.06);margin:12px 0">
  <p class="form-label" style="margin-bottom:8px">✏️ 手动指定通道:</p>
  <div class="form-group"><label class="form-label">源频道 ID</label><input class="form-input" id="bkSrc" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerBkSrc"></div></div>
  <p class="form-label" style="font-weight:700;color:var(--text)">目标频道 (可多个)</p>
  <div id="bkTgtContainer"><div class="form-group"><input class="form-input bk-tgt" placeholder="-100xxxxxxxxxx"><div class="channel-picker"></div></div></div>
  <button class="btn btn-ghost btn-sm" onclick="addBkTgtRow()" style="margin-bottom:12px">➕ 添加目标频道</button>
  <div class="form-group"><label class="form-label">源频道最新消息链接</label><input class="form-input" id="bkLink" placeholder="https://t.me/..."></div>
  <div class="form-group" style="display:flex;align-items:center;justify-content:space-between;background:rgba(255,255,255,.03);padding:14px;border-radius:10px;border:1px solid rgba(255,255,255,.06)">
    <div>
      <div style="font-size:13px;font-weight:600">🔄 洗文件 MD5</div>
      <div style="font-size:11px;color:var(--hint);margin-top:2px">下载→改哈希→重传,速度较慢但文件唯一</div>
    </div>
    <label style="position:relative;display:inline-block;width:48px;height:26px;flex-shrink:0;margin-left:12px">
      <input type="checkbox" id="bkWash" style="opacity:0;width:0;height:0">
      <span style="position:absolute;cursor:pointer;inset:0;background:rgba(255,255,255,.12);border-radius:26px;transition:.3s"></span>
      <span id="bkWashDot" style="position:absolute;left:3px;top:3px;width:20px;height:20px;background:#fff;border-radius:50%;transition:.3s"></span>
    </label>
  </div>
  <button class="btn btn-primary btn-block" onclick="startBackup()">🚀 开始备份</button>
</div></div>

<!-- ========== 创建统计任务 ========== -->
<div class="modal-overlay" id="modalAddStat"><div class="modal">
  <div class="modal-title">📈 创建统计任务 <button class="modal-close" onclick="closeModal('modalAddStat')"></button></div>
  <div class="form-group"><label class="form-label">任务名称</label><input class="form-input" id="stName" placeholder="日常早报统计"></div>
  <div class="form-group"><label class="form-label">频道 ID</label><input class="form-input" id="stCh" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerStCh"></div></div>
  <div class="form-group"><label class="form-label">消息 ID 或链接</label><input class="form-input" id="stMsg" placeholder="311"></div>
  <div class="form-group"><label class="form-label">统计表标题</label><input class="form-input" id="stTitle" placeholder="🔥 霸榜热评区:"></div>
  <div class="form-group"><label class="form-label">显示前几名</label><input class="form-input" id="stTopN" placeholder="10" type="number"></div>
  <div class="form-group"><label class="form-label">触发标签 (带 #)</label><input class="form-input" id="stTrig" placeholder="#更新"></div>
  <div class="form-group"><label class="form-label">更新频率 (分钟)</label><input class="form-input" id="stIntv" placeholder="15" type="number"></div>
  <div class="form-group"><label class="form-label">寿命期限 (天)</label><input class="form-input" id="stDura" placeholder="7" type="number"></div>
  <div class="form-group"><label class="form-label">屏蔽名单 (空格隔开,无则留空)</label><input class="form-input" id="stBlack" placeholder="名字A 名字B"></div>
  <div class="form-group"><label class="form-label">屏蔽区标题 (留空则默认)</label><input class="form-input" id="stBlTitle" placeholder="🚫本月轮换限制:"></div>
  <div class="form-group">
    <label class="form-label">📥 上期榜单消息 ID (可选,自动提取名字加入屏蔽)</label>
    <input class="form-input" id="stExtractMsg" placeholder="留空则跳过">
    <div class="form-hint">💡 输入上一期统计消息 ID 或链接,系统自动提取上榜名字加入屏蔽名单</div>
  </div>
  <button class="btn btn-primary btn-block" onclick="addStatTask()">✅ 创建任务</button>
</div></div>

<!-- ========== 创建自动目录 ========== -->
<div class="modal-overlay" id="modalAddDir"><div class="modal">
  <div class="modal-title">🗂️ 创建自动目录 <button class="modal-close" onclick="closeModal('modalAddDir')"></button></div>
  <div class="form-group"><label class="form-label">任务名称</label><input class="form-input" id="drName" placeholder="主频道自动目录"></div>
  <div class="form-group"><label class="form-label">🔍 扫描频道 ID</label><input class="form-input" id="drScanCh" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerDrScan"></div></div>
  <hr style="border-color:rgba(255,255,255,.06);margin:12px 0">
  <p class="form-label" style="font-weight:700;color:var(--text);margin-bottom:8px">📌 目标频道</p>
  <div id="drTargetsContainer">
    <div class="target-row" data-idx="0">
      <label class="form-label">目标 1 - 频道 ID</label>
      <input class="form-input dr-tgt-ch" placeholder="-100xxxxxxxxxx">
      <div class="channel-picker"></div>
      <label class="form-label">目标 1 - 消息 ID</label>
      <input class="form-input dr-tgt-msg" placeholder="消息ID">
    </div>
  </div>
  <button class="btn btn-ghost btn-sm" onclick="addDirTargetRow()" style="margin-bottom:12px">➕ 添加更多目标</button>
  <hr style="border-color:rgba(255,255,255,.06);margin:12px 0">
  <div class="form-group"><label class="form-label">屏蔽标签 (空格隔开,无则留空)</label><input class="form-input" id="drBlack" placeholder="#通知 #避雷"></div>
  <button class="btn btn-primary btn-block" onclick="addDirTask()">✅ 创建</button>
</div></div>

<!-- ========== 添加目录目标 ========== -->
<div class="modal-overlay" id="modalAddDirTarget"><div class="modal">
  <div class="modal-title">➕ 添加目标频道 <button class="modal-close" onclick="closeModal('modalAddDirTarget')"></button></div>
  <div class="form-group"><label class="form-label">目标频道 ID</label><input class="form-input" id="adtCh" placeholder="-100xxxxxxxxxx"><div class="channel-picker" id="pickerAdtCh"></div></div>
  <div class="form-group"><label class="form-label">承载消息 ID</label><input class="form-input" id="adtMsg" placeholder="消息ID"></div>
  <button class="btn btn-primary btn-block" onclick="submitAddDirTarget()">✅ 添加</button>
</div></div>

<!-- ========== 移除目录目标 ========== -->
<div class="modal-overlay" id="modalRmDirTarget"><div class="modal">
  <div class="modal-title">➖ 移除目标频道 <button class="modal-close" onclick="closeModal('modalRmDirTarget')"></button></div>
  <div id="rmDirTargetList"></div>
</div></div>

<!-- ========== 编辑弹窗 ========== -->
<div class="modal-overlay" id="modalEdit"><div class="modal">
  <div class="modal-title" id="editTitle">✏️ 编辑 <button class="modal-close" onclick="closeModal('modalEdit')"></button></div>
  <div class="form-group">
    <label class="form-label" id="editLabel">新值</label>
    <input class="form-input" id="editVal">
    <div class="channel-picker" id="pickerEditVal"></div>
  </div>
  <button class="btn btn-primary btn-block" onclick="submitEdit()">✅ 确认修改</button>
</div></div>

<!-- ========== 批量建频道 ========== -->
<div class="modal-overlay" id="modalBatchCreate"><div class="modal">
  <div class="modal-title">🏢 批量创建频道 <button class="modal-close" onclick="closeModal('modalBatchCreate')"></button></div>
  <div class="form-group">
    <label class="form-label">频道名称列表 (每行一个)</label>
    <textarea class="form-input" id="bcNames" rows="5" placeholder="频道名称A&#10;频道名称B&#10;频道名称C"></textarea>
  </div>
  <div class="form-group">
    <label class="form-label">每个名称创建数量</label>
    <input class="form-input" id="bcCount" type="number" value="1" min="1" placeholder="例如 9 → 名1..名9">
    <div class="form-hint">💡 数量 1 不加后缀,数量 3 则创建:名称1、名称2、名称3</div>
  </div>
  <div class="form-group">
    <label class="form-label">自动拉入的用户/机器人 ID</label>
    <input class="form-input" id="bcUsers" placeholder="@your_bot 123456789">
    <div class="form-hint">💡 空格、逗号或换行隔开</div>
  </div>
  <p class="form-hint" style="color:var(--danger)">⚠️ 耗时较长,请到 Bot 对话查看进度</p>
  <button class="btn btn-primary btn-block" style="margin-top:12px" onclick="startBatchCreate()">🚀 开始批量创建</button>
</div></div>

<!-- ========== 🆕 备份频道成员 ========== -->
<div class="modal-overlay" id="modalBackupMembers"><div class="modal">
  <div class="modal-title">👥 备份频道成员 <button class="modal-close" onclick="closeModal('modalBackupMembers')"></button></div>
  <div class="form-group">
    <label class="form-label">频道 / 群组 ID</label>
    <input class="form-input" id="bmChId" placeholder="-100xxxxxxxxxx">
    <div class="channel-picker" id="pickerBmChId"></div>
  </div>
  <div class="form-hint" style="margin-bottom:12px">
    📋 将导出所有成员的 UserID、Username、昵称等信息为 CSV 文件<br>
    ☁️ 文件将同时上传 WebDAV (<code>members/</code> 目录) 并发送到 Bot 对话
  </div>
  <button class="btn btn-primary btn-block" onclick="backupMembers()">📥 开始导出</button>
</div></div>

<script>
const tg = window.Telegram.WebApp;
tg.ready(); tg.expand(); tg.enableClosingConfirmation();

const API = '/api';
const initData = tg.initData || '';
const user = tg.initDataUnsafe?.user;
let userData = null;
let currentTaskTab = 'stats';
let editCtx = {};
let dirTargetCtx = {};

if (user) {
  const ac = document.getElementById('avatarContainer');
  if (user.photo_url) {
    ac.innerHTML = `<img class="avatar" src="${user.photo_url}" onerror="this.outerHTML='<div class=\\'avatar-placeholder\\'>${user.first_name?user.first_name[0]:'👤'}</div>'">`;
  } else {
    ac.innerHTML = `<div class="avatar-placeholder">${user.first_name?user.first_name[0]:'👤'}</div>`;
  }
  const h = new Date().getHours();
  let g = '🌙 晚上好';
  if(h>=5&&h<12) g='🌅 早上好'; else if(h>=12&&h<14) g='☀️ 中午好'; else if(h>=14&&h<18) g='🌤 下午好';
  document.getElementById('headerGreeting').textContent = `${g}${user.first_name}!`;
  document.getElementById('headerSub').textContent = `UID: ${user.id}`;
} else {
  document.getElementById('headerGreeting').textContent = '';
  document.getElementById('headerSub').textContent = '未检测到用户';
}

function chLabel(id) {
  if(!id) return '<code>未设置</code>';
  const ab = userData?.address_book||{};
  const name = ab[id]||ab[String(id)];
  return name ? `<span class="ch-name">📔${name}</span> <code>${id}</code>` : `<code>${id}</code>`;
}
function chNameOnly(id) {
  if(!id) return '未设置';
  const ab = userData?.address_book||{};
  const name = ab[id]||ab[String(id)];
  return name ? `📔${name} (${id})` : String(id);
}

function toast(msg, type='success') {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.className = `toast show ${type}`;
  setTimeout(()=>t.className='toast', 2800);
}

async function api(path, method='GET', body=null) {
  const opts = { method, headers:{'Content-Type':'application/json','X-Init-Data':initData} };
  if(body) opts.body = JSON.stringify(body);
  return (await fetch(API+path, opts)).json();
}

function switchPage(name, el) {
  document.querySelectorAll('.page').forEach(p=>p.classList.remove('active'));
  document.querySelectorAll('.nav-item').forEach(n=>n.classList.remove('active'));
  document.getElementById('page-'+name).classList.add('active');
  el.classList.add('active');
  if(name==='sync') renderSync();
  if(name==='tasks') renderTasks();
  if(name==='addr') renderAddr();
  if(name==='home') loadHome();
}

function openModal(id) {
  document.getElementById(id).classList.add('open');
  renderChannelPickers();
  if(id==='modalBackup') renderBackupGroups();
}
function closeModal(id) { document.getElementById(id).classList.remove('open'); }
document.querySelectorAll('.modal-overlay').forEach(o=>{
  o.addEventListener('click',e=>{if(e.target===o) o.classList.remove('open');});
});

/* ====== 频道快选 ====== */
function renderChannelPickers() {
  if(!userData) return;
  const ab = userData.address_book||{};
  document.querySelectorAll('.channel-picker').forEach(picker => {
    picker.innerHTML = '';
    Object.entries(ab).forEach(([cid,name])=>{
      const chip = document.createElement('div');
      chip.className = 'ch-chip';
      chip.textContent = `📔 ${name}`;
      chip.onclick = () => {
        const inp = picker.previousElementSibling;
        if(inp && (inp.classList.contains('form-input')||inp.tagName==='INPUT')) inp.value = cid;
        chip.classList.add('picked');
        setTimeout(()=>chip.classList.remove('picked'),600);
        try{tg.HapticFeedback.impactOccurred('light')}catch(e){}
      };
      picker.appendChild(chip);
    });
  });
}

/* ====== 🆕 格式工具栏 ====== */
function insertFmt(tag) {
  const ta = document.getElementById('bnText');
  const start = ta.selectionStart, end = ta.selectionEnd;
  const sel = ta.value.substring(start, end);
  const wrapped = `<${tag}>${sel || '文本'}</${tag}>`;
  ta.value = ta.value.substring(0, start) + wrapped + ta.value.substring(end);
  ta.focus();
  const newPos = start + tag.length + 2 + (sel||'文本').length;
  ta.setSelectionRange(start + tag.length + 2, newPos);
  updatePreview();
  try{tg.HapticFeedback.impactOccurred('light')}catch(e){}
}

function insertLink() {
  const ta = document.getElementById('bnText');
  const start = ta.selectionStart, end = ta.selectionEnd;
  const sel = ta.value.substring(start, end);
  const linkText = sel || '链接文字';
  const wrapped = `<a href="https://">${linkText}</a>`;
  ta.value = ta.value.substring(0, start) + wrapped + ta.value.substring(end);
  ta.focus();
  const urlStart = start + 9; // position after href="
  ta.setSelectionRange(urlStart, urlStart + 8);
  updatePreview();
}

function updatePreview() {
  const text = document.getElementById('bnText').value;
  const preview = document.getElementById('bnPreview');
  if(!text.trim()) {
    preview.innerHTML = '<span style="color:var(--hint)">输入内容后预览将显示在这里</span>';
    return;
  }
  // 安全地渲染预览(只允许 Telegram 支持的标签)
  let html = text;
  // 将换行转为 <br>
  html = html.replace(/\n/g, '<br>');
  preview.innerHTML = html;
  // 遮罩文字点击切换
  preview.querySelectorAll('.tg-spoiler').forEach(el=>{
    el.onclick = ()=> el.classList.toggle('revealed');
  });
}

/* ====== 🆕 媒体预览 ====== */
function previewMedia(input, previewId) {
  const container = document.getElementById(previewId);
  container.innerHTML = '';
  if(!input.files||!input.files[0]) return;
  const file = input.files[0];
  const url = URL.createObjectURL(file);
  let el;
  if(file.type.startsWith('video/')) {
    el = document.createElement('video');
    el.src = url; el.controls = true; el.muted = true;
  } else {
    el = document.createElement('img');
    el.src = url;
  }
  const clearBtn = document.createElement('button');
  clearBtn.className = 'media-clear';
  clearBtn.innerHTML = '✕';
  clearBtn.onclick = ()=>{ input.value=''; container.innerHTML=''; };
  container.appendChild(el);
  container.appendChild(clearBtn);
}

/* ====== 首页 ====== */
async function loadHome() {
  const data = await api('/data');
  if(!data.ok) return;
  userData = data.user;
  document.getElementById('statusInfo').innerHTML = `
    <div class="stat-row"><span>☁️ 云端路径</span><span class="stat-val" style="font-size:11px;max-width:160px;overflow:hidden;text-overflow:ellipsis">${data.webdav_url||'未设置'}</span></div>
    <div class="stat-row"><span>🗺️ 消息映射</span><span class="stat-val">${data.msg_count} 条</span></div>
    <div class="stat-row"><span>🤖 Userbot</span><span class="stat-val">${data.userbot?'✅ 在线':'❌ 离线'}</span></div>`;
  const g=userData.groups||[], s=userData.stats_tasks||[], d=userData.dir_tasks||[], ab=userData.address_book||{};
  document.getElementById('overview').innerHTML = `
    <div class="stat-row"><span>🔄 同步组</span><span class="stat-val">${g.length}</span></div>
    <div class="stat-row"><span>📈 统计任务</span><span class="stat-val">${s.length}</span></div>
    <div class="stat-row"><span>📂 目录任务</span><span class="stat-val">${d.length}</span></div>
    <div class="stat-row"><span>📔 地址簿</span><span class="stat-val">${Object.keys(ab).length} 个频道</span></div>`;
}

/* ====== 同步组 ====== */
function addSyncTgtRow() {
  const c = document.getElementById('syncTgtContainer');
  const div = document.createElement('div');
  div.className = 'form-group';
  div.innerHTML = `<input class="form-input sync-tgt" placeholder="-100xxxxxxxxxx"><div class="channel-picker"></div>`;
  c.appendChild(div);
  renderChannelPickers();
}

function renderSync() {
  const list = document.getElementById('syncList');
  const groups = userData?.groups||[];
  if(!groups.length) {
    list.innerHTML='<div class="empty"><div class="e-icon">🔄</div><div class="e-text">暂无同步任务<br>点击右下角 + 创建</div></div>';
    return;
  }
  list.innerHTML = groups.map((g,i)=>{
    let tgts = g.tgt; if(typeof tgts==='string') tgts=[tgts];
    const tgtHtml = (tgts||[]).map(t=>`<div style="margin-left:8px">▪️ ${chLabel(t)}</div>`).join('');
    const nm = g.name||`同步组 ${i+1}`;
    return `<div class="card">
      <div class="card-title">📦 ${nm}</div>
      <div class="card-body">源频道: ${chLabel(g.src)}<br>目标频道:<br>${tgtHtml}</div>
      <div class="card-actions"><button class="btn btn-danger btn-sm" onclick="delSync(${i})">🗑 删除</button></div>
    </div>`;
  }).join('');
}

async function addSyncGroup() {
  const name = document.getElementById('syncName').value.trim();
  const src = document.getElementById('syncSrc').value.trim();
  const tgts = [];
  document.querySelectorAll('#syncTgtContainer .sync-tgt').forEach(i=>{const v=i.value.trim();if(v)tgts.push(v);});
  if(!src||!tgts.length) return toast('请填写源频道和至少一个目标','error');
  const res = await api('/groups','POST',{name,src,tgt:tgts});
  if(res.ok){toast('✅ 同步组已创建');closeModal('modalAddSync');userData=res.user;renderSync();}
  else toast(res.msg||'失败','error');
}

async function delSync(idx) {
  tg.showConfirm('确认删除该同步组?',async(ok)=>{
    if(!ok)return;
    const res=await api(`/groups/${idx}`,'DELETE');
    if(res.ok){toast('已删除');userData=res.user;renderSync();}
  });
}

/* ====== 地址簿 ====== */
function renderAddr() {
  const list=document.getElementById('addrList'), ab=userData?.address_book||{}, entries=Object.entries(ab);
  if(!entries.length){list.innerHTML='<div class="empty"><div class="e-icon">📔</div><div class="e-text">暂无保存的频道<br>点击右下角 + 添加</div></div>';return;}
  list.innerHTML=entries.map(([c,n])=>`
    <div class="card"><div class="card-title">📔 ${n}</div><div class="card-body"><code>${c}</code></div>
    <div class="card-actions"><button class="btn btn-danger btn-sm" onclick="delAddr('${c}')">🗑 删除</button></div></div>`).join('');
}
async function addChannel() {
  const id=document.getElementById('addrId').value.trim(), name=document.getElementById('addrName').value.trim();
  if(!id||!name) return toast('请填写完整','error');
  const res=await api('/channels','POST',{id,name});
  if(res.ok){toast('✅ 已添加');closeModal('modalAddAddr');userData=res.user;renderAddr();renderChannelPickers();}
}
async function delAddr(cid) {
  tg.showConfirm('确认删除?',async(ok)=>{
    if(!ok)return;
    const res=await api(`/channels/${encodeURIComponent(cid)}`,'DELETE');
    if(res.ok){toast('已删除');userData=res.user;renderAddr();renderChannelPickers();}
  });
}

/* ====== 任务 ====== */
function switchTaskTab(el,listId) {
  document.querySelectorAll('.seg-btn').forEach(b=>b.classList.remove('active'));
  el.classList.add('active');
  currentTaskTab=listId==='statsList'?'stats':'dirs';
  document.getElementById('statsList').style.display=listId==='statsList'?'':'none';
  document.getElementById('dirsList').style.display=listId==='dirsList'?'':'none';
}
function openAddTask() { openModal(currentTaskTab==='stats'?'modalAddStat':'modalAddDir'); }
function renderTasks() { renderStatsTasks(); renderDirsTasks(); }

function renderStatsTasks() {
  const list=document.getElementById('statsList'), tasks=userData?.stats_tasks||[];
  if(!tasks.length){list.innerHTML='<div class="empty"><div class="e-icon">📈</div><div class="e-text">暂无统计任务</div></div>';return;}
  list.innerHTML=tasks.map((t,i)=>`
    <div class="card">
      <div class="card-title">🎯 ${t.task_name||'未命名'} <span class="badge badge-info">每${t.interval||60}分钟</span></div>
      <div class="card-body">
        频道: ${chLabel(t.channel_id)} | 消息: <code>${t.msg_id}</code><br>
        表头: <code>${t.table_title||''}</code><br>
        触发: <code>${t.trigger_tag||''}</code> | 前 <code>${t.top_n||10}</code> 名 | 寿命 <code>${t.duration||7}</code> 天<br>
        🚫 屏蔽: <code>${(t.stats_blacklist||[]).join(', ')||'无'}</code><br>
        📝 屏蔽标题: <code>${t.blacklist_title||'默认'}</code>
      </div>
      <div class="card-actions">
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'task_name','任务名称')">✏️名称</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'channel_id','频道ID',true)">✏️频道</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'msg_id','消息ID')">✏️消息</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'table_title','表头标题')">✏️表头</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'trigger_tag','触发标签')">✏️标签</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'top_n','上榜名额')">🏆名额</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'interval','更新频率(分钟)')">⏱频率</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'duration','寿命(天)')">⏳寿命</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'add_stats_bl','添加屏蔽(空格隔开)')">🚫加屏蔽</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'rm_stats_bl','解除屏蔽(空格隔开)')">✅删屏蔽</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'blacklist_title','屏蔽区标题')">📝屏蔽标题</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('stats',${i},'extract_blacklist','上期榜单消息ID')">📥提取屏蔽</button>
        <button class="btn btn-danger btn-sm" onclick="delTask('stats',${i})">🗑 删除</button>
      </div>
    </div>`).join('');
}

function renderDirsTasks() {
  const list=document.getElementById('dirsList'), tasks=userData?.dir_tasks||[];
  if(!tasks.length){list.innerHTML='<div class="empty"><div class="e-icon">📂</div><div class="e-text">暂无目录任务</div></div>';return;}
  list.innerHTML=tasks.map((t,i)=>{
    const targets=t.targets||[];
    const tgtHtml=targets.length?targets.map((tgt,ti)=>
      `<div class="target-mini"><span class="info">${ti+1}. ${chLabel(tgt.channel_id)} | 消息 <code>${tgt.msg_id}</code></span></div>`
    ).join(''):'<span style="color:var(--hint)">暂无目标</span>';
    return `<div class="card">
      <div class="card-title">🗂️ ${t.task_name||'未命名'} <span class="badge badge-info">每${t.interval||15}分钟</span></div>
      <div class="card-body">
        🔍 扫描: ${chLabel(t.scan_id)}<br>
        📌 目标频道:<br>${tgtHtml}
        屏蔽: <code>${(t.blacklist||[]).join(', ')||'无'}</code><br>
        已收录: <code>${(t.tags_cache||[]).length}</code> 个标签
      </div>
      <div class="card-actions">
        <button class="btn btn-success btn-sm" onclick="openAddTargetModal(${i})">➕目标</button>
        <button class="btn btn-ghost btn-sm" onclick="openRmTargetModal(${i})">➖目标</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('dirs',${i},'add_blacklist','追加屏蔽标签')">➕屏蔽</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('dirs',${i},'rm_blacklist','移除屏蔽标签')">➖屏蔽</button>
        <button class="btn btn-ghost btn-sm" onclick="editField('dirs',${i},'interval','扫描频率(分钟)')">⏱频率</button>
        <button class="btn btn-danger btn-sm" onclick="delTask('dirs',${i})">🗑 删除</button>
      </div>
    </div>`;
  }).join('');
}

async function addStatTask() {
  const body = {
    task_name:document.getElementById('stName').value.trim(),
    channel_id:document.getElementById('stCh').value.trim(),
    msg_id:document.getElementById('stMsg').value.trim(),
    table_title:document.getElementById('stTitle').value.trim(),
    top_n:parseInt(document.getElementById('stTopN').value)||10,
    trigger_tag:document.getElementById('stTrig').value.trim(),
    interval:parseInt(document.getElementById('stIntv').value)||15,
    duration:parseInt(document.getElementById('stDura').value)||7,
    stats_blacklist:document.getElementById('stBlack').value.trim(),
    blacklist_title:document.getElementById('stBlTitle').value.trim()||'🚫本月轮换限制:',
    extract_from_msg:document.getElementById('stExtractMsg').value.trim()
  };
  if(!body.task_name||!body.channel_id||!body.msg_id) return toast('请填写必填项','error');
  if(!body.trigger_tag.startsWith('#')) return toast('触发标签必须以#开头','error');
  const res=await api('/stats','POST',body);
  if(res.ok){
    toast('✅ 统计任务已创建');closeModal('modalAddStat');userData=res.user;renderStatsTasks();
    if(body.extract_from_msg) toast('🔍 正在后台提取屏蔽名单...');
  } else toast(res.msg||'创建失败','error');
}

let dirTargetCounter = 1;
function addDirTargetRow() {
  dirTargetCounter++;
  const c = document.getElementById('drTargetsContainer');
  const div = document.createElement('div');
  div.className = 'target-row';
  div.innerHTML = `
    <label class="form-label">目标 ${dirTargetCounter} - 频道 ID</label>
    <input class="form-input dr-tgt-ch" placeholder="-100xxxxxxxxxx">
    <div class="channel-picker"></div>
    <label class="form-label">目标 ${dirTargetCounter} - 消息 ID</label>
    <input class="form-input dr-tgt-msg" placeholder="消息ID">`;
  c.appendChild(div);
  renderChannelPickers();
}

async function addDirTask() {
  const name=document.getElementById('drName').value.trim();
  const scanCh=document.getElementById('drScanCh').value.trim();
  const bl=document.getElementById('drBlack').value.trim();
  const rows=document.querySelectorAll('#drTargetsContainer .target-row');
  const targets=[];
  rows.forEach(r=>{
    const ch=r.querySelector('.dr-tgt-ch').value.trim();
    const msg=r.querySelector('.dr-tgt-msg').value.trim();
    if(ch&&msg) targets.push({channel_id:ch,msg_id:msg});
  });
  if(!name||!scanCh||!targets.length) return toast('请填写完整','error');
  const res=await api('/dirs','POST',{task_name:name,scan_id:scanCh,targets:targets,blacklist:bl?bl.split(/\s+/):[]});
  if(res.ok){toast('✅ 目录任务已创建');closeModal('modalAddDir');userData=res.user;renderDirsTasks();}
  else toast(res.msg||'创建失败','error');
}

function openAddTargetModal(idx) {
  dirTargetCtx={idx};
  document.getElementById('adtCh').value='';
  document.getElementById('adtMsg').value='';
  openModal('modalAddDirTarget');
}
async function submitAddDirTarget() {
  const ch=document.getElementById('adtCh').value.trim();
  const msg=document.getElementById('adtMsg').value.trim();
  if(!ch||!msg) return toast('请填写完整','error');
  const res=await api(`/dirs/${dirTargetCtx.idx}`,'PUT',{field:'add_target',value:JSON.stringify({channel_id:ch,msg_id:msg})});
  if(res.ok){toast('✅ 目标已添加');closeModal('modalAddDirTarget');userData=res.user;renderDirsTasks();}
  else toast(res.msg||'失败','error');
}

function openRmTargetModal(idx) {
  dirTargetCtx={idx};
  const task=userData.dir_tasks[idx];
  const targets=task?.targets||[];
  const list=document.getElementById('rmDirTargetList');
  if(!targets.length){list.innerHTML='<p style="color:var(--hint)">暂无目标频道</p>';openModal('modalRmDirTarget');return;}
  list.innerHTML=targets.map((tgt,ti)=>`
    <div class="target-mini">
      <span class="info">${ti+1}. ${chNameOnly(tgt.channel_id)} | 消息 ${tgt.msg_id}</span>
      <button class="btn btn-danger btn-sm" onclick="rmDirTarget(${idx},${ti})">❌</button>
    </div>`).join('');
  openModal('modalRmDirTarget');
}
async function rmDirTarget(taskIdx,targetIdx) {
  const res=await api(`/dirs/${taskIdx}`,'PUT',{field:'rm_target',value:String(targetIdx)});
  if(res.ok){toast('✅ 已移除');userData=res.user;renderDirsTasks();openRmTargetModal(taskIdx);}
  else toast(res.msg||'失败','error');
}

async function delTask(type,idx) {
  tg.showConfirm('确认删除此任务?',async(ok)=>{
    if(!ok)return;
    const path=type==='stats'?`/stats/${idx}`:`/dirs/${idx}`;
    const res=await api(path,'DELETE');
    if(res.ok){toast('已删除');userData=res.user;renderTasks();}
  });
}

/* ====== 编辑弹窗 ====== */
const CHANNEL_FIELDS = ['channel_id','scan_id'];
function editField(type,idx,field,label,showChPicker) {
  editCtx = {type,idx,field};
  document.getElementById('editTitle').innerHTML = `✏️ 编辑 - ${label} <button class="modal-close" onclick="closeModal('modalEdit')">✕</button>`;
  document.getElementById('editLabel').textContent = label;
  document.getElementById('editVal').value = '';
  document.getElementById('editVal').placeholder = `请输入新的${label}`;
  const pickerEl = document.getElementById('pickerEditVal');
  pickerEl.style.display = (showChPicker||CHANNEL_FIELDS.includes(field)) ? '' : 'none';
  openModal('modalEdit');
}

async function submitEdit() {
  const val=document.getElementById('editVal').value.trim();
  if(!val) return toast('不能为空','error');
  const {type,idx,field}=editCtx;
  const path=type==='stats'?`/stats/${idx}`:`/dirs/${idx}`;
  const res=await api(path,'PUT',{field,value:val});
  if(res.ok){
    if(field==='extract_blacklist') toast('🔍 正在后台读取榜单...');
    else toast('✅ 已修改');
    closeModal('modalEdit');
    if(res.user){userData=res.user;renderTasks();}
  } else toast(res.msg||'修改失败','error');
}

/* ====== 🆕 发送消息(支持媒体文件)====== */
async function sendBtnNew() {
  const chId = document.getElementById('bnCh').value.trim();
  const text = document.getElementById('bnText').value;
  const btnText = document.getElementById('bnBtnText').value.trim();
  const url = document.getElementById('bnUrl').value.trim();
  const fileInput = document.getElementById('bnMedia');

  if(!chId) return toast('请填写频道ID','error');
  if(!text && (!fileInput.files||!fileInput.files[0])) return toast('请输入内容或选择媒体文件','error');

  // 有媒体文件时用 FormData 上传
  if(fileInput.files && fileInput.files[0]) {
    const formData = new FormData();
    formData.append('ch_id', chId);
    formData.append('text', text);
    formData.append('btn_text', btnText);
    formData.append('url', url);
    formData.append('media', fileInput.files[0]);

    try {
      const resp = await fetch(API+'/btn_new_media', {
        method:'POST',
        headers:{'X-Init-Data':initData},
        body: formData
      });
      const res = await resp.json();
      if(res.ok){toast('✅ 消息已发送');closeModal('modalBtnNew');}
      else toast(res.msg||'发送失败','error');
    } catch(e) { toast('发送出错: '+e.message,'error'); }
  } else {
    // 纯文本模式
    const body = {ch_id:chId, text, btn_text:btnText, url};
    const res = await api('/btn_new','POST',body);
    if(res.ok){toast('✅ 消息已发送');closeModal('modalBtnNew');}
    else toast(res.msg||'发送失败','error');
  }
}

async function sendBtnOld() {
  const body={ch_id:document.getElementById('boCh').value.trim(),msg_id:document.getElementById('boMsg').value.trim(),
    btn_text:document.getElementById('boBtnText').value.trim(),url:document.getElementById('boUrl').value.trim()};
  if(!body.ch_id||!body.msg_id||!body.btn_text) return toast('请填写必填项','error');
  const res=await api('/btn_old','POST',body);
  if(res.ok){toast('✅ 操作成功');closeModal('modalBtnOld');}else toast(res.msg||'失败','error');
}

function addBtnRow() {
  const c=document.getElementById('bmBtnsContainer');
  const div=document.createElement('div');
  div.className='form-group';div.style.cssText='display:flex;gap:8px';
  div.innerHTML=`<input class="form-input" placeholder="按钮文字" style="flex:1"><input class="form-input" placeholder="https://链接" style="flex:1">`;
  c.appendChild(div);
}

async function sendBtnMulti() {
  const ch=document.getElementById('bmCh').value.trim(), text=document.getElementById('bmText').value;
  const rows=document.querySelectorAll('#bmBtnsContainer .form-group'), buttons=[];
  rows.forEach(r=>{const ins=r.querySelectorAll('input');if(ins[0].value.trim()&&ins[1].value.trim()) buttons.push({text:ins[0].value.trim(),url:ins[1].value.trim()});});
  if(!ch||!text||!buttons.length) return toast('请填写完整','error');
  const res=await api('/btn_multi','POST',{ch_id:ch,text,buttons});
  if(res.ok){toast('✅ 已发送');closeModal('modalBtnMulti');}else toast(res.msg||'失败','error');
}

async function genDir() {
  const ch=document.getElementById('gdCh').value.trim();
  if(!ch) return toast('请输入频道ID','error');
  const res=await api('/gen_dir','POST',{ch_id:ch});
  toast(res.ok?'✅ 扫描已启动,请在 Bot 对话中查看结果':(res.msg||'失败'),res.ok?'success':'error');
  if(res.ok) closeModal('modalGenDir');
}

async function replaceTag() {
  const body={ch_id:document.getElementById('rpCh').value.trim(),old_tag:document.getElementById('rpOld').value.trim(),
    new_tag:document.getElementById('rpNew').value.trim()};
  if(!body.ch_id||!body.old_tag) return toast('请填写必填项','error');
  if(!body.old_tag.startsWith('#')) return toast('旧标签需以#开头','error');
  const res=await api('/replace_tag','POST',body);
  toast(res.ok?'✅ 替换任务已启动':(res.msg||'失败'),res.ok?'success':'error');
  if(res.ok) closeModal('modalReplace');
}

function renderBackupGroups() {
  const c=document.getElementById('backupGroupBtns'), groups=userData?.groups||[];
  if(!groups.length){c.innerHTML='<p style="color:var(--hint);font-size:13px">暂无同步组可快速备份</p>';return;}
  c.innerHTML=groups.map((g,i)=>{
    const nm=g.name||`组${i+1}`;
    return `<button class="btn btn-ghost btn-sm" style="margin:4px" onclick="quickBackup(${i})">📦 ${nm}: ${chNameOnly(g.src)}</button>`;
  }).join('');
}

function quickBackup(idx) {
  const g=userData.groups[idx]; if(!g) return;
  document.getElementById('bkSrc').value = g.src||'';
  const container=document.getElementById('bkTgtContainer');
  let tgts=g.tgt; if(typeof tgts==='string') tgts=[tgts];
  container.innerHTML='';
  (tgts||[]).forEach(t=>{
    const div=document.createElement('div');
    div.className='form-group';
    div.innerHTML=`<input class="form-input bk-tgt" placeholder="-100xxxxxxxxxx" value="${t}"><div class="channel-picker"></div>`;
    container.appendChild(div);
  });
  renderChannelPickers();
  toast('✅ 已自动填充,请粘贴最新消息链接后点击备份');
}

function addBkTgtRow() {
  const c=document.getElementById('bkTgtContainer');
  const div=document.createElement('div');
  div.className='form-group';
  div.innerHTML=`<input class="form-input bk-tgt" placeholder="-100xxxxxxxxxx"><div class="channel-picker"></div>`;
  c.appendChild(div);
  renderChannelPickers();
}

async function startBackup() {
  const src=document.getElementById('bkSrc').value.trim();
  const link=document.getElementById('bkLink').value.trim();
  const wash=document.getElementById('bkWash').checked;
  const tgts=[];
  document.querySelectorAll('#bkTgtContainer .bk-tgt').forEach(i=>{const v=i.value.trim();if(v)tgts.push(v);});
  if(!src||!tgts.length||!link) return toast('请填写完整','error');
  const mode=wash?'🔄 洗MD5':'📦 普通';
  const res=await api('/backup','POST',{src,tgt:tgts,link,wash});
  toast(res.ok?`✅ 备份已启动 (${mode}, ${tgts.length}个目标)`:(res.msg||'失败'),res.ok?'success':'error');
  if(res.ok) closeModal('modalBackup');
}

/* ====== 🆕 备份频道成员 ====== */
async function backupMembers() {
  const chId = document.getElementById('bmChId').value.trim();
  if(!chId) return toast('请输入频道ID','error');
  const res = await api('/backup_members','POST',{ch_id:chId});
  if(res.ok){
    toast('✅ 导出任务已启动,请在 Bot 对话查看结果');
    closeModal('modalBackupMembers');
  } else toast(res.msg||'失败','error');
}

/* ====== 批量建频道 ====== */
async function startBatchCreate() {
  const names=document.getElementById('bcNames').value.trim();
  const users=document.getElementById('bcUsers').value.trim();
  const count=parseInt(document.getElementById('bcCount').value)||1;
  if(!names) return toast('请输入频道名称','error');
  const res=await api('/batch_create','POST',{names,users,count});
  if(res.ok){toast('✅ 批量创建已启动!');closeModal('modalBatchCreate');}
  else toast(res.msg||'提交失败','error');
}

/* ====== 洗MD5开关交互 ====== */
document.getElementById('bkWash').addEventListener('change', function() {
  const dot=document.getElementById('bkWashDot');
  if(this.checked){
    dot.style.left='25px';
    dot.parentElement.previousElementSibling.style.background='rgba(233,69,96,.5)';
  } else {
    dot.style.left='3px';
    dot.parentElement.previousElementSibling.style.background='rgba(255,255,255,.12)';
  }
  try{tg.HapticFeedback.impactOccurred('light')}catch(e){}
});

loadHome();
</script>
</body>
</html>