File size: 44,230 Bytes
7a85a0b
 
 
 
 
 
 
5136ade
7a85a0b
 
 
 
 
 
 
 
 
792dfe4
7a85a0b
792dfe4
 
7a85a0b
 
 
 
 
 
 
792dfe4
 
7a85a0b
 
792dfe4
 
7a85a0b
 
 
792dfe4
7a85a0b
 
 
 
792dfe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a85a0b
792dfe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a85a0b
792dfe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a85a0b
 
 
 
792dfe4
 
7a85a0b
 
 
 
 
792dfe4
 
7a85a0b
 
 
 
 
 
792dfe4
 
7a85a0b
 
792dfe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a85a0b
15b4b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792dfe4
 
 
 
 
 
 
 
 
 
 
 
15b4b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a85a0b
 
 
792dfe4
 
 
 
 
7a85a0b
792dfe4
 
 
 
 
7a85a0b
792dfe4
 
cc5568f
 
 
 
 
 
 
15b4b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792dfe4
15b4b9b
792dfe4
 
 
 
15b4b9b
 
792dfe4
15b4b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792dfe4
15b4b9b
 
 
 
42605a3
 
 
 
 
 
 
 
 
 
 
 
 
792dfe4
7a85a0b
792dfe4
 
 
 
7a85a0b
 
792dfe4
42605a3
 
 
 
 
 
792dfe4
 
c46caa2
792dfe4
 
 
c46caa2
 
 
792dfe4
f000e98
c46caa2
792dfe4
 
 
c46caa2
792dfe4
 
 
 
 
 
 
 
 
c46caa2
 
792dfe4
 
 
 
 
 
 
941bcc7
792dfe4
 
 
 
0b72b24
792dfe4
 
 
 
 
 
 
0b72b24
792dfe4
 
 
 
 
 
 
 
0b72b24
792dfe4
 
 
941bcc7
792dfe4
 
 
 
 
359910b
 
 
 
 
792dfe4
 
941bcc7
792dfe4
 
 
 
 
 
 
 
 
 
 
 
0b72b24
15b4b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792dfe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b72b24
792dfe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b72b24
792dfe4
 
 
 
 
 
 
0b72b24
 
 
c46caa2
 
15b4b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
792dfe4
 
 
15b4b9b
792dfe4
 
 
 
 
c46caa2
792dfe4
 
0b72b24
15b4b9b
 
 
 
c46caa2
0b72b24
 
15b4b9b
792dfe4
 
 
 
 
0b72b24
c46caa2
 
15b4b9b
792dfe4
15b4b9b
792dfe4
 
15b4b9b
 
 
 
 
792dfe4
0b72b24
15b4b9b
 
792dfe4
0b72b24
792dfe4
 
 
15b4b9b
 
0b72b24
792dfe4
 
 
 
0b72b24
 
792dfe4
 
 
 
15b4b9b
0b72b24
 
 
941bcc7
15b4b9b
 
7a85a0b
792dfe4
15b4b9b
 
 
 
 
792dfe4
15b4b9b
 
 
 
 
792dfe4
 
 
 
 
15b4b9b
c46caa2
15b4b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c46caa2
1373a35
 
 
 
 
bd26bbb
1373a35
 
51ef028
1373a35
 
 
 
 
af7bd09
fd76978
af7bd09
1373a35
 
 
 
af7bd09
1373a35
 
fd76978
 
99aac9d
 
 
 
 
 
 
fd76978
 
99aac9d
 
 
 
 
 
51ef028
fd76978
1373a35
 
fd76978
1373a35
 
 
e5a55b2
1373a35
 
 
 
 
 
 
fd76978
 
 
1373a35
 
 
 
 
fd76978
 
 
1373a35
 
 
 
 
 
99aac9d
 
 
1373a35
fd76978
 
1373a35
 
 
 
 
 
 
 
 
 
 
 
 
76b32b8
 
1373a35
 
 
 
 
 
 
 
 
e5a55b2
1373a35
 
 
c46caa2
 
1373a35
c46caa2
 
7a85a0b
5136ade
a0862a6
1373a35
fd76978
 
 
 
 
76b32b8
5136ade
1373a35
 
 
 
 
5136ade
fd76978
76b32b8
 
1373a35
 
359910b
5136ade
1373a35
 
5136ade
 
1373a35
754fcda
5136ade
e5a55b2
76b32b8
fd76978
 
 
1373a35
e5a55b2
1373a35
 
76b32b8
bd26bbb
ed44796
1373a35
 
 
 
ed44796
 
1373a35
ed44796
51ef028
ed44796
754fcda
76b32b8
 
 
1373a35
 
 
 
 
 
 
 
 
 
 
e5a55b2
1373a35
 
 
5136ade
 
 
1373a35
 
 
5136ade
 
c46caa2
 
1373a35
fd76978
1373a35
c46caa2
1373a35
e1435d8
fd76978
 
 
 
 
e1435d8
fd76978
 
e1435d8
1373a35
c46caa2
941bcc7
7a85a0b
 
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
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bio-Vibe Web</title>
    <link rel="icon" href="data:,">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
    <style>

        body {

            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

            background-color: #1a1a2e;

            color: #e94560;

            display: flex;

            flex-direction: column;

            align-items: center;

            justify-content: center;

            min-height: 100vh;

            margin: 0;

            padding: 20px;

            box-sizing: border-box;

        }

        .container {

            background-color: #16213e;

            padding: 40px;

            border-radius: 15px;

            text-align: center;

            box-shadow: 0 10px 30px rgba(0,0,0,0.5);

            max-width: 620px;

            width: 100%;

        }

        h1 { color: #fff; margin-bottom: 5px; }

        .subtitle { color: #a2a2bd; margin-bottom: 20px; }



        #bpm-display {

            font-size: 80px;

            font-weight: bold;

            margin: 15px 0;

            text-shadow: 0 0 15px #e94560;

            transition: color 0.3s ease;

        }



        @keyframes pulse {

            0% { transform: scale(1); opacity: 1; }

            50% { transform: scale(1.05); opacity: 0.8; }

            100% { transform: scale(1); opacity: 1; }

        }



        /* ---- TABS ---- */

        .tab-group {

            display: flex;

            justify-content: center;

            gap: 0;

            margin-bottom: 20px;

            border-radius: 8px;

            overflow: hidden;

            border: 1px solid #0f3460;

        }

        .tab-btn {

            flex: 1;

            background: #0f3460;

            color: #a2a2bd;

            border: none;

            padding: 10px 16px;

            font-size: 14px;

            cursor: pointer;

            transition: 0.2s;

            font-weight: bold;

        }

        .tab-btn.active { background: #4ecca3; color: #1a1a2e; }

        .tab-btn:hover:not(.active) { background: #1a3a6e; color: #fff; }



        .tab-panel { display: none; }

        .tab-panel.active { display: block; }



        /* ---- MANUAL INPUT ---- */

        .manual-group {

            display: flex;

            align-items: center;

            justify-content: center;

            gap: 12px;

            margin: 10px 0 16px;

        }

        #manual-bpm-input {

            background: #0f3460;

            border: 1px solid #4ecca3;

            border-radius: 8px;

            color: #fff;

            font-size: 28px;

            font-weight: bold;

            width: 110px;

            text-align: center;

            padding: 8px;

        }

        #manual-bpm-input:focus { outline: 2px solid #4ecca3; }

        #btn-manual-set {

            background: #4ecca3;

            color: #1a1a2e;

            border: none;

            padding: 10px 18px;

            font-size: 15px;

            border-radius: 8px;

            cursor: pointer;

            font-weight: bold;

            transition: 0.2s;

        }

        #btn-manual-set:hover { background: #38b499; }



        /* ---- BUTTONS ---- */

        .button-group {

            display: flex;

            justify-content: center;

            flex-wrap: wrap;

            gap: 12px;

            margin-top: 10px;

        }

        button {

            background-color: #0f3460;

            color: white;

            border: none;

            padding: 13px 22px;

            font-size: 15px;

            border-radius: 8px;

            cursor: pointer;

            transition: 0.3s;

            font-weight: bold;

        }

        button:hover { background-color: #4ecca3; color: #1a1a2e; }

        button:disabled { background-color: #2a2a3e; cursor: not-allowed; color: #555; }



        #btn-stop { background-color: #8b0000; }

        #btn-stop:hover { background-color: #ff4d4d; color: white; }

        #btn-stop:disabled { background-color: #2a2a3e; }



        /* ---- STATUS ---- */

        #status {

            margin-top: 18px;

            font-size: 13px;

            font-style: italic;

            min-height: 20px;

        }

        .status-ok { color: #4ecca3; }

        .status-err { color: #ff4d4d; }

        .status-info { color: #a2a2bd; }



        /* ---- DEBUG LOG ---- */

        .debug-section {

            margin-top: 20px;

            text-align: left;

        }

        .debug-toggle {

            background: none;

            border: none;

            color: #555;

            font-size: 12px;

            cursor: pointer;

            padding: 4px 0;

            font-style: italic;

        }

        .debug-toggle:hover { color: #a2a2bd; background: none; }

        #debug-log {

            display: none;

            background: #0a0a1a;

            border-radius: 6px;

            padding: 10px;

            font-size: 11px;

            color: #4ecca3;

            font-family: monospace;

            max-height: 160px;

            overflow-y: auto;

            margin-top: 6px;

            text-align: left;

        }



        /* ---- QUICK BPM ZONES ---- */

        .zone-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:8px; margin:12px 0; }

        .zone-btn { background:#0f3460; border:1px solid #1a3a6e; border-radius:10px; color:#fff;

            padding:10px 4px; font-size:13px; cursor:pointer; transition:0.2s;

            display:flex; flex-direction:column; align-items:center; gap:3px; }

        .zone-btn:hover { background:#1a4070; border-color:#4ecca3; }

        .zone-btn.active-zone { border-color:#4ecca3; background:#0a2844; }

        .zone-btn .zone-emoji { font-size:20px; }

        .zone-btn .zone-label { font-size:10px; color:#a2a2bd; }

        .zone-btn .zone-bpm { font-size:12px; color:#4ecca3; font-weight:bold; }

        .auto-row { display:flex; align-items:center; justify-content:center; gap:10px;

            margin-top:8px; font-size:13px; color:#a2a2bd; }

        .toggle-wrap { position:relative; width:36px; height:20px; }

        .toggle-wrap input { opacity:0; width:100%; height:100%; position:absolute; cursor:pointer; margin:0; z-index:2; }

        .toggle-track { position:absolute; inset:0; background:#1a3a6e; border-radius:10px; transition:background 0.2s; }

        .toggle-wrap input:checked ~ .toggle-track { background:#4ecca3; }

        .toggle-thumb { position:absolute; top:3px; left:3px; width:14px; height:14px;

            background:#fff; border-radius:50%; transition:transform 0.2s; pointer-events:none; }

        .toggle-wrap input:checked ~ .toggle-thumb { transform:translateX(16px); }

        #refresh-interval-wrap { display:none; align-items:center; gap:6px; }

        #refresh-interval-wrap.visible { display:flex; }

        #refresh-sec { width:52px; background:#0f3460; border:1px solid #4ecca3;

            border-radius:6px; color:#fff; font-size:14px; text-align:center; padding:3px; }



        /* ---- NOTICE ---- */

        .notice {

            background: #0f2040;

            border-left: 3px solid #e94560;

            border-radius: 0 6px 6px 0;

            padding: 10px 14px;

            margin-bottom: 14px;

            font-size: 13px;

            color: #a2a2bd;

            text-align: left;

        }

        .notice strong { color: #e94560; }



        /* ---- BLE DEVICE CARD ---- */

        #ble-idle { }

        #ble-card { display:none; }



        .scan-hint {

            font-size: 12px; color: #4a5a7a; margin-top: 8px; font-style: italic;

        }



        /* Scanning animation */

        .scan-ring-wrap {

            display: flex; align-items: center; justify-content: center;

            gap: 14px; margin: 12px 0 8px;

        }

        .scan-ring {

            width: 44px; height: 44px; border-radius: 50%;

            border: 3px solid transparent;

            border-top-color: #4ecca3;

            border-right-color: #4ecca366;

            animation: spin 1s linear infinite;

        }

        @keyframes spin { to { transform: rotate(360deg); } }

        .scan-label { color: #4ecca3; font-size: 14px; font-weight: bold; }



        /* Connected device card */

        .device-card {

            background: linear-gradient(135deg, #0a2040 0%, #0f3060 100%);

            border: 1px solid #4ecca355;

            border-radius: 14px;

            padding: 16px 18px;

            margin: 10px 0;

            display: flex;

            align-items: center;

            gap: 14px;

            text-align: left;

            position: relative;

            overflow: hidden;

        }

        .device-card::before {

            content: '';

            position: absolute;

            inset: 0;

            background: radial-gradient(ellipse at 20% 50%, #4ecca318 0%, transparent 60%);

            pointer-events: none;

        }

        .device-icon-wrap {

            width: 52px; height: 52px; border-radius: 50%;

            background: linear-gradient(135deg, #0f3460, #1a4a80);

            border: 2px solid #4ecca355;

            display: flex; align-items: center; justify-content: center;

            font-size: 26px; flex-shrink: 0;

        }

        .device-info { flex: 1; min-width: 0; }

        .device-name {

            color: #fff; font-size: 15px; font-weight: bold;

            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;

        }

        .device-sub {

            color: #a2a2bd; font-size: 12px; margin-top: 2px;

        }

        .device-badges {

            display: flex; gap: 6px; margin-top: 6px; flex-wrap: wrap;

        }

        .badge {

            background: #0f3460; border: 1px solid #1a4a80;

            border-radius: 20px; padding: 2px 9px;

            font-size: 11px; color: #a2a2bd;

        }

        .badge.connected {

            background: #0a3020; border-color: #4ecca355; color: #4ecca3;

        }

        .badge.subscribing {

            background: #2a1a00; border-color: #e9a02055; color: #e9a020;

        }

        .badge.no-hr {

            background: #300a0a; border-color: #e9456055; color: #e94560;

        }



        /* Signal bars */

        .signal-wrap {

            display: flex; align-items: flex-end; gap: 2px; height: 18px;

        }

        .sig-bar {

            width: 4px; border-radius: 2px; background: #4ecca3;

            opacity: 0.25; transition: opacity 0.4s;

        }

        .sig-bar.active { opacity: 1; }

        .sig-bar:nth-child(1) { height: 5px; }

        .sig-bar:nth-child(2) { height: 9px; }

        .sig-bar:nth-child(3) { height: 13px; }

        .sig-bar:nth-child(4) { height: 18px; }



        /* Disconnect button */

        #btn-disconnect {

            background: transparent;

            border: 1px solid #e9456066;

            color: #e94560;

            padding: 6px 13px;

            font-size: 12px;

            border-radius: 8px;

            cursor: pointer;

            font-weight: bold;

            transition: 0.2s;

            flex-shrink: 0;

        }

        #btn-disconnect:hover {

            background: #e9456020; border-color: #e94560;

        }



        /* Reconnect button (shown when disconnected) */

        #btn-reconnect {

            display: none;

            background: #4ecca322;

            border: 1px solid #4ecca355;

            color: #4ecca3;

            padding: 6px 13px;

            font-size: 12px;

            border-radius: 8px;

            cursor: pointer;

            font-weight: bold;

            transition: 0.2s;

            flex-shrink: 0;

        }

        #btn-reconnect:hover { background: #4ecca344; }



        /* Pulse dot (connection alive indicator) */

        .pulse-dot {

            width: 8px; height: 8px; border-radius: 50%;

            background: #4ecca3;

            box-shadow: 0 0 0 0 #4ecca3aa;

            animation: pulseDot 1.8s ease infinite;

            flex-shrink: 0;

        }

        @keyframes pulseDot {

            0%   { box-shadow: 0 0 0 0 #4ecca3aa; }

            70%  { box-shadow: 0 0 0 7px #4ecca300; }

            100% { box-shadow: 0 0 0 0 #4ecca300; }

        }

        .pulse-dot.dead {

            background: #e94560; box-shadow: none; animation: none;

        }

    </style>
</head>
<body>
<div class="container">
    <h1>Bio-Vibe 🎧</h1>
    <p class="subtitle">Âm nhạc trị liệu AI theo Nhịp tim</p>

    <div id="bpm-display">-- BPM</div>

    <!-- TABS -->
    <div class="tab-group">
        <button class="tab-btn active" onclick="switchTab('ble')">📡 Kết nối BLE</button>
        <button class="tab-btn" onclick="switchTab('manual')">✏️ Nhập thủ công</button>
    </div>

    <!-- TAB: BLE -->
    <div id="tab-ble" class="tab-panel active">
        <!-- STATE: idle / scanning -->
        <div id="ble-idle">
            <div class="button-group">
                <button id="btn-connect">📡 Quét thiết bị BLE</button>
            </div>
            <p class="scan-hint">Trình duyệt sẽ mở hộp thoại chọn thiết bị Bluetooth</p>
        </div>
        <!-- STATE: scanning spinner (shown briefly) -->
        <div id="ble-scanning" style="display:none; padding:8px 0 4px;">
            <div class="scan-ring-wrap">
                <div class="scan-ring"></div>
                <span class="scan-label">Đang kết nối…</span>
            </div>
        </div>

        <!-- STATE: connected device card -->
        <div id="ble-card" style="display:none;">
            <div class="device-card">
                <div class="device-icon-wrap" id="dev-icon"></div>
                <div class="device-info">
                    <div class="device-name" id="dev-name">Unknown Device</div>
                    <div class="device-sub" id="dev-sub">Đang kiểm tra characteristics…</div>
                    <div class="device-badges">
                        <span class="badge connected" id="badge-conn">● Đã kết nối</span>
                        <span class="badge" id="badge-hr" style="display:none"></span>
                        <span class="badge" id="badge-svc"></span>
                    </div>
                </div>
                <div style="display:flex; flex-direction:column; align-items:center; gap:8px;">
                    <div class="signal-wrap" id="signal-bars">
                        <div class="sig-bar active"></div>
                        <div class="sig-bar active"></div>
                        <div class="sig-bar active"></div>
                        <div class="sig-bar"></div>
                    </div>
                    <div class="pulse-dot" id="pulse-dot"></div>
                </div>
                <div style="display:flex; flex-direction:column; gap:6px; align-items:flex-end;">
                    <button id="btn-disconnect">Ngắt kết nối</button>
                    <button id="btn-reconnect">🔄 Kết nối lại</button>
                </div>
            </div>
        </div>

    </div>

    <!-- TAB: MANUAL -->
    <div id="tab-manual" class="tab-panel">
        <p style="color:#a2a2bd; font-size:13px; margin-bottom:6px;">
            Nhìn BPM trên Samsung Health → chọn vùng hoặc nhập chính xác bên dưới.
        </p>

        <!-- Quick zone buttons -->
        <div class="zone-grid">
            <button class="zone-btn" onclick="setZone(55,'Nghỉ ngơi')">
                <span class="zone-emoji">😴</span>
                <span class="zone-label">Nghỉ ngơi</span>
                <span class="zone-bpm">~55 BPM</span>
            </button>
            <button class="zone-btn" onclick="setZone(70,'Nhẹ nhàng')">
                <span class="zone-emoji">🚶</span>
                <span class="zone-label">Nhẹ nhàng</span>
                <span class="zone-bpm">~70 BPM</span>
            </button>
            <button class="zone-btn" onclick="setZone(95,'Vận động')">
                <span class="zone-emoji">🏃</span>
                <span class="zone-label">Vận động</span>
                <span class="zone-bpm">~95 BPM</span>
            </button>
            <button class="zone-btn" onclick="setZone(130,'Cường độ cao')">
                <span class="zone-emoji">🔥</span>
                <span class="zone-label">Cường độ cao</span>
                <span class="zone-bpm">~130 BPM</span>
            </button>
        </div>

        <!-- Precise input -->
        <div class="manual-group">
            <input type="number" id="manual-bpm-input" min="30" max="220" value="75"

                onkeydown="if(event.key==='Enter') setManualBpm()" />
            <button id="btn-manual-set" onclick="setManualBpm()">Áp dụng</button>
        </div>

        <!-- Auto refresh reminder -->
        <div class="auto-row">
            <label class="toggle-wrap">
                <input type="checkbox" id="auto-refresh-toggle" onchange="toggleAutoRefresh(this.checked)">
                <span class="toggle-track"></span>
                <span class="toggle-thumb"></span>
            </label>
            <span>Nhắc cập nhật BPM mỗi</span>
            <span id="refresh-interval-wrap">
                <input type="number" id="refresh-sec" min="10" max="300" value="30"> giây
            </span>
        </div>
    </div>

    <!-- PLAYBACK CONTROLS -->
    <div class="button-group" style="margin-top:18px;">
        <button id="btn-generate">2. Sinh nhạc AI</button>
        <button id="btn-stop" disabled>3. Dừng nhạc</button>
    </div>

    <div id="status" class="status-info">Chưa có BPM...</div>

    <!-- DEBUG -->
    <div class="debug-section">
        <button class="debug-toggle" onclick="toggleDebug()">▶ Xem log BLE debug</button>
        <div id="debug-log"></div>
    </div>
</div>

<script>

    // ===============================

    // STATE

    // ===============================

    let currentBpm = 0;

    let bpmHistory = [];

    let currentAudio = null;

    let debugVisible = false;

    let ws = null; // Biến giữ kết nối WebSocket



    const bpmDisplay  = document.getElementById('bpm-display');

    const statusEl    = document.getElementById('status');

    const btnConnect  = document.getElementById('btn-connect');

    const btnGenerate = document.getElementById('btn-generate');

    const btnStop     = document.getElementById('btn-stop');

    const debugLog    = document.getElementById('debug-log');



    // ===============================

    // UI HELPERS

    // ===============================

    function setStatus(msg, type = 'info') {

        statusEl.textContent = msg;

        statusEl.className   = 'status-' + type;

    }



    function log(msg) {

        const line = document.createElement('div');

        line.textContent = '[' + new Date().toLocaleTimeString() + '] ' + msg;

        debugLog.appendChild(line);

        debugLog.scrollTop = debugLog.scrollHeight;

        console.log(msg);

    }



    function toggleDebug() {

        debugVisible = !debugVisible;

        debugLog.style.display = debugVisible ? 'block' : 'none';

    }



    function switchTab(name) {

        document.querySelectorAll('.tab-btn').forEach((b, i) => {

            b.classList.toggle('active', (i === 0 && name === 'ble') || (i === 1 && name === 'manual'));

        });

        document.getElementById('tab-ble').classList.toggle('active', name === 'ble');

        document.getElementById('tab-manual').classList.toggle('active', name === 'manual');

    }



    // ===============================

    // BPM SMOOTHING

    // ===============================

    function smoothBpm(val) {

        bpmHistory.push(val);

        if (bpmHistory.length > 5) bpmHistory.shift();

        return Math.round(bpmHistory.reduce((a, b) => a + b, 0) / bpmHistory.length);

    }



    function applyBpm(raw, source) {

        if (raw < 30 || raw > 220) return false;

        if (currentBpm !== 0 && Math.abs(raw - currentBpm) > 40) return false;



        const smoothed    = smoothBpm(raw);

        currentBpm        = smoothed;

        bpmDisplay.textContent = currentBpm + ' BPM';

        bpmDisplay.style.color = '#e94560';

        setStatus('BPM nhận từ: ' + source, 'ok');



        if (ws && ws.readyState === WebSocket.OPEN) {

            ws.send(JSON.stringify({ bpm: currentBpm }));

        }



        return true;

    }



    // ===============================

    // MANUAL BPM

    // ===============================

    function setManualBpm() {

        const val = parseInt(document.getElementById('manual-bpm-input').value, 10);

        if (isNaN(val) || val < 30 || val > 220) {

            setStatus('Giá trị BPM không hợp lệ (30–220)', 'err');

            return;

        }

        bpmHistory = [];

        applyBpm(val, 'Nhập thủ công');

    }



    function setZone(bpm, label) {

        document.getElementById('manual-bpm-input').value = bpm;

        bpmHistory = [];

        applyBpm(bpm, label);

        // Highlight active zone

        document.querySelectorAll('.zone-btn').forEach(b => b.classList.remove('active-zone'));

        event.currentTarget.classList.add('active-zone');

    }



    let autoRefreshTimer = null;

    function toggleAutoRefresh(on) {

        const wrap = document.getElementById('refresh-interval-wrap');

        wrap.classList.toggle('visible', on);

        if (autoRefreshTimer) { clearInterval(autoRefreshTimer); autoRefreshTimer = null; }

        if (on) {

            const sec = parseInt(document.getElementById('refresh-sec').value, 10) || 30;

            autoRefreshTimer = setInterval(() => {

                setStatus(`⏰ Hãy kiểm tra BPM trên Samsung Health và cập nhật!`, 'info');

                // Flash BPM display

                bpmDisplay.style.opacity = '0.4';

                setTimeout(() => bpmDisplay.style.opacity = '1', 600);

            }, sec * 1000);

            setStatus(`Sẽ nhắc cập nhật BPM mỗi ${sec} giây`, 'ok');

        }

    }



    // ===============================

    // PARSE CHUẨN BLE Heart Rate (0x2A37)

    // ===============================

    function parseHeartRateMeasurement(dataView) {

        /*

         * Byte 0: Flags

         *   bit 0 = 0 → Heart Rate Value là UINT8 (byte 1)

         *   bit 0 = 1 → Heart Rate Value là UINT16 (bytes 1-2, little-endian)

         */

        const flags   = dataView.getUint8(0);

        const is16bit = (flags & 0x01) !== 0;

        return is16bit

            ? dataView.getUint16(1, true)

            : dataView.getUint8(1);

    }



    // ===============================

    // HANDLE INCOMING CHARACTERISTIC DATA

    // ===============================

    function handleCharData(event, uuid, serviceUuid) {

        const dv  = event.target.value;

        const raw = [];

        for (let i = 0; i < dv.byteLength; i++) raw.push(dv.getUint8(i));

        log(`UUID ${uuid.substring(0,8)}… DATA: [${raw.join(', ')}]`);



        const HR_MEASUREMENT_UUID = '00002a37-0000-1000-8000-00805f9b34fb';



        // 1. Nếu đúng UUID chuẩn Heart Rate Measurement → parse theo spec

        if (uuid === HR_MEASUREMENT_UUID) {

            if (dv.byteLength >= 2) {

                const bpm = parseHeartRateMeasurement(dv);

                log(`Standard HR parse → ${bpm} BPM`);

                applyBpm(bpm, 'HR chuẩn BLE');

            }

            return;

        }



        // 2. Fallback heuristic cho proprietary chars

        //    Duyệt từng byte, lấy byte đầu tiên nằm trong [40, 180]

        for (let i = 0; i < raw.length; i++) {

            const v = raw[i];

            if (v >= 40 && v <= 180) {

                log(`Heuristic byte[${i}] = ${v} BPM`);

                applyBpm(v, `Heuristic (${uuid.substring(0,8)}…)`);

                break;

            }

        }

    }



    // ===============================

    // BLE STATE

    // ===============================

    let bleDevice   = null;

    let bleServer   = null;

    let bleSubCount = 0;



    const bleIdle      = document.getElementById('ble-idle');

    const bleScanning  = document.getElementById('ble-scanning');

    const bleCard      = document.getElementById('ble-card');

    const devIcon      = document.getElementById('dev-icon');

    const devName      = document.getElementById('dev-name');

    const devSub       = document.getElementById('dev-sub');

    const badgeConn    = document.getElementById('badge-conn');

    const badgeHr      = document.getElementById('badge-hr');

    const badgeSvc     = document.getElementById('badge-svc');

    const pulseDot     = document.getElementById('pulse-dot');

    const btnDisconnect = document.getElementById('btn-disconnect');

    const btnReconnect  = document.getElementById('btn-reconnect');



    function guessDeviceIcon(name) {

        if (!name) return '📡';

        const n = name.toLowerCase();

        if (n.includes('polar') || n.includes('hrm') || n.includes('chest')) return '💓';

        if (n.includes('garmin')) return '🏃';

        if (n.includes('galaxy') || n.includes('watch') || n.includes('samsung')) return '⌚';

        if (n.includes('mi band') || n.includes('xiaomi') || n.includes('amazfit')) return '📿';

        if (n.includes('fitbit')) return '💪';

        return '⌚';

    }



    function showBleCard(name, subText) {

        bleIdle.style.display     = 'none';

        bleScanning.style.display = 'none';

        bleCard.style.display     = 'block';

        devIcon.textContent       = guessDeviceIcon(name);

        devName.textContent       = name || 'Unknown Device';

        devSub.textContent        = subText || '';

    }



    function setBleConnected() {

        badgeConn.textContent  = '● Đã kết nối';

        badgeConn.className    = 'badge connected';

        pulseDot.classList.remove('dead');

        btnDisconnect.style.display = 'inline-block';

        btnReconnect.style.display  = 'none';

    }



    function setBleDisconnected() {

        badgeConn.textContent  = '○ Mất kết nối';

        badgeConn.className    = 'badge no-hr';

        pulseDot.classList.add('dead');

        btnDisconnect.style.display = 'none';

        btnReconnect.style.display  = 'inline-block';

        // Animate signal bars off

        document.querySelectorAll('.sig-bar').forEach(b => b.classList.remove('active'));

    }



    function resetBleUI() {

        bleCard.style.display     = 'none';

        bleScanning.style.display = 'none';

        bleIdle.style.display     = 'block';

        badgeHr.style.display     = 'none';

        bleDevice = null; bleServer = null; bleSubCount = 0;

    }



    // ===============================

    // BLE CONNECT — auto scan tất cả services

    // ===============================

    async function doBleConnect() {

        if (!navigator.bluetooth) {

            setStatus('Trình duyệt không hỗ trợ Web Bluetooth!', 'err');

            return;

        }



        try {

            setStatus('Đang mở hộp thoại BLE…', 'info');

            log('Bắt đầu scan BLE...');



            // Show scanning state while picker is open

            bleIdle.style.display     = 'none';

            bleScanning.style.display = 'block';



            const device = await navigator.bluetooth.requestDevice({

                acceptAllDevices: true,

                optionalServices: [

                    'heart_rate', 'battery_service', 'device_information', 'generic_access',

                    '0000fee0-0000-1000-8000-00805f9b34fb',

                    '0000fee1-0000-1000-8000-00805f9b34fb',

                    '0000181d-0000-1000-8000-00805f9b34fb',

                    '0000fd00-0000-1000-8000-00805f9b34fb',

                    '0000180d-0000-1000-8000-00805f9b34fb',

                ]

            });



            bleDevice = device;

            log(`Device: ${device.name || '(no name)'} id=${device.id}`);

            showBleCard(device.name, 'Đang kết nối GATT…');

            setStatus('Đang kết nối GATT…', 'info');



            // Listen for unexpected disconnects

            device.addEventListener('gattserverdisconnected', onGattDisconnected);



            bleServer = await device.gatt.connect();

            const services = await bleServer.getPrimaryServices();

            log(`Tìm thấy ${services.length} service(s)`);



            badgeSvc.textContent = `${services.length} services`;



            let subscribed = 0;



            for (const svc of services) {

                log(`Service: ${svc.uuid}`);

                let chars;

                try { chars = await svc.getCharacteristics(); }

                catch (e) { log(`  Không đọc được chars: ${e.message}`); continue; }



                for (const char of chars) {

                    const props = char.properties;

                    log(`  Char: ${char.uuid} [notify=${props.notify} indicate=${props.indicate} read=${props.read}]`);

                    if (props.notify || props.indicate) {

                        try {

                            await char.startNotifications();

                            char.addEventListener('characteristicvaluechanged',

                                (ev) => handleCharData(ev, char.uuid, svc.uuid));

                            log(`  ✅ Subscribed: ${char.uuid}`);

                            subscribed++;

                        } catch (e) { log(`  ❌ Subscribe failed: ${e.message}`); }

                    }

                }

            }



            bleSubCount = subscribed;

            setBleConnected();



            if (subscribed === 0) {

                badgeHr.textContent   = '✗ Không có HR';

                badgeHr.className     = 'badge no-hr';

                badgeHr.style.display = 'inline-block';

                devSub.textContent    = 'Không đọc được HR — thử tab Nhập thủ công';

                setStatus('Kết nối OK nhưng thiết bị không stream HR. Thử tab Nhập thủ công.', 'err');

            } else {

                badgeHr.textContent   = `♥ ${subscribed} HR char`;

                badgeHr.className     = 'badge subscribing';

                badgeHr.style.display = 'inline-block';

                devSub.textContent    = `Đã subscribe ${subscribed} characteristic — đang chờ BPM…`;

                setStatus(`Đã subscribe ${subscribed} characteristic, đang chờ BPM…`, 'ok');

            }



        } catch (err) {

            log(`Lỗi: ${err.message}`);

            setStatus('Lỗi BLE: ' + err.message, 'err');

            resetBleUI();

        }

    }



    // ===============================

    // GATT DISCONNECTED EVENT

    // ===============================

    function onGattDisconnected() {

        log('⚠ GATT server disconnected (đồng hồ tự ngắt hoặc ra khỏi tầm)');

        setStatus('⚠ Mất kết nối BLE — nhấn "Kết nối lại" để thử lại.', 'err');

        setBleDisconnected();

        devSub.textContent = 'Mất kết nối — ra khỏi tầm Bluetooth?';

    }



    // ===============================

    // DISCONNECT

    // ===============================

    function doDisconnect() {

        if (bleDevice && bleDevice.gatt.connected) {

            bleDevice.gatt.disconnect();

            log('Đã ngắt kết nối BLE theo yêu cầu');

        }

        setBleDisconnected();

        devSub.textContent = 'Đã ngắt kết nối';

        setStatus('Đã ngắt kết nối BLE.', 'info');

    }



    // ===============================

    // RECONNECT

    // ===============================

    async function doReconnect() {

        if (!bleDevice) { resetBleUI(); return; }

        try {

            devSub.textContent = 'Đang kết nối lại…';

            btnReconnect.disabled = true;

            setStatus('Đang kết nối lại GATT…', 'info');



            bleServer = await bleDevice.gatt.connect();

            const services = await bleServer.getPrimaryServices();

            let subscribed = 0;



            for (const svc of services) {

                let chars;

                try { chars = await svc.getCharacteristics(); } catch { continue; }

                for (const char of chars) {

                    const props = char.properties;

                    if (props.notify || props.indicate) {

                        try {

                            await char.startNotifications();

                            char.addEventListener('characteristicvaluechanged',

                                (ev) => handleCharData(ev, char.uuid, svc.uuid));

                            subscribed++;

                        } catch {}

                    }

                }

            }



            bleSubCount = subscribed;

            setBleConnected();

            devSub.textContent = `Kết nối lại thành công — ${subscribed} char`;

            setStatus('Kết nối lại BLE thành công!', 'ok');

        } catch (err) {

            log(`Reconnect failed: ${err.message}`);

            setStatus('Kết nối lại thất bại: ' + err.message, 'err');

            devSub.textContent = 'Kết nối lại thất bại';

        } finally {

            btnReconnect.disabled = false;

        }

    }



    btnConnect.addEventListener('click', doBleConnect);

    btnDisconnect.addEventListener('click', doDisconnect);

    btnReconnect.addEventListener('click', doReconnect);



    // ================================================================

    // AUDIO CHAIN — volume boosted, gain staging cẩn thận

    // ================================================================

    const masterGain = new Tone.Gain(1.5).toDestination();         // +3.5dB tổng thể

    const limiter    = new Tone.Limiter(-0.3).connect(masterGain); // limiter thoáng hơn

    const compressor = new Tone.Compressor({

        threshold: -14, ratio: 3, attack: 0.008, release: 0.18

    }).connect(limiter);

    const eq = new Tone.EQ3({ low: 1, mid: 0, high: 2 }).connect(compressor);  // low cut: bỏ rumble

    const stereo = new Tone.StereoWidener(0.65).connect(eq);

    const reverb = new Tone.Reverb({ decay: 3.5, wet: 0.38 }).connect(stereo); // wet sẽ thay đổi theo BPM

    const delay  = new Tone.FeedbackDelay({ delayTime: "8n", feedback: 0.28, wet: 0.18 }).connect(reverb);



    // 🎹 PIANO — volume tăng lên, kết nối thẳng vào delay

    const piano = new Tone.Sampler({

        volume: 4,   // +4dB so với trước (trước là 0)

        urls: {

            A1:"A1.mp3", C2:"C2.mp3", "D#2":"Ds2.mp3", "F#2":"Fs2.mp3",

            A2:"A2.mp3", C3:"C3.mp3", "D#3":"Ds3.mp3", "F#3":"Fs3.mp3",

            A3:"A3.mp3", C4:"C4.mp3", "D#4":"Ds4.mp3", "F#4":"Fs4.mp3",

            A4:"A4.mp3", C5:"C5.mp3"

        },

        baseUrl: "https://raw.githubusercontent.com/Tonejs/audio/master/salamander/",

        release: 1

    }).connect(delay);



    // 🌊 STRING PAD — fatsawtooth + lowpass filter: ấm, organic, blend với piano

    // "sine" tạo tiếng sóng não vì không có harmonics.

    // "fatsawtooth" (3 voice detuned) qua filter ~700Hz = string pad lofi chuẩn.

    const padFilter = new Tone.Filter({

        frequency: 700,

        type: "lowpass",

        rolloff: -24        // cắt mạnh để không overlap với piano

    }).connect(reverb);



    const pad = new Tone.PolySynth(Tone.Synth, {

        volume: -9,

        oscillator: { type: "fatsawtooth", count: 3, spread: 25 },

        envelope: { attack: 1.4, decay: 0.4, sustain: 0.75, release: 3.5 }

    }).connect(padFilter);



    // Bass synth đã bỏ — chord pad đủ low-end, không cần thêm sub



    log("🎹 Đã khởi tạo audio chain. Volume boosted.");

    setStatus("Sẵn sàng sinh nhạc AI", "ok");



    // ================================================================

    // BPM-REACTIVE: thay đổi texture theo nhịp tim

    // ================================================================

    function applyBpmTexture(bpm) {

        // ── ENTRAINMENT LOGIC ──────────────────────────────────────────

        // Nhịp tim cao = cơ thể đang stress → nhạc kéo ngược lại: chậm,

        // mơ màng, ambient hơn để hạ nhiệt.

        // Nhịp tim thấp = nghỉ ngơi → nhạc có thể nhẹ nhàng groove hơn.



        // Reverb: BPM CAO = nhiều reverb hơn (mơ màng, bay bổng, dịu)

        //         BPM thấp = ít reverb (rõ ràng, có chiều sâu nhẹ)

        const reverbWet = bpm < 70  ? 0.28 :

                          bpm < 90  ? 0.35 :

                          bpm < 110 ? 0.46 : 0.58;

        reverb.wet.rampTo(reverbWet, 2.5);



        // Delay feedback: BPM cao = echo dài hơn (hypnotic, calming)

        const delayFb = bpm < 80 ? 0.16 : bpm < 110 ? 0.24 : 0.34;

        delay.feedback.rampTo(delayFb, 2.5);



        // Pad volume: BPM cao = pad nổi hơn (ambient nhấn chìm, che melody)

        //             BPM thấp = pad lùi, melody groove rõ hơn

        const padVol = bpm < 75 ? -12 : bpm < 100 ? -8 : -4;

        pad.volume.rampTo(padVol, 2.5);



        // Pad attack: BPM cao = attack chậm (drifting), thấp = attack vừa

        const padAttack = bpm < 75 ? 0.6 : bpm < 100 ? 1.2 : 2.2;

        pad.set({ envelope: { attack: padAttack } });

        // Lowpass cutoff: BPM cao (calming) → filter tối hơn (500Hz), thấp → sáng hơn (800Hz)

        const filterFreq = bpm < 75 ? 800 : bpm < 100 ? 650 : 500;

        padFilter.frequency.rampTo(filterFreq, 2.5);



        // Nhạc tempo: BPM cao → tempo chậm hơn để kéo nhịp tim xuống

        // map BPM [40,180] → music tempo [85, 55] BPM (inverse linear)

        const musicTempo = Math.round(85 - (bpm - 40) * (30 / 140));

        Tone.getTransport().bpm.rampTo(Math.max(52, Math.min(88, musicTempo)), 3);



        // BPM display color theo mức độ stress

        // (màu vẫn phản ánh nhịp tim thực, không phải tempo nhạc)

        const color = bpm < 70  ? '#4ecca3' :   // xanh — bình tĩnh

                      bpm < 90  ? '#a0d8ef' :   // xanh dương — nhẹ nhàng

                      bpm < 110 ? '#f9c74f' :   // vàng — đang tăng

                                  '#e94560';    // đỏ — cần hạ nhiệt

        bpmDisplay.style.color      = color;

        bpmDisplay.style.textShadow = `0 0 20px ${color}`;



        log(`🎚 Texture (entrainment) → reverb:${reverbWet} delayFb:${delayFb} padVol:${padVol} musicTempo:${musicTempo}`);

    }



    // Override applyBpm để gọi texture update

    const _origApplyBpm = applyBpm;

    // Không thể override function declaration, thêm hook vào ws.send thay thế

    function sendBpmToServer(bpm) {

        if (ws && ws.readyState === WebSocket.OPEN) {

            ws.send(JSON.stringify({ bpm }));

        }

        applyBpmTexture(bpm);

    }



    // ================================================================

    // WEBSOCKET — sinh nhạc

    // ================================================================

    btnGenerate.addEventListener('click', async () => {

        if (currentBpm === 0) {

            alert('Chưa có BPM! Kết nối đồng hồ hoặc nhập thủ công.');

            return;

        }



        await Tone.start();

        await Tone.loaded();

        log("✅ Piano samples loaded");



        // Khôi phục gain (có thể đang = 0 nếu vừa Stop)

        masterGain.gain.cancelScheduledValues(Tone.now());

        masterGain.gain.setValueAtTime(1.5, Tone.now());



        if (ws) ws.close();



        setStatus(`Đang kết nối AI với ${currentBpm} BPM…`, 'info');

        btnGenerate.textContent = 'AI đang truyền nốt…';

        btnGenerate.disabled    = true;

        btnStop.disabled        = false;

        bpmDisplay.style.animation = 'pulse 1s infinite';



        // Khởi động texture ngay

        applyBpmTexture(currentBpm);



        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';

        ws = new WebSocket(`${protocol}//${window.location.host}/ws/vibe`);



        ws.onopen = () => {

            setStatus('🎵 Đang phát nhạc Real-time…', 'ok');

            ws.send(JSON.stringify({ bpm: currentBpm }));

        };



        let startTime = Tone.now() + 0.15;



        ws.onmessage = (event) => {

            const data = JSON.parse(event.data);



            // Sync Transport BPM với music_bpm server trả về (entrainment tempo)

            if (data.music_bpm) {

                Tone.getTransport().bpm.rampTo(data.music_bpm, 2);

            }



            data.notes.forEach(n => {

                const noteStr = Tone.Frequency(n.note, "midi").toNote();

                const t = startTime + n.time;



                if (n.type === "melody") {

                    // Velocity melody cũng phản ánh BPM: cao → piano mạnh hơn

                    const velBoost = currentBpm > 100 ? 1.15 : 1.0;

                    const vel = Math.min(1, (n.velocity / 127) * velBoost);

                    piano.triggerAttackRelease(noteStr, n.duration, t, vel);

                }

                else if (n.type === "chord") {

                    pad.triggerAttackRelease(noteStr, n.duration, t, n.velocity / 127);

                }

      

            });



            startTime += data.batch_duration;

        };



        // Mỗi khi BPM thay đổi từ đồng hồ/manual → cập nhật texture + drum

        const origApply = applyBpm;

        // Patch ws.send để bắt BPM change

        const _origSend = ws.send.bind(ws);

        ws.send = function(data) {

            try {

                const parsed = JSON.parse(data);

                if (parsed.bpm) applyBpmTexture(parsed.bpm);

            } catch {}

            return _origSend(data);

        };



        ws.onerror = (err) => {

            log('WebSocket Error: ' + err);

            setStatus('Lỗi kết nối tới AI!', 'err');

        };



        ws.onclose = () => {

            btnGenerate.textContent    = '2. Sinh nhạc AI';

            btnGenerate.disabled       = false;

            btnStop.disabled           = true;

            bpmDisplay.style.animation = 'none';

        };

    });



    // ================================================================

    // STOP — tắt ngay lập tức, không chờ note đã schedule trong buffer

    // ================================================================

    btnStop.addEventListener('click', () => {

        if (ws) { ws.close(); ws = null; }



        // cancelScheduledValues triệt tiêu mọi ramp đang chờ,

        // setValueAtTime(0) tắt gain TỨC THỜI — kể cả note đã queue sẵn.

        // Gain KHÔNG được restore ở đây — chỉ restore khi nhấn Generate lại.

        masterGain.gain.cancelScheduledValues(Tone.now());

        masterGain.gain.setValueAtTime(0, Tone.now());



        piano.releaseAll();

        pad.releaseAll();



        setStatus('Đã dừng nhạc.', 'info');

    });

</script>
</body>
</html>