File size: 119,242 Bytes
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
 
62c33e5
 
225f569
62c33e5
 
225f569
62c33e5
 
 
 
 
 
 
 
 
 
225f569
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
225f569
62c33e5
 
 
 
225f569
62c33e5
 
 
 
 
225f569
62c33e5
 
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
62c33e5
 
 
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324566d
 
 
 
62c33e5
 
 
324566d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
 
 
 
 
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
 
 
 
 
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
225f569
 
62c33e5
 
 
225f569
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
 
62c33e5
225f569
62c33e5
 
 
 
 
 
 
225f569
21e7939
225f569
 
 
 
62c33e5
 
 
225f569
 
 
 
 
62c33e5
 
225f569
 
 
 
62c33e5
 
 
 
 
225f569
324566d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
 
324566d
62c33e5
 
225f569
62c33e5
 
 
225f569
 
 
 
 
 
 
 
62c33e5
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
225f569
 
 
 
 
 
 
 
62c33e5
 
225f569
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
62c33e5
 
 
225f569
62c33e5
 
 
 
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324566d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62c33e5
 
 
 
324566d
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
62c33e5
 
225f569
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
21e7939
225f569
 
 
 
 
21e7939
62c33e5
225f569
62c33e5
 
225f569
21e7939
225f569
 
62c33e5
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
62c33e5
225f569
62c33e5
225f569
62c33e5
 
225f569
62c33e5
 
 
 
 
 
 
 
 
 
 
225f569
62c33e5
 
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225f569
62c33e5
 
 
 
 
225f569
 
62c33e5
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>VitalTrack Pro</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
    <script src="https://unpkg.com/feather-icons"></script>
    
    <style>
        :root {
            --primary: #10b981;
            --primary-dark: #059669;
            --secondary: #06b6d4;
            --secondary-dark: #0891b2;
            --bg-dark: #0f172a;
            --bg-light: #f8fafc;
            --card-dark: #1e293b;
            --card-light: #ffffff;
            --text-dark: #f1f5f9;
            --text-light: #0f172a;
            --border-dark: #334155;
            --border-light: #e2e8f0;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'SF Pro Display', 'Prompt', sans-serif;
            background: var(--bg-dark);
            color: var(--text-dark);
            min-height: 100vh;
            overflow-x: hidden;
        }

        body.light-mode {
            background: var(--bg-light);
            color: var(--text-light);
        }

        .card {
            background: var(--card-dark);
            border-radius: 16px;
            padding: 16px;
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            border: 1px solid var(--border-dark);
        }

        body.light-mode .card {
            background: var(--card-light);
            border-color: var(--border-light);
        }

        .tab-content {
            display: none;
            animation: fadeIn 0.3s ease-in-out;
        }

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

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--card-dark);
            border-top: 1px solid var(--border-dark);
            padding: 8px 0;
            z-index: 100;
        }

        body.light-mode .bottom-nav {
            background: var(--card-light);
        }

        .nav-item {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 8px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .nav-item.active {
            color: var(--primary);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 200;
            padding: 20px;
            overflow-y: auto;
        }

        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: var(--card-dark);
            border-radius: 20px;
            width: 100%;
            max-width: 390px;
            max-height: 90vh;
            overflow-y: auto;
        }

        body.light-mode .modal-content {
            background: var(--card-light);
        }

        .donut-chart {
            width: 120px;
            height: 120px;
            position: relative;
        }

        .progress-ring {
            transform: rotate(-90deg);
        }

        .progress-ring-bg {
            stroke: var(--border-dark);
        }

        .progress-ring-fill {
            transition: stroke-dashoffset 0.5s ease;
        }

        .skeleton {
            background: linear-gradient(90deg, var(--border-dark) 25%, var(--card-dark) 50%, var(--border-dark) 75%);
            background-size: 200% 100%;
            animation: loading 1.5s infinite;
        }

        @keyframes loading {
            0% { background-position: 200% 0; }
            100% { background-position: -200% 0; }
        }

        .sparkline {
            stroke: var(--primary);
            fill: none;
            stroke-width: 2;
        }

        .chart-container {
            position: relative;
            height: 200px;
            width: 100%;
        }

        .pulse {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.05); opacity: 0.8; }
            100% { transform: scale(1); opacity: 1; }
        }

        .slide-up {
            animation: slideUp 0.3s ease-out;
        }

        @keyframes slideUp {
            from { transform: translateY(100%); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        @media (max-width: 390px) {
            body {
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="sticky top-0 z-50 card rounded-b-3xl mb-4">
        <div class="flex justify-between items-center p-4">
            <div class="flex items-center gap-2">
                <i data-feather="activity" class="w-5 h-5 text-primary"></i>
                <span class="font-semibold text-lg" data-translate="app-title">VitalTrack Pro</span>
            </div>
            <div class="flex gap-3">
                <button onclick="toggleLanguage()" class="p-2 rounded-lg hover:bg-gray-700 transition">
                    <span id="lang-toggle" class="text-sm font-medium">TH</span>
                </button>
                <button onclick="toggleTheme()" class="p-2 rounded-lg hover:bg-gray-700 transition">
                    <i data-feather="moon" class="w-5 h-5"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="pb-20 px-4 max-w-md mx-auto">
        <!-- Today Tab -->
        <div id="tab-today" class="tab-content active">
            <div class="mb-4">
                <h2 class="text-2xl font-bold mb-1" data-translate="today">วันนี้</h2>
                <p class="text-sm opacity-75" id="current-date">11 พฤศจิกายน 2025</p>
            </div>

            <!-- Daily Overview Card -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3" data-translate="daily-overview">ภาพรวมประจำวัน</h3>
                <div class="grid grid-cols-2 gap-3">
                    <div class="text-center p-3 rounded-lg bg-gradient-to-br from-red-500/20 to-red-600/20">
                        <div class="text-2xl font-bold text-red-400" id="strain-value">13.2</div>
                        <div class="text-xs opacity-75" data-translate="strain">ความเหนื่อย</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-gradient-to-br from-green-500/20 to-green-600/20">
                        <div class="text-2xl font-bold text-green-400" id="recovery-value">74%</div>
                        <div class="text-xs opacity-75" data-translate="recovery">การฟื้นตัว</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-gradient-to-br from-blue-500/20 to-blue-600/20">
                        <div class="text-2xl font-bold text-blue-400" id="sleep-value">82%</div>
                        <div class="text-xs opacity-75" data-translate="sleep">การนอนหลับ</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-gradient-to-br from-purple-500/20 to-purple-600/20">
                        <div class="text-2xl font-bold text-purple-400" id="hrv-value">85</div>
                        <div class="text-xs opacity-75">HRV (ms)</div>
                    </div>
                </div>
            </div>

            <!-- Donut Charts -->
            <div class="grid grid-cols-3 gap-3 mb-4">
                <div class="card text-center">
                    <div class="donut-chart mx-auto mb-2">
                        <svg width="120" height="120">
                            <circle cx="60" cy="60" r="50" fill="none" stroke-width="8" class="progress-ring-bg"/>
                            <circle id="strain-ring" cx="60" cy="60" r="50" fill="none" stroke-width="8" stroke="#ef4444" 
                                stroke-dasharray="314" stroke-dashoffset="250" class="progress-ring progress-ring-fill"/>
                        </svg>
                        <div class="absolute inset-0 flex items-center justify-center">
                            <span class="text-xl font-bold">13.2</span>
                        </div>
                    </div>
                    <div class="text-xs" data-translate="strain">ความเหนื่อย</div>
                </div>
                <div class="card text-center">
                    <div class="donut-chart mx-auto mb-2">
                        <svg width="120" height="120">
                            <circle cx="60" cy="60" r="50" fill="none" stroke-width="8" class="progress-ring-bg"/>
                            <circle id="recovery-ring" cx="60" cy="60" r="50" fill="none" stroke-width="8" stroke="#22c55e" 
                                stroke-dasharray="314" stroke-dashoffset="82" class="progress-ring progress-ring-fill"/>
                        </svg>
                        <div class="absolute inset-0 flex items-center justify-center">
                            <span class="text-xl font-bold">74%</span>
                        </div>
                    </div>
                    <div class="text-xs" data-translate="recovery">การฟื้นตัว</div>
                </div>
                <div class="card text-center">
                    <div class="donut-chart mx-auto mb-2">
                        <svg width="120" height="120">
                            <circle cx="60" cy="60" r="50" fill="none" stroke-width="8" class="progress-ring-bg"/>
                            <circle id="sleep-ring" cx="60" cy="60" r="50" fill="none" stroke-width="8" stroke="#3b82f6" 
                                stroke-dasharray="314" stroke-dashoffset="57" class="progress-ring progress-ring-fill"/>
                        </svg>
                        <div class="absolute inset-0 flex items-center justify-center">
                            <span class="text-xl font-bold">82%</span>
                        </div>
                    </div>
                    <div class="text-xs" data-translate="sleep">การนอนหลับ</div>
                </div>
            </div>

            <!-- Real-time HR -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3 flex items-center gap-2">
                    <i data-feather="heart" class="w-4 h-4 text-red-500 pulse"></i>
                    <span data-translate="current-hr">อัตราการเต้นหัวใจปัจจุบัน</span>
                </h3>
                <div class="text-3xl font-bold text-red-400 mb-2">
                    <span id="current-hr">64</span> <span class="text-sm font-normal">bpm</span>
                </div>
                <canvas id="hr-chart" height="80"></canvas>
            </div>

            <!-- Timeline -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3" data-translate="timeline">ไทม์ไลน์กิจกรรม</h3>
                <div id="timeline" class="space-y-2">
                    <div class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-800/50 transition">
                        <i data-feather="activity" class="w-4 h-4 text-blue-400"></i>
                        <div class="flex-1">
                            <div class="font-medium text-sm">Morning Run</div>
                            <div class="text-xs opacity-75">07:00 - 07:30 • 245 kcal • Avg HR 145</div>
                        </div>
                    </div>
                    <div class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-800/50 transition">
                        <i data-feather="shopping-bag" class="w-4 h-4 text-green-400"></i>
                        <div class="flex-1">
                            <div class="font-medium text-sm">Walking</div>
                            <div class="text-xs opacity-75">12:30 - 13:00 • 85 kcal • Avg HR 95</div>
                        </div>
                    </div>
                    <div class="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-800/50 transition">
                        <i data-feather="zap" class="w-4 h-4 text-purple-400"></i>
                        <div class="flex-1">
                            <div class="font-medium text-sm">Gym Session</div>
                            <div class="text-xs opacity-75">18:00 - 19:00 • 420 kcal • Avg HR 130</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Log Journal Button -->
            <button onclick="openJournalModal()" class="w-full card bg-gradient-to-r from-primary to-primary-dark text-white font-semibold py-3 flex items-center justify-center gap-2 hover:opacity-90 transition">
                <i data-feather="edit-3" class="w-4 h-4"></i>
                <span data-translate="log-journal">บันทึก Journal</span>
            </button>
        </div>

        <!-- Recovery Tab -->
        <div id="tab-recovery" class="tab-content">
            <div class="mb-4">
                <h2 class="text-2xl font-bold mb-1" data-translate="recovery">การฟื้นตัว</h2>
                <p class="text-sm opacity-75" data-translate="recovery-subtitle">ติดตามสถานะการฟื้นตัวของคุณ</p>
            </div>

            <!-- Recovery Score Card -->
            <div class="card mb-4">
                <div class="text-center py-4">
                    <div class="text-5xl font-bold text-green-400 mb-2">74</div>
                    <div class="text-lg font-medium mb-3" data-translate="recovery-score">คะแนนการฟื้นตัว</div>
                    <div class="w-full bg-gray-700 rounded-full h-4 mb-2">
                        <div class="bg-gradient-to-r from-green-500 to-green-400 h-4 rounded-full" style="width: 74%"></div>
                    </div>
                    <div class="flex justify-between text-xs opacity-75">
                        <span data-translate="poor">แย่</span>
                        <span data-translate="fair">ปานกลาง</span>
                        <span data-translate="good">ดี</span>
                        <span data-translate="excellent">ยอดเยี่ยม</span>
                    </div>
                </div>
            </div>

            <!-- HRV Chart -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">HRV (7 วัน)</h3>
                <canvas id="hrv-chart" height="150"></canvas>
            </div>

            <!-- Resting HR Chart -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3" data-translate="resting-hr">อัตราการเต้นหัวใจขณะพัก</h3>
                <canvas id="rhr-chart" height="150"></canvas>
            </div>

            <!-- Factors -->
            <div class="card">
                <h3 class="font-semibold mb-3" data-translate="factors">ปัจจัยที่ส่งผล</h3>
                <div class="space-y-3">
                    <div class="flex justify-between items-center">
                        <span data-translate="sleep-performance">ประสิทธิภาพการนอน</span>
                        <span class="font-medium text-green-400">82%</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span data-translate="yesterday-strain">ความเหนื่อยเมื่อวาน</span>
                        <span class="font-medium text-yellow-400">11.8</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span data-translate="respiration-rate">อัตราการหายใจ</span>
                        <span class="font-medium">14.2 breaths/min</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span data-translate="skin-temp">อุณหภูมิผิวหนัง</span>
                        <span class="font-medium">+0.1°C</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sleep Tab -->
        <div id="tab-sleep" class="tab-content">
            <div class="mb-4">
                <h2 class="text-2xl font-bold mb-1" data-translate="sleep">การนอนหลับ</h2>
                <p class="text-sm opacity-75" data-translate="sleep-subtitle">วิเคราะห์คุณภาพการนอนหลับของคุณ</p>
            </div>

            <!-- Sleep Coach Card -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3 flex items-center gap-2">
                    <i data-feather="moon" class="w-4 h-4 text-blue-400"></i>
                    <span data-translate="sleep-coach">Sleep Coach</span>
                </h3>
                <div class="grid grid-cols-2 gap-3">
                    <div class="text-center p-3 rounded-lg bg-blue-500/20">
                        <i data-feather="log-in" class="w-5 h-5 mx-auto mb-1 text-blue-400"></i>
                        <div class="text-xs opacity-75 mb-1" data-translate="bedtime">เวลาเข้านอน</div>
                        <div class="font-semibold">22:45</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-yellow-500/20">
                        <i data-feather="log-out" class="w-5 h-5 mx-auto mb-1 text-yellow-400"></i>
                        <div class="text-xs opacity-75 mb-1" data-translate="wake-time">ตื่นนอน</div>
                        <div class="font-semibold">06:30</div>
                    </div>
                </div>
                <div class="mt-3 p-3 rounded-lg bg-green-500/20">
                    <div class="flex items-center gap-2 text-green-400">
                        <i data-feather="target" class="w-4 h-4"></i>
                        <span class="text-sm" data-translate="sleep-goal">เป้าหมาย: 7.5 ชั่วโมงตามความเหนื่อยวันนี้</span>
                    </div>
                </div>
            </div>

            <!-- Sleep Stages -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3" data-translate="sleep-stages">ระยะการนอนหลับ</h3>
                <canvas id="sleep-stages-chart" height="150"></canvas>
                <div class="grid grid-cols-4 gap-2 mt-3 text-xs">
                    <div class="flex items-center gap-1">
                        <div class="w-3 h-3 bg-purple-500 rounded"></div>
                        <span>Awake</span>
                    </div>
                    <div class="flex items-center gap-1">
                        <div class="w-3 h-3 bg-blue-400 rounded"></div>
                        <span>Light</span>
                    </div>
                    <div class="flex items-center gap-1">
                        <div class="w-3 h-3 bg-blue-600 rounded"></div>
                        <span>Deep</span>
                    </div>
                    <div class="flex items-center gap-1">
                        <div class="w-3 h-3 bg-cyan-400 rounded"></div>
                        <span>REM</span>
                    </div>
                </div>
            </div>

            <!-- Sleep Performance History -->
            <div class="card">
                <h3 class="font-semibold mb-3" data-translate="sleep-history">ประวัติการนอนหลับ (14 วัน)</h3>
                <canvas id="sleep-history-chart" height="150"></canvas>
            </div>
        </div>

        <!-- Training Tab -->
        <div id="tab-training" class="tab-content">
            <div class="mb-4">
                <h2 class="text-2xl font-bold mb-1" data-translate="training">การฝึก</h2>
                <p class="text-sm opacity-75" data-translate="training-subtitle">บันทึกและติดตามการออกกำลังกาย</p>
            </div>

            <!-- Start Workout Button -->
            <button onclick="startWorkout()" class="w-full card bg-gradient-to-r from-red-500 to-orange-500 text-white font-semibold py-4 flex items-center justify-center gap-2 hover:opacity-90 transition mb-4">
                <i data-feather="play-circle" class="w-6 h-6"></i>
                <span data-translate="start-workout">เริ่ม Live Workout</span>
            </button>

            <!-- Sport Selection -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3" data-translate="select-sport">เลือกชนิดกีฬา</h3>
                <div class="grid grid-cols-4 gap-2">
                    <button class="p-3 rounded-lg bg-blue-500/20 hover:bg-blue-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="activity" class="w-5 h-5 text-blue-400"></i>
                        <span class="text-xs">Run</span>
                    </button>
                    <button class="p-3 rounded-lg bg-green-500/20 hover:bg-green-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="navigation" class="w-5 h-5 text-green-400"></i>
                        <span class="text-xs">Bike</span>
                    </button>
                    <button class="p-3 rounded-lg bg-purple-500/20 hover:bg-purple-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="zap" class="w-5 h-5 text-purple-400"></i>
                        <span class="text-xs">Gym</span>
                    </button>
                    <button class="p-3 rounded-lg bg-cyan-500/20 hover:bg-cyan-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="droplet" class="w-5 h-5 text-cyan-400"></i>
                        <span class="text-xs">Swim</span>
                    </button>
                    <button class="p-3 rounded-lg bg-orange-500/20 hover:bg-orange-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="trending-up" class="w-5 h-5 text-orange-400"></i>
                        <span class="text-xs">HIIT</span>
                    </button>
                    <button class="p-3 rounded-lg bg-pink-500/20 hover:bg-pink-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="heart" class="w-5 h-5 text-pink-400"></i>
                        <span class="text-xs">Yoga</span>
                    </button>
                    <button class="p-3 rounded-lg bg-indigo-500/20 hover:bg-indigo-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="compass" class="w-5 h-5 text-indigo-400"></i>
                        <span class="text-xs">Hike</span>
                    </button>
                    <button class="p-3 rounded-lg bg-gray-500/20 hover:bg-gray-500/30 transition flex flex-col items-center gap-1">
                        <i data-feather="more-horizontal" class="w-5 h-5 text-gray-400"></i>
                        <span class="text-xs">Other</span>
                    </button>
                </div>
            </div>

            <!-- Live Workout Display (Hidden by default) -->
            <div id="live-workout" class="hidden card mb-4 bg-gradient-to-br from-red-500/10 to-orange-500/10">
                <h3 class="font-semibold mb-3 text-red-400">Live Workout</h3>
                <div class="grid grid-cols-2 gap-3 mb-3">
                    <div class="text-center p-3 rounded-lg bg-black/30">
                        <div class="text-2xl font-bold text-red-400 pulse" id="live-hr">145</div>
                        <div class="text-xs opacity-75">Current HR</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-black/30">
                        <div class="text-2xl font-bold text-orange-400" id="live-time">00:00</div>
                        <div class="text-xs opacity-75">Duration</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-black/30">
                        <div class="text-2xl font-bold text-yellow-400" id="live-kcal">0</div>
                        <div class="text-xs opacity-75">Calories</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-black/30">
                        <div class="text-2xl font-bold text-green-400" id="live-strain">0.0</div>
                        <div class="text-xs opacity-75">Strain</div>
                    </div>
                </div>
                <canvas id="live-hr-chart" height="100"></canvas>
                <button onclick="endWorkout()" class="w-full mt-3 bg-red-500 text-white font-semibold py-2 rounded-lg hover:bg-red-600 transition">
                    End Workout
                </button>
            </div>

            <!-- Recent Workouts -->
            <div class="card">
                <h3 class="font-semibold mb-3" data-translate="recent-workouts">การฝึกล่าสุด</h3>
                <div id="workout-list" class="space-y-2">
                    <!-- Workouts will be populated here -->
                </div>
            </div>
        </div>

        <!-- Trends Tab -->
        <div id="tab-trends" class="tab-content">
            <div class="mb-4">
                <h2 class="text-2xl font-bold mb-1" data-translate="trends">แนวโน้ม</h2>
                <p class="text-sm opacity-75" data-translate="trends-subtitle">วิเคราะห์ข้อมูลระยะยาว</p>
            </div>

            <!-- Time Period Selector -->
            <div class="card mb-4">
                <div class="flex gap-2">
                    <button onclick="setTrendPeriod('7D')" class="flex-1 py-2 px-4 rounded-lg bg-primary/20 text-primary font-medium">7D</button>
                    <button onclick="setTrendPeriod('30D')" class="flex-1 py-2 px-4 rounded-lg hover:bg-gray-700/30 transition font-medium">30D</button>
                    <button onclick="setTrendPeriod('90D')" class="flex-1 py-2 px-4 rounded-lg hover:bg-gray-700/30 transition font-medium">90D</button>
                </div>
            </div>

            <!-- Combined Metrics Chart -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Strain, Recovery & Sleep</h3>
                <canvas id="combined-chart" height="200"></canvas>
            </div>

            <!-- HRV vs RHR Chart -->
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">HRV vs Resting HR</h3>
                <canvas id="hrv-rhr-chart" height="200"></canvas>
            </div>

            <!-- Weekly Summary -->
            <div class="card">
                <h3 class="font-semibold mb-3" data-translate="weekly-report">สรุปประจำสัปดาห์</h3>
                <div class="grid grid-cols-2 gap-3">
                    <div class="text-center p-3 rounded-lg bg-primary/20">
                        <div class="text-xl font-bold text-primary">8.5</div>
                        <div class="text-xs opacity-75">Avg Strain</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-green-500/20">
                        <div class="text-xl font-bold text-green-400">72%</div>
                        <div class="text-xs opacity-75">Avg Recovery</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-blue-500/20">
                        <div class="text-xl font-bold text-blue-400">84%</div>
                        <div class="text-xs opacity-75">Avg Sleep</div>
                    </div>
                    <div class="text-center p-3 rounded-lg bg-purple-500/20">
                        <div class="text-xl font-bold text-purple-400">2,850</div>
                        <div class="text-xs opacity-75">Total Calories</div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Bottom Navigation -->
    <nav class="bottom-nav">
        <div class="flex justify-around items-center max-w-md mx-auto">
            <div class="nav-item active" onclick="switchTab('today')">
                <i data-feather="home" class="w-5 h-5"></i>
                <span class="text-xs mt-1" data-translate="nav-today">วันนี้</span>
            </div>
            <div class="nav-item" onclick="switchTab('recovery')">
                <i data-feather="heart" class="w-5 h-5"></i>
                <span class="text-xs mt-1" data-translate="nav-recovery">ฟื้นตัว</span>
            </div>
            <div class="nav-item" onclick="switchTab('sleep')">
                <i data-feather="moon" class="w-5 h-5"></i>
                <span class="text-xs mt-1" data-translate="nav-sleep">นอน</span>
            </div>
            <div class="nav-item" onclick="switchTab('training')">
                <i data-feather="activity" class="w-5 h-5"></i>
                <span class="text-xs mt-1" data-translate="nav-training">ฝึก</span>
            </div>
            <div class="nav-item" onclick="switchTab('trends')">
                <i data-feather="trending-up" class="w-5 h-5"></i>
                <span class="text-xs mt-1" data-translate="nav-trends">แนวโน้ม</span>
            </div>
            <div class="nav-item" onclick="switchTab('advance-lab')">
                <i data-feather="cpu" class="w-5 h-5"></i>
                <span class="text-xs mt-1">Lab</span>
            </div>
        </div>
    </nav>

    <!-- Advance Lab Tab -->
    <div id="tab-advance-lab" class="tab-content">
        <div class="mb-4">
            <h2 class="text-2xl font-bold mb-1">Advance Lab</h2>
            <p class="text-sm opacity-75 mb-2">เพื่อการศึกษา ไม่ใช่คำวินิจฉัยทางการแพทย์</p>
            <div class="card bg-yellow-500/10 border-yellow-500/30">
                <div class="flex items-center gap-2 text-yellow-400">
                    <i data-feather="alert-triangle" class="w-4 h-4"></i>
                    <span class="text-xs">Last test: 2025-11-01 • 3 abnormal markers detected</span>
                </div>
            </div>
        </div>

        <!-- Lab Sub-Navigation -->
        <div class="card mb-4">
            <div class="flex gap-1 overflow-x-auto pb-2">
                <button onclick="switchLabSubTab('overview')" class="lab-sub-tab px-3 py-2 rounded-lg bg-primary/20 text-primary text-sm font-medium whitespace-nowrap">Overview</button>
                <button onclick="switchLabSubTab('panels')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Panels</button>
                <button onclick="switchLabSubTab('derived')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Derived & Ratios</button>
                <button onclick="switchLabSubTab('trends')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Trends & Heatmap</button>
                <button onclick="switchLabSubTab('correlations')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Correlations</button>
                <button onclick="switchLabSubTab('import')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Import/Export</button>
                <button onclick="switchLabSubTab('settings')" class="lab-sub-tab px-3 py-2 rounded-lg hover:bg-gray-700/30 text-sm font-medium whitespace-nowrap">Lab Settings</button>
            </div>
        </div>

        <!-- Overview Section -->
        <div id="lab-overview" class="lab-sub-content">
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Lab Wellness Index</h3>
                <div class="text-center py-4">
                    <div class="text-5xl font-bold text-green-400 mb-2">78</div>
                    <div class="w-full bg-gray-700 rounded-full h-4 mb-2">
                        <div class="bg-gradient-to-r from-green-500 to-green-400 h-4 rounded-full" style="width: 78%"></div>
                    </div>
                    <div class="flex justify-between text-xs opacity-75">
                        <span>Poor</span>
                        <span>Fair</span>
                        <span>Good</span>
                        <span>Excellent</span>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Panel Radar</h3>
                <canvas id="lab-radar-chart" height="200"></canvas>
            </div>

            <div class="card">
                <h3 class="font-semibold mb-3">Top 5 Abnormal Markers</h3>
                <div class="space-y-2">
                    <div class="flex justify-between items-center p-2 rounded-lg bg-red-500/10 border border-red-500/30">
                        <span class="text-sm">HOMA-IR</span>
                        <span class="text-sm font-bold text-red-400">3.2 ↑</span>
                    </div>
                    <div class="flex justify-between items-center p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
                        <span class="text-sm">AIP</span>
                        <span class="text-sm font-bold text-yellow-400">0.5 ↑</span>
                    </div>
                    <div class="flex justify-between items-center p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
                        <span class="text-sm">hs-CRP</span>
                        <span class="text-sm font-bold text-yellow-400">3.1 mg/L ↑</span>
                    </div>
                    <div class="flex justify-between items-center p-2 rounded-lg bg-blue-500/10 border border-blue-500/30">
                        <span class="text-sm">Ferritin</span>
                        <span class="text-sm font-bold text-blue-400">18 ng/mL ↓</span>
                    </div>
                    <div class="flex justify-between items-center p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
                        <span class="text-sm">Vitamin D</span>
                        <span class="text-sm font-bold text-yellow-400">22 ng/mL ↓</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Panels Section -->
        <div id="lab-panels" class="lab-sub-content hidden">
            <div class="space-y-3" id="lab-panels-container">
                <!-- Panels will be dynamically generated -->
            </div>
        </div>

        <!-- Derived & Ratios Section -->
        <div id="lab-derived" class="lab-sub-content hidden">
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Derived Calculations</h3>
                <div class="space-y-2">
                    <div class="grid grid-cols-2 gap-3">
                        <div class="p-3 rounded-lg bg-gray-700/30">
                            <div class="text-xs opacity-75 mb-1">HOMA-IR</div>
                            <div class="text-lg font-bold text-red-400">3.2</div>
                            <div class="text-xs text-red-400">Insulin Resistance</div>
                        </div>
                        <div class="p-3 rounded-lg bg-gray-700/30">
                            <div class="text-xs opacity-75 mb-1">AIP</div>
                            <div class="text-lg font-bold text-yellow-400">0.5</div>
                            <div class="text-xs text-yellow-400">Atherogenic Risk</div>
                        </div>
                        <div class="p-3 rounded-lg bg-gray-700/30">
                            <div class="text-xs opacity-75 mb-1">LDL-C (calc)</div>
                            <div class="text-lg font-bold">128 mg/dL</div>
                            <div class="text-xs">Borderline</div>
                        </div>
                        <div class="p-3 rounded-lg bg-gray-700/30">
                            <div class="text-xs opacity-75 mb-1">eGFR</div>
                            <div class="text-lg font-bold">92 mL/min</div>
                            <div class="text-xs">Normal</div>
                        </div>
                        <div class="p-3 rounded-lg bg-gray-700/30">
                            <div class="text-xs opacity-75 mb-1">UACR</div>
                            <div class="text-lg font-bold">12 mg/g</div>
                            <div class="text-xs">A1 Normal</div>
                        </div>
                        <div class="p-3 rounded-lg bg-gray-700/30">
                            <div class="text-xs opacity-75 mb-1">Free Testosterone</div>
                            <div class="text-lg font-bold">9.2 ng/dL</div>
                            <div class="text-xs">Normal</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card">
                <h3 class="font-semibold mb-3">Ratios</h3>
                <div class="space-y-2">
                    <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30">
                        <span class="text-sm">TG/HDL Ratio</span>
                        <span class="text-sm font-bold">2.8</span>
                    </div>
                    <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30">
                        <span class="text-sm">A/G Ratio</span>
                        <span class="text-sm font-bold">1.5</span>
                    </div>
                    <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30">
                        <span class="text-sm">Transferrin Saturation</span>
                        <span class="text-sm font-bold">22%</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Trends & Heatmap Section -->
        <div id="lab-trends" class="lab-sub-content hidden">
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Z-Score Heatmap (12 months)</h3>
                <canvas id="lab-heatmap" height="300"></canvas>
            </div>

            <div class="card">
                <h3 class="font-semibold mb-3">Multi-Marker Trends</h3>
                <canvas id="lab-trends-chart" height="200"></canvas>
            </div>
        </div>

        <!-- Correlations Section -->
        <div id="lab-correlations" class="lab-sub-content hidden">
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Correlation Matrix</h3>
                <canvas id="lab-correlation-matrix" height="250"></canvas>
            </div>

            <div class="card">
                <h3 class="font-semibold mb-3">Scatter Plot</h3>
                <div class="mb-3">
                    <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="scatter-x">
                        <option value="homa_ir">HOMA-IR</option>
                        <option value="aip">AIP</option>
                        <option value="hs_crp">hs-CRP</option>
                    </select>
                </div>
                <div class="mb-3">
                    <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="scatter-y">
                        <option value="recovery">Recovery Score</option>
                        <option value="hrv">HRV</option>
                        <option value="sleep">Sleep Score</option>
                    </select>
                </div>
                <canvas id="lab-scatter" height="200"></canvas>
            </div>
        </div>

        <!-- Import/Export Section -->
        <div id="lab-import" class="lab-sub-content hidden">
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Import Data</h3>
                <div class="border-2 border-dashed border-gray-600 rounded-lg p-6 text-center">
                    <i data-feather="upload-cloud" class="w-8 h-8 mx-auto mb-2 opacity-50"></i>
                    <p class="text-sm opacity-75 mb-2">Drag CSV/JSON file here or click to browse</p>
                    <input type="file" id="lab-file-input" accept=".csv,.json" class="hidden">
                    <button onclick="document.getElementById('lab-file-input').click()" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition">
                        Select File
                    </button>
                </div>
            </div>

            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Download Template</h3>
                <button onclick="downloadLabTemplate()" class="w-full p-3 rounded-lg bg-gray-700/50 border border-gray-600 text-left hover:bg-gray-700/70 transition">
                    <i data-feather="download" class="inline w-4 h-4 mr-2"></i>
                    Download CSV Template
                </button>
            </div>

            <div class="card">
                <h3 class="font-semibold mb-3">Export Data</h3>
                <button onclick="exportLabData()" class="w-full p-3 rounded-lg bg-gray-700/50 border border-gray-600 text-left hover:bg-gray-700/70 transition">
                    <i data-feather="download" class="inline w-4 h-4 mr-2"></i>
                    Export Lab Data (JSON)
                </button>
            </div>
        </div>

        <!-- Lab Settings Section -->
        <div id="lab-settings" class="lab-sub-content hidden">
            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Personal Information</h3>
                <div class="space-y-3">
                    <div>
                        <label class="block text-sm mb-1">Sex</label>
                        <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="lab-sex">
                            <option value="male">Male</option>
                            <option value="female">Female</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm mb-1">Age</label>
                        <input type="number" class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="lab-age" value="32">
                    </div>
                    <div>
                        <label class="block text-sm mb-1">Units</label>
                        <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600" id="lab-units">
                            <option value="si">SI (mmol/L)</option>
                            <option value="us">US (mg/dL)</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Reference Set</h3>
                <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600">
                    <option value="general">General Population</option>
                    <option value="athlete">Athlete</option>
                    <option value="elderly">Elderly (60+)</option>
                </select>
            </div>

            <div class="card mb-4">
                <h3 class="font-semibold mb-3">Risk Thresholds</h3>
                <div class="space-y-2">
                    <div class="flex justify-between items-center">
                        <span class="text-sm">Normal Range</span>
                        <div class="w-20 h-2 bg-green-500 rounded"></div>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm">Borderline</span>
                        <div class="w-20 h-2 bg-yellow-500 rounded"></div>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm">High Risk</span>
                        <div class="w-20 h-2 bg-red-500 rounded"></div>
                    </div>
                </div>
            </div>

            <div class="card">
                <button onclick="recalculateLabData()" class="w-full bg-primary text-white font-semibold py-3 rounded-lg hover:bg-primary-dark transition mb-2">
                    Recalculate All
                </button>
                <button onclick="resetLabData()" class="w-full bg-red-500/20 text-red-400 font-semibold py-3 rounded-lg hover:bg-red-500/30 transition">
                    Reset Lab Data
                </button>
            </div>
        </div>
    </div>
<!-- Journal Modal -->
    <div id="journal-modal" class="modal">
        <div class="modal-content slide-up">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-bold" data-translate="log-journal">บันทึก Journal</h3>
                    <button onclick="closeJournalModal()" class="p-2 hover:bg-gray-700/50 rounded-lg transition">
                        <i data-feather="x" class="w-5 h-5"></i>
                    </button>
                </div>
                <div class="space-y-4">
                    <!-- Categories -->
                    <div>
                        <h4 class="font-semibold mb-2" data-translate="nutrition">โภชนาการ</h4>
                        <div class="grid grid-cols-2 gap-2">
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Caffeine</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Alcohol</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Late meal</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Supplements</span>
                            </label>
                        </div>
                    </div>
                    <div>
                        <h4 class="font-semibold mb-2" data-translate="lifestyle">ไลฟ์สไตล์</h4>
                        <div class="grid grid-cols-2 gap-2">
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Travel</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Sick</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Stress</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Meditation</span>
                            </label>
                        </div>
                    </div>
                    <div>
                        <h4 class="font-semibold mb-2" data-translate="recovery-tools">เครื่องมือฟื้นตัว</h4>
                        <div class="grid grid-cols-2 gap-2">
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Sauna</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Cold plunge</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Massage</span>
                            </label>
                            <label class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-700/30 cursor-pointer">
                                <input type="checkbox" class="form-checkbox text-primary">
                                <span class="text-sm">Stretching</span>
                            </label>
                        </div>
                    </div>
                    <div>
                        <label class="block">
                            <span class="font-semibold mb-2 block" data-translate="mood">อารมณ์</span>
                            <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600">
                                <option value="excellent" data-translate="excellent">ยอดเยี่ยม</option>
                                <option value="good" data-translate="good">ดี</option>
                                <option value="fair" data-translate="fair">ปานกลาง</option>
                                <option value="poor" data-translate="poor">แย่</option>
                            </select>
                        </label>
                    </div>
                    <button onclick="saveJournal()" class="w-full bg-primary text-white font-semibold py-3 rounded-lg hover:bg-primary-dark transition">
                        <span data-translate="save">บันทึก</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Modal -->
    <div id="settings-modal" class="modal">
        <div class="modal-content slide-up">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-bold" data-translate="settings">การตั้งค่า</h3>
                    <button onclick="closeSettingsModal()" class="p-2 hover:bg-gray-700/50 rounded-lg transition">
                        <i data-feather="x" class="w-5 h-5"></i>
                    </button>
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="block font-semibold mb-2" data-translate="units">หน่วย</label>
                        <select class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600">
                            <option value="metric">Metric (km, kg)</option>
                            <option value="imperial">Imperial (mi, lbs)</option>
                        </select>
                    </div>
                    <div>
                        <label class="block font-semibold mb-2" data-translate="export-data">ส่งออกข้อมูล</label>
                        <button onclick="exportData()" class="w-full p-2 rounded-lg bg-gray-700/50 border border-gray-600 text-left hover:bg-gray-700/70 transition">
                            <i data-feather="download" class="inline w-4 h-4 mr-2"></i>
                            Download CSV
                        </button>
                    </div>
                    <div>
                        <button onclick="resetData()" class="w-full p-2 rounded-lg bg-red-500/20 border border-red-500 text-red-400 hover:bg-red-500/30 transition">
                            <i data-feather="trash-2" class="inline w-4 h-4 mr-2"></i>
                            <span data-translate="reset-data">รีเซ็ตข้อมูลจำลอง</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        // Lab Catalog - Complete biomarker definitions
        const labCatalog = {
            // Metabolic & Glycemia
            glucose: { id: 'glucose', label_th: 'น้ำตาล', panel: 'Metabolic', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/18, toUS: (v) => v*18, ref_range: {male: {18_39: {low: 3.9, high: 5.6}, 40_59: {low: 4.1, high: 5.8}, 60_: {low: 4.4, high: 6.1}}, female: {18_39: {low: 3.9, high: 5.2}, 40_59: {low: 4.2, high: 5.9}, 60_: {low: 4.5, high: 6.2}}}, direction: 'high_worse', weight: 1.0, color_thresholds: {normal: {low: 3.9, high: 5.6}, borderline: {low: 5.6, high: 6.9}, high_risk: {low: 6.9, high: 999}} },
            insulin: { id: 'insulin', label_th: 'อินซูลิน', panel: 'Metabolic', unit_SI: 'pmol/L', unit_US: 'µU/mL', toSI: (v) => v*6.945, toUS: (v) => v/6.945, ref_range: {male: {18_39: {low: 18, high: 180}, 40_59: {low: 18, high: 180}, 60_: {low: 18, high: 180}}, female: {18_39: {low: 18, high: 180}, 40_59: {low: 18, high: 180}, 60_: {low: 18, high: 180}}}, direction: 'high_worse', weight: 1.0 },
            hba1c: { id: 'hba1c', label_th: 'HbA1c', panel: 'Metabolic', unit_SI: 'mmol/mol', unit_US: '%', toSI: (v) => (v*10.93)-23.5, toUS: (v) => (v+23.5)/10.93, ref_range: {male: {18_39: {low: 20, high: 42}, 40_59: {low: 20, high: 42}, 60_: {low: 20, high: 42}}, female: {18_39: {low: 20, high: 42}, 40_59: {low: 20, high: 42}, 60_: {low: 20, high: 42}}}, direction: 'high_worse', weight: 1.2 },
            
            // Lipids
            total_chol: { id: 'total_chol', label_th: 'คอเลสเตอรอลรวม', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/38.67, toUS: (v) => v*38.67, ref_range: {male: {18_39: {low: 3.1, high: 5.2}, 40_59: {low: 3.7, high: 6.2}, 60_: {low: 4.1, high: 6.8}}, female: {18_39: {low: 3.1, high: 5.2}, 40_59: {low: 3.9, high: 6.4}, 60_: {low: 4.4, high: 7.2}}}, direction: 'high_worse', weight: 0.8 },
            ldl_c: { id: 'ldl_c', label_th: 'LDL-C', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/38.67, toUS: (v) => v*38.67, ref_range: {male: {18_39: {low: 0, high: 3.0}, 40_59: {low: 0, high: 3.4}, 60_: {low: 0, high: 3.6}}, female: {18_39: {low: 0, high: 2.9}, 40_59: {low: 0, high: 3.3}, 60_: {low: 0, high: 3.8}}}, direction: 'high_worse', weight: 1.2 },
            hdl_c: { id: 'hdl_c', label_th: 'HDL-C', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/38.67, toUS: (v) => v*38.67, ref_range: {male: {18_39: {low: 1.0, high: 999}, 40_59: {low: 0.9, high: 999}, 60_: {low: 0.9, high: 999}}, female: {18_39: {low: 1.2, high: 999}, 40_59: {low: 1.1, high: 999}, 60_: {low: 1.0, high: 999}}}, direction: 'low_worse', weight: 1.0 },
            triglycerides: { id: 'triglycerides', label_th: 'ไตรกลีเซอไรด์', panel: 'Lipids', unit_SI: 'mmol/L', unit_US: 'mg/dL', toSI: (v) => v/88.54, toUS: (v) => v*88.54, ref_range: {male: {18_39: {low: 0, high: 1.7}, 40_59: {low: 0, high: 2.0}, 60_: {low: 0, high: 2.3}}, female: {18_39: {low: 0, high: 1.5}, 40_59: {low: 0, high: 1.8}, 60_: {low: 0, high: 2.1}}}, direction: 'high_worse', weight: 0.9 },
            
            // Liver
            ast: { id: 'ast', label_th: 'AST (GOT)', panel: 'Liver', unit_SI: 'U/L', unit_US: 'U/L', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0, high: 40}, 40_59: {low: 0, high: 40}, 60_: {low: 0, high: 40}}, female: {18_39: {low: 0, high: 32}, 40_59: {low: 0, high: 32}, 60_: {low: 0, high: 32}}}, direction: 'high_worse', weight: 0.8 },
            alt: { id: 'alt', label_th: 'ALT (GPT)', panel: 'Liver', unit_SI: 'U/L', unit_US: 'U/L', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0, high: 45}, 40_59: {low: 0, high: 45}, 60_: {low: 0, high: 45}}, female: {18_39: {low: 0, high: 34}, 40_59: {low: 0, high: 34}, 60_: {low: 0, high: 34}}}, direction: 'high_worse', weight: 0.9 },
            
            // Renal
            creatinine: { id: 'creatinine', label_th: 'ครีอะตินีน', panel: 'Renal', unit_SI: 'µmol/L', unit_US: 'mg/dL', toSI: (v) => v*88.4, toUS: (v) => v/88.4, ref_range: {male: {18_39: {low: 62, high: 106}, 40_59: {low: 66, high: 112}, 60_: {low: 72, high: 124}}, female: {18_39: {low: 44, high: 80}, 40_59: {low: 48, high: 86}, 60_: {low: 54, high: 94}}}, direction: 'high_worse', weight: 1.0 },
            
            // Thyroid
            tsh: { id: 'tsh', label_th: 'TSH', panel: 'Thyroid', unit_SI: 'mIU/L', unit_US: 'µIU/mL', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0.4, high: 4.0}, 40_59: {low: 0.4, high: 4.0}, 60_: {low: 0.5, high: 4.5}}, female: {18_39: {low: 0.4, high: 4.0}, 40_59: {low: 0.4, high: 4.2}, 60_: {low: 0.5, high: 5.0}}}, direction: 'u_shaped', weight: 0.9 },
            
            // Inflammation
            hs_crp: { id: 'hs_crp', label_th: 'hs-CRP', panel: 'Inflammation', unit_SI: 'mg/L', unit_US: 'mg/L', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 0, high: 3.0}, 40_59: {low: 0, high: 3.0}, 60_: {low: 0, high: 4.0}}, female: {18_39: {low: 0, high: 3.0}, 40_59: {low: 0, high: 3.5}, 60_: {low: 0, high: 4.5}}}, direction: 'high_worse', weight: 0.8 },
            
            // Nutrition
            vitamin_d: { id: 'vitamin_d', label_th: 'วิตามิน D', panel: 'Nutrition', unit_SI: 'nmol/L', unit_US: 'ng/mL', toSI: (v) => v*2.5, toUS: (v) => v/2.5, ref_range: {male: {18_39: {low: 50, high: 999}, 40_59: {low: 50, high: 999}, 60_: {low: 50, high: 999}}, female: {18_39: {low: 50, high: 999}, 40_59: {low: 50, high: 999}, 60_: {low: 50, high: 999}}}, direction: 'low_worse', weight: 0.7 },
            ferritin: { id: 'ferritin', label_th: 'เฟอร์ริติน', panel: 'Nutrition', unit_SI: 'µg/L', unit_US: 'ng/mL', toSI: (v) => v, toUS: (v) => v, ref_range: {male: {18_39: {low: 30, high: 300}, 40_59: {low: 30, high: 300}, 60_: {low: 20, high: 300}}, female: {18_39: {low: 15, high: 150}, 40_59: {low: 15, high: 150}, 60_: {low: 10, high: 150}}}, direction: 'u_shaped', weight: 0.8 },
            
            // Hormones
            testosterone: { id: 'testosterone', label_th: 'เทสโทสเตอโรนรวม', panel: 'Hormones', unit_SI: 'nmol/L', unit_US: 'ng/dL', toSI: (v) => v*0.0347, toUS: (v) => v/0.0347, ref_range: {male: {18_39: {low: 9.9, high: 27.8}, 40_59: {low: 8.6, high: 25.5}, 60_: {low: 6.6, high: 20.9}}, female: {18_39: {low: 0.3, high: 1.7}, 40_59: {low: 0.2, high: 1.4}, 60_: {low: 0.1, high: 1.2}}}, direction: 'u_shaped', weight: 0.6 },
            
            // Hematology
            hemoglobin: { id: 'hemoglobin', label_th: 'ฮีโมโกลบิน', panel: 'Hematology', unit_SI: 'g/L', unit_US: 'g/dL', toSI: (v) => v*10, toUS: (v) => v/10, ref_range: {male: {18_39: {low: 130, high: 175}, 40_59: {low: 130, high: 175}, 60_: {low: 125, high: 170}}, female: {18_39: {low: 115, high: 155}, 40_59: {low: 115, high: 155}, 60_: {low: 115, high: 155}}}, direction: 'u_shaped', weight: 0.7 }
        };

        // Derived calculation functions
        const labDerived = {
            homa_ir: (glucose, insulin, unit_system = 'us') => {
                const g = unit_system === 'us' ? glucose : labCatalog.glucose.toUS(glucose);
                const i = unit_system === 'us' ? insulin : labCatalog.insulin.toUS(insulin);
                return (g * i) / 405;
            },
            
            ldl_calc: (total_chol, hdl_c, triglycerides, unit_system = 'us') => {
                const tc = unit_system === 'us' ? total_chol : labCatalog.total_chol.toUS(total_chol);
                const hdl = unit_system === 'us' ? hdl_c : labCatalog.hdl_c.toUS(hdl_c);
                const tg = unit_system === 'us' ? triglycerides : labCatalog.triglycerides.toUS(triglycerides);
                return tg < 400 ? tc - hdl - (tg / 5) : null;
            },
            
            aip: (triglycerides, hdl_c, unit_system = 'us') => {
                const tg = unit_system === 'us' ? triglycerides : labCatalog.triglycerides.toUS(triglycerides);
                const hdl = unit_system === 'us' ? hdl_c : labCatalog.hdl_c.toUS(hdl_c);
                return Math.log10(tg / hdl);
            },
            
            tg_hdl_ratio: (triglycerides, hdl_c, unit_system = 'us') => {
                const tg = unit_system === 'us' ? triglycerides : labCatalog.triglycerides.toUS(triglycerides);
                const hdl = unit_system === 'us' ? hdl_c : labCatalog.hdl_c.toUS(hdl_c);
                return tg / hdl;
            },
            
            egfr: (creatinine, age, sex, unit_system = 'us') => {
                const scr = unit_system === 'us' ? creatinine : labCatalog.creatinine.toUS(creatinine);
                const kappa = sex === 'female' ? 0.7 : 0.9;
                const alpha = sex === 'female' ? -0.241 : -0.302;
                const female_factor = sex === 'female' ? 1.012 : 1.0;
                
                return 142 * Math.min(scr/kappa, 1)**alpha * Math.max(scr/kappa, 1)**(-1.200) * 0.9938**age * female_factor;
            },
            
            free_testosterone: (testosterone, shbg, albumin, sex, unit_system = 'us') => {
                const t = unit_system === 'us' ? testosterone : labCatalog.testosterone.toUS(testosterone);
                const shbg_val = shbg || 40; // Default SHBG
                const albumin_val = albumin || 4.3; // Default albumin
                
                // Vermeulen approximation (simplified)
                const c1 = 0.0167; // Association constants
                const c2 = 1.0e-9;
                const c3 = 1.0e-12;
                
                const ft = t / (1 + c1*shbg_val + c2*albumin_val + c3*shbg_val*albumin_val);
                return ft;
            },
            
            z_score: (value, mean, sd) => {
                const z = (value - mean) / sd;
                return Math.max(-3.5, Math.min(3.5, z));
            },
            
            percentile: (z_score) => {
                // Normal CDF approximation
                const t = 1 / (1 + 0.2316419 * Math.abs(z_score));
                const d = 0.3989423 * Math.exp(-z_score * z_score / 2);
                const prob = d * t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));
                return z_score > 0 ? 1 - prob : prob;
            }
        };

        // Lab data generation and management
        const labData = {
            currentValues: {},
            historicalData: {},
            derivedValues: {},
            
            generateMockData: function(months = 24) {
                const now = new Date();
                this.historicalData = {};
                
                for (let i = 0; i < months; i++) {
                    const date = new Date(now);
                    date.setMonth(date.getMonth() - i);
                    const dateKey = date.toISOString().split('T')[0];
                    
                    this.historicalData[dateKey] = {};
                    
                    // Generate values for all biomarkers with realistic trends
                    Object.keys(labCatalog).forEach(biomarkerId => {
                        const biomarker = labCatalog[biomarkerId];
                        const baseValue = this.getBaseValue(biomarkerId);
                        
                        // Add realistic variation and trends
                        let value = baseValue + (Math.random() - 0.5) * baseValue * 0.2;
                        
                        // Add trends based on age/time progression
                        if (i > 6) { // After 6 months
                            if (biomarkerId === 'glucose' || biomarkerId === 'triglycerides') {
                                value *= 1.02; // Gradual increase
                            } else if (biomarkerId === 'hdl_c') {
                                value *= 0.98; // Gradual decrease
                            }
                        }
                        
                        this.historicalData[dateKey][biomarkerId] = value;
                    });
                    
                    // Set latest values as current
                    if (i === 0) {
                        this.currentValues = {...this.historicalData[dateKey]};
                    }
                }
                
                this.calculateDerivedValues();
                this.saveToStorage();
            },
            
            getBaseValue: function(biomarkerId) {
                // Return baseline values within normal ranges
                const baseValues = {
                    glucose: 5.2,
                    insulin: 12,
                    hba1c: 35,
                    total_chol: 4.8,
                    ldl_c: 3.0,
                    hdl_c: 1.4,
                    triglycerides: 1.2,
                    ast: 25,
                    alt: 28,
                    creatinine: 85,
                    tsh: 2.5,
                    hs_crp: 2.0,
                    vitamin_d: 60,
                    ferritin: 80,
                    testosterone: 15,
                    hemoglobin: 145
                };
                
                return baseValues[biomarkerId] || 50;
            },
            
            calculateDerivedValues: function() {
                const current = this.currentValues;
                const unitSystem = 'us'; // Default to US units for calculations
                
                this.derivedValues = {
                    homa_ir: labDerived.homa_ir(current.glucose, current.insulin, unitSystem),
                    ldl_calc: labDerived.ldl_calc(current.total_chol, current.hdl_c, current.triglycerides, unitSystem),
                    aip: labDerived.aip(current.triglycerides, current.hdl_c, unitSystem),
                    tg_hdl_ratio: labDerived.tg_hdl_ratio(current.triglycerides, current.hdl_c, unitSystem),
                    egfr: labDerived.egfr(current.creatinine, 32, 'male', unitSystem),
                    free_testosterone: labDerived.free_testosterone(current.testosterone, null, null, 'male', unitSystem)
                };
            },
            
            getLabWellnessIndex: function() {
                let totalScore = 0;
                let totalWeight = 0;
                
                // Include both current and derived values
                const allValues = {...this.currentValues, ...this.derivedValues};
                
                Object.keys(allValues).forEach(key => {
                    let biomarker = labCatalog[key];
                    if (!biomarker) {
                        // Handle derived values
                        if (key === 'homa_ir') biomarker = {id: 'homa_ir', weight: 1.2, direction: 'high_worse', color_thresholds: {normal: {low: 0, high: 2.5}, borderline: {low: 2.5, high: 3.5}, high_risk: {low: 3.5, high: 999}}};
                        else if (key === 'aip') biomarker = {id: 'aip', weight: 1.0, direction: 'high_worse', color_thresholds: {normal: {low: -999, high: 0.1}, borderline: {low: 0.1, high: 0.24}, high_risk: {low: 0.24, high: 999}}};
                        else if (key === 'tg_hdl_ratio') biomarker = {id: 'tg_hdl_ratio', weight: 0.8, direction: 'high_worse', color_thresholds: {normal: {low: 0, high: 2.0}, borderline: {low: 2.0, high: 3.0}, high_risk: {low: 3.0, high: 999}}};
                        else biomarker = {id: key, weight: 0.5, direction: 'high_worse', color_thresholds: {normal: {low: 0, high: 100}, borderline: {low: 100, high: 200}, high_risk: {low: 200, high: 999}}};
                    }
                    
                    const value = allValues[key];
                    const thresholds = biomarker.color_thresholds || {normal: {low: 0, high: 100}, borderline: {low: 100, high: 200}, high_risk: {low: 200, high: 999}};
                    
                    let score = 100;
                    
                    if (biomarker.direction === 'high_worse') {
                        if (value >= thresholds.high_risk.low) score = 30;
                        else if (value >= thresholds.borderline.low) score = 60;
                    } else if (biomarker.direction === 'low_worse') {
                        if (value <= thresholds.normal.low * 0.5) score = 30;
                        else if (value <= thresholds.normal.low * 0.8) score = 60;
                    } else if (biomarker.direction === 'u_shaped') {
                        if (value < thresholds.normal.low || value > thresholds.normal.high) score = 30;
                    }
                    
                    totalScore += score * (biomarker.weight || 1.0);
                    totalWeight += (biomarker.weight || 1.0);
                });
                
                return Math.round(totalScore / totalWeight);
            },
            
            saveToStorage: function() {
                localStorage.setItem('labData', JSON.stringify({
                    current: this.currentValues,
                    historical: this.historicalData,
                    derived: this.derivedValues
                }));
            },
            
            loadFromStorage: function() {
                const stored = localStorage.getItem('labData');
                if (stored) {
                    const data = JSON.parse(stored);
                    this.currentValues = data.current || {};
                    this.historicalData = data.historical || {};
                    this.derivedValues = data.derived || {};
                } else {
                    this.generateMockData();
                }
            }
        };

        // Lab rendering functions
        const labRenderer = {
            renderPanels: function() {
                const container = document.getElementById('lab-panels-container');
                if (!container) return;
                
                container.innerHTML = '';
                const panels = {};
                
                // Group biomarkers by panel
                Object.keys(labCatalog).forEach(id => {
                    const biomarker = labCatalog[id];
                    if (!panels[biomarker.panel]) {
                        panels[biomarker.panel] = [];
                    }
                    panels[biomarker.panel].push(biomarker);
                });
                
                // Render each panel
                Object.keys(panels).forEach(panelName => {
                    const panelCard = document.createElement('div');
                    panelCard.className = 'card';
                    
                    let panelHTML = `
                        <h3 class="font-semibold mb-3 cursor-pointer flex items-center justify-between" onclick="togglePanelExpand('${panelName}')">
                            ${panelName}
                            <i data-feather="chevron-down" class="w-4 h-4"></i>
                        </h3>
                        <div id="panel-${panelName}" class="space-y-2">
                    `;
                    
                    panels[panelName].forEach(biomarker => {
                        const value = labData.currentValues[biomarker.id];
                        if (value !== undefined) {
                            const status = this.getBiomarkerStatus(value, biomarker);
                            panelHTML += `
                                <div class="flex justify-between items-center p-2 rounded-lg bg-gray-700/30">
                                    <span class="text-sm">${biomarker.label_th}</span>
                                    <span class="text-sm font-bold ${status.color}">${value.toFixed(1)} ${biomarker.unit_US} ${status.icon}</span>
                                </div>
                            `;
                        }
                    });
                    
                    panelHTML += '</div>';
                    panelCard.innerHTML = panelHTML;
                    container.appendChild(panelCard);
                });
                
                feather.replace();
            },
            
            getBiomarkerStatus: function(value, biomarker) {
                const thresholds = biomarker.color_thresholds;
                if (!thresholds) return {color: 'text-gray-400', icon: ''};
                
                let status = {color: 'text-green-400', icon: '✓'};
                
                if (biomarker.direction === 'high_worse') {
                    if (value >= thresholds.high_risk?.low) {
                        status = {color: 'text-red-400', icon: '↑'};
                    } else if (value >= thresholds.borderline?.low) {
                        status = {color: 'text-yellow-400', icon: '↑'};
                    }
                } else if (biomarker.direction === 'low_worse') {
                    if (value <= thresholds.normal?.low * 0.5) {
                        status = {color: 'text-red-400', icon: '↓'};
                    } else if (value <= thresholds.normal?.low * 0.8) {
                        status = {color: 'text-blue-400', icon: '↓'};
                    }
                } else if (biomarker.direction === 'u_shaped') {
                    if (value < thresholds.normal?.low || value > thresholds.normal?.high) {
                        status = {color: 'text-yellow-400', icon: '⚠'};
                    }
                }
                
                return status;
            },
            
            renderRadarChart: function() {
                const canvas = document.getElementById('lab-radar-chart');
                if (!canvas) return;
                
                const ctx = canvas.getContext('2d');
                canvas.width = canvas.offsetWidth;
                canvas.height = 200;
                
                const panels = ['Metabolic', 'Lipids', 'Liver', 'Renal', 'Thyroid', 'Inflammation', 'Nutrition', 'Hematology', 'Hormones'];
                const panelScores = panels.map(panel => {
                    let totalScore = 0;
                    let count = 0;
                    
                    Object.keys(labCatalog).forEach(id => {
                        if (labCatalog[id].panel === panel) {
                            const value = labData.currentValues[id];
                            if (value !== undefined) {
                                const status = this.getBiomarkerStatus(value, labCatalog[id]);
                                totalScore += status.color === 'text-green-400' ? 100 : 
                                              status.color === 'text-yellow-400' ? 60 : 
                                              status.color === 'text-blue-400' ? 60 : 30;
                                count++;
                            }
                        }
                    });
                    
                    return count > 0 ? totalScore / count : 50;
                });
                
                // Draw radar chart
                const centerX = canvas.width / 2;
                const centerY = canvas.height / 2;
                const radius = Math.min(centerX, centerY) - 20;
                const angleStep = (Math.PI * 2) / panels.length;
                
                ctx.strokeStyle = '#10b981';
                ctx.lineWidth = 2;
                ctx.fillStyle = 'rgba(16, 185, 129, 0.2)';
                
                ctx.beginPath();
                panelScores.forEach((score, index) => {
                    const angle = angleStep * index - Math.PI / 2;
                    const x = centerX + Math.cos(angle) * radius * (score / 100);
                    const y = centerY + Math.sin(angle) * radius * (score / 100);
                    
                    if (index === 0) {
                        ctx.moveTo(x, y);
                    } else {
                        ctx.lineTo(x, y);
                    }
                });
                ctx.closePath();
                ctx.fill();
                ctx.stroke();
                
                // Draw labels
                ctx.fillStyle = '#f1f5f9';
                ctx.font = '11px sans-serif';
                panels.forEach((panel, index) => {
                    const angle = angleStep * index - Math.PI / 2;
                    const x = centerX + Math.cos(angle) * (radius + 15);
                    const y = centerY + Math.sin(angle) * (radius + 15);
                    
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText(panel.substring(0, 8), x, y);
                });
            },
            
            renderHeatmap: function() {
                const canvas = document.getElementById('lab-heatmap');
                if (!canvas) return;
                
                const ctx = canvas.getContext('2d');
                canvas.width = canvas.offsetWidth;
                canvas.height = 300;
                
                const biomarkers = Object.keys(labCatalog).slice(0, 15); // Limit to 15 for visibility
                const months = 12;
                const cellWidth = canvas.width / months;
                const cellHeight = canvas.height / biomarkers.length;
                
                // Draw heatmap
                biomarkers.forEach((biomarkerId, row) => {
                    for (let col = 0; col < months; col++) {
                        const date = new Date();
                        date.setMonth(date.getMonth() - (months - col - 1));
                        const dateKey = date.toISOString().split('T')[0];
                        
                        const value = labData.historicalData[dateKey]?.[biomarkerId];
                        if (value !== undefined) {
                            const biomarker = labCatalog[biomarkerId];
                            const status = this.getBiomarkerStatus(value, biomarker);
                            
                            ctx.fillStyle = status.color === 'text-green-400' ? '#22c55e' :
                                           status.color === 'text-yellow-400' ? '#f59e0b' :
                                           status.color === 'text-blue-400' ? '#3b82f6' :
                                           status.color === 'text-red-400' ? '#ef4444' : '#6b7280';
                            
                            ctx.fillRect(col * cellWidth, row * cellHeight, cellWidth - 1, cellHeight - 1);
                        }
                    }
                });
                
                // Draw labels
                ctx.fillStyle = '#f1f5f9';
                ctx.font = '10px sans-serif';
                
                // Month labels
                const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                monthNames.forEach((month, col) => {
                    ctx.textAlign = 'center';
                    ctx.fillText(month, col * cellWidth + cellWidth/2, canvas.height - 5);
                });
                
                // Biomarker labels
                biomarkers.forEach((biomarkerId, row) => {
                    ctx.textAlign = 'right';
                    ctx.fillText(labCatalog[biomarkerId].label_th.substring(0, 10), cellWidth - 5, row * cellHeight + cellHeight/2);
                });
            }
        };

        // Lab sub-tab switching
        function switchLabSubTab(tabName) {
            // Hide all sub-tabs
            document.querySelectorAll('.lab-sub-content').forEach(tab => {
                tab.classList.add('hidden');
            });
            
            // Show selected sub-tab
            document.getElementById(`lab-${tabName}`).classList.remove('hidden');
            
            // Update tab styles
            document.querySelectorAll('.lab-sub-tab').forEach(tab => {
                tab.classList.remove('bg-primary/20', 'text-primary');
                tab.classList.add('hover:bg-gray-700/30');
            });
            event.currentTarget.classList.add('bg-primary/20', 'text-primary');
            event.currentTarget.classList.remove('hover:bg-gray-700/30');
            
            // Render content based on tab
            if (tabName === 'overview') {
                setTimeout(() => labRenderer.renderRadarChart(), 100);
            } else if (tabName === 'panels') {
                labRenderer.renderPanels();
            } else if (tabName === 'trends') {
                setTimeout(() => labRenderer.renderHeatmap(), 100);
            }
            
            feather.replace();
        }

        // Lab utility functions
        function togglePanelExpand(panelName) {
            const panel = document.getElementById(`panel-${panelName}`);
            if (panel) {
                panel.classList.toggle('hidden');
            }
        }

        function downloadLabTemplate() {
            const csvContent = "date,biomarker_id,value,unit\n2025-11-01,glucose,95,mg/dL\n2025-11-01,insulin,12,µU/mL\n2025-11-01,total_chol,185,mg/dL\n2025-11-01,hdl_c,45,mg/dL\n2025-11-01,triglycerides,120,mg/dL";
            
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'lab_template.csv';
            a.click();
            URL.revokeObjectURL(url);
            
            showToast('Template downloaded!');
        }

        function exportLabData() {
            const data = {
                current: labData.currentValues,
                historical: labData.historicalData,
                derived: labData.derivedValues,
                catalog: labCatalog
            };
            
            const jsonContent = JSON.stringify(data, null, 2);
            const blob = new Blob([jsonContent], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'lab_data.json';
            a.click();
            URL.revokeObjectURL(url);
            
            showToast('Lab data exported!');
        }

        function importLabData(file) {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                try {
                    if (file.name.endsWith('.json')) {
                        const data = JSON.parse(e.target.result);
                        labData.currentValues = data.current || {};
                        labData.historicalData = data.historical || {};
                        labData.derivedValues = data.derived || {};
                    } else if (file.name.endsWith('.csv')) {
                        // Parse CSV
                        const lines = e.target.result.split('\n');
                        const headers = lines[0].split(',');
                        
                        for (let i = 1; i < lines.length; i++) {
                            if (lines[i].trim()) {
                                const values = lines[i].split(',');
                                const date = values[0];
                                const biomarkerId = values[1];
                                const value = parseFloat(values[2]);
                                
                                if (!labData.historicalData[date]) {
                                    labData.historicalData[date] = {};
                                }
                                labData.historicalData[date][biomarkerId] = value;
                                
                                if (i === 1) { // First row as current
                                    labData.currentValues[biomarkerId] = value;
                                }
                            }
                        }
                    }
                    
                    labData.calculateDerivedValues();
                    labData.saveToStorage();
                    showToast('Data imported successfully!');
                    
                    // Refresh UI
                    if (document.getElementById('tab-advance-lab').classList.contains('active')) {
                        const activeSubTab = document.querySelector('.lab-sub-content:not(.hidden)');
                        if (activeSubTab) {
                            const tabName = activeSubTab.id.replace('lab-', '');
                            if (tabName === 'panels') labRenderer.renderPanels();
                            else if (tabName === 'overview') labRenderer.renderRadarChart();
                        }
                    }
                } catch (error) {
                    showToast('Import failed: ' + error.message);
                }
            };
            
            reader.readAsText(file);
        }

        function recalculateLabData() {
            labData.calculateDerivedValues();
            labData.saveToStorage();
            showToast('Lab data recalculated!');
            
            // Refresh UI
            if (document.getElementById('tab-advance-lab').classList.contains('active')) {
                const activeSubTab = document.querySelector('.lab-sub-content:not(.hidden)');
                if (activeSubTab) {
                    const tabName = activeSubTab.id.replace('lab-', '');
                    if (tabName === 'panels') labRenderer.renderPanels();
                    else if (tabName === 'overview') labRenderer.renderRadarChart();
                }
            }
        }

        function resetLabData() {
            if (confirm('Are you sure you want to reset all lab data? This cannot be undone.')) {
                labData.generateMockData();
                showToast('Lab data reset!');
                
                // Refresh UI
                if (document.getElementById('tab-advance-lab').classList.contains('active')) {
                    const activeSubTab = document.querySelector('.lab-sub-content:not(.hidden)');
                    if (activeSubTab) {
                        const tabName = activeSubTab.id.replace('lab-', '');
                        if (tabName === 'panels') labRenderer.renderPanels();
                        else if (tabName === 'overview') labRenderer.renderRadarChart();
                    }
                }
            }
        }

        // File input handler
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.getElementById('lab-file-input');
            if (fileInput) {
                fileInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    if (file) {
                        importLabData(file);
                    }
                });
            }
            
            // Initialize lab data
            labData.loadFromStorage();
        });

        // Mock Data
        const mockData = {
profile: {
                name: "Demo User",
                age: 32,
                gender: "unspecified"
            },
            today: {
                date: "2025-11-11",
                strain: 13.2,
                recovery: 74,
                sleep_score: 82,
                hr_current: 64,
                hrv_ms: 85,
                rhr_bpm: 52,
                resp_rate: 14.2,
                skin_temp_delta: 0.1
            },
            sleep: {
                coach_recommended_bedtime: "22:45",
                coach_recommended_waketime: "06:30",
                stages: [
                    {t: "22:50", stage: "Light", duration: 50},
                    {t: "23:40", stage: "Deep", duration: 90},
                    {t: "01:10", stage: "REM", duration: 50},
                    {t: "02:00", stage: "Light", duration: 80},
                    {t: "03:20", stage: "Deep", duration: 140},
                    {t: "05:40", stage: "REM", duration: 50},
                    {t: "06:30", stage: "Awake", duration: 0}
                ],
                history: generateSleepHistory(14)
            },
            recovery_history: generateRecoveryHistory(30),
            strain_history: generateStrainHistory(30),
            workouts: generateWorkouts(10),
            journal_logs: [],
            hrv_data: generateHRVData(14),
            rhr_data: generateRHRData(14)
        };

        // Language data
        const translations = {
            th: {
                "app-title": "VitalTrack Pro",
                "today": "วันนี้",
                "recovery": "การฟื้นตัว",
                "sleep": "การนอนหลับ",
                "training": "การฝึก",
                "trends": "แนวโน้ม",
                "nav-today": "วันนี้",
                "nav-recovery": "ฟื้นตัว",
                "nav-sleep": "นอน",
                "nav-training": "ฝึก",
                "nav-trends": "แนวโน้ม",
                "daily-overview": "ภาพรวมประจำวัน",
                "strain": "ความเหนื่อย",
                "current-hr": "อัตราการเต้นหัวใจปัจจุบัน",
                "timeline": "ไทม์ไลน์กิจกรรม",
                "log-journal": "บันทึก Journal",
                "recovery-score": "คะแนนการฟื้นตัว",
                "poor": "แย่",
                "fair": "ปานกลาง",
                "good": "ดี",
                "excellent": "ยอดเยี่ยม",
                "resting-hr": "อัตราการเต้นหัวใจขณะพัก",
                "factors": "ปัจจัยที่ส่งผล",
                "sleep-performance": "ประสิทธิภาพการนอน",
                "yesterday-strain": "ความเหนื่อยเมื่อวาน",
                "respiration-rate": "อัตราการหายใจ",
                "skin-temp": "อุณหภูมิผิวหนัง",
                "sleep-coach": "Sleep Coach",
                "bedtime": "เวลาเข้านอน",
                "wake-time": "ตื่นนอน",
                "sleep-goal": "เป้าหมาย: 7.5 ชั่วโมงตามความเหนื่อยวันนี้",
                "sleep-stages": "ระยะการนอนหลับ",
                "sleep-history": "ประวัติการนอนหลับ (14 วัน)",
                "start-workout": "เริ่ม Live Workout",
                "select-sport": "เลือกชนิดกีฬา",
                "recent-workouts": "การฝึกล่าสุด",
                "weekly-report": "สรุปประจำสัปดาห์",
                "nutrition": "โภชนาการ",
                "lifestyle": "ไลฟ์สไตล์",
                "recovery-tools": "เครื่องมือฟื้นตัว",
                "mood": "อารมณ์",
                "save": "บันทึก",
                "settings": "การตั้งค่า",
                "units": "หน่วย",
                "export-data": "ส่งออกข้อมูล",
                "reset-data": "รีเซ็ตข้อมูลจำลอง"
            },
            en: {
                "app-title": "VitalTrack Pro",
                "today": "Today",
                "recovery": "Recovery",
                "sleep": "Sleep",
                "training": "Training",
                "trends": "Trends",
                "nav-today": "Today",
                "nav-recovery": "Recovery",
                "nav-sleep": "Sleep",
                "nav-training": "Training",
                "nav-trends": "Trends",
                "daily-overview": "Daily Overview",
                "strain": "Strain",
                "current-hr": "Current Heart Rate",
                "timeline": "Activity Timeline",
                "log-journal": "Log Journal",
                "recovery-score": "Recovery Score",
                "poor": "Poor",
                "fair": "Fair",
                "good": "Good",
                "excellent": "Excellent",
                "resting-hr": "Resting Heart Rate",
                "factors": "Factors",
                "sleep-performance": "Sleep Performance",
                "yesterday-strain": "Yesterday's Strain",
                "respiration-rate": "Respiration Rate",
                "skin-temp": "Skin Temperature",
                "sleep-coach": "Sleep Coach",
                "bedtime": "Bedtime",
                "wake-time": "Wake Time",
                "sleep-goal": "Goal: 7.5 hours based on today's strain",
                "sleep-stages": "Sleep Stages",
                "sleep-history": "Sleep History (14 days)",
                "start-workout": "Start Live Workout",
                "select-sport": "Select Sport",
                "recent-workouts": "Recent Workouts",
                "weekly-report": "Weekly Summary",
                "nutrition": "Nutrition",
                "lifestyle": "Lifestyle",
                "recovery-tools": "Recovery Tools",
                "mood": "Mood",
                "save": "Save",
                "settings": "Settings",
                "units": "Units",
                "export-data": "Export Data",
                "reset-data": "Reset Mock Data"
            }
        };

        // Global state
        let currentLang = 'th';
        let isDarkMode = true;
        let workoutInterval = null;
        let workoutStartTime = null;
        let liveHRData = [];
        let hrChartInstance = null;

        // Generate mock data functions
        function generateSleepHistory(days) {
            const history = [];
            for (let i = days - 1; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                history.push({
                    date: date.toISOString().split('T')[0],
                    duration: 7 + Math.random() * 2,
                    efficiency: 75 + Math.random() * 20,
                    deep: Math.random() * 2,
                    rem: Math.random() * 2,
                    light: 4 + Math.random() * 2
                });
            }
            return history;
        }

        function generateRecoveryHistory(days) {
            const history = [];
            for (let i = days - 1; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                history.push({
                    date: date.toISOString().split('T')[0],
                    recovery: 60 + Math.random() * 30,
                    rhr: 45 + Math.random() * 20,
                    hrv: 60 + Math.random() * 60
                });
            }
            return history;
        }

        function generateStrainHistory(days) {
            const history = [];
            for (let i = days - 1; i >= 0; i--) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                history.push({
                    date: date.toISOString().split('T')[0],
                    strain: 5 + Math.random() * 15
                });
            }
            return history;
        }

        function generateWorkouts(count) {
            const workouts = [];
            const sports = ['Run', 'Bike', 'Gym', 'Swim', 'HIIT', 'Yoga'];
            for (let i = 0; i < count; i++) {
                const date = new Date();
                date.setDate(date.getDate() - i);
                workouts.push({
                    date: date.toISOString().split('T')[0],
                    sport: sports[Math.floor(Math.random() * sports.length)],
                    duration_min: 30 + Math.random() * 60,
                    kcal: 200 + Math.random() * 400,
                    avg_hr: 100 + Math.random() * 60,
                    max_hr: 150 + Math.random() * 30,
                    strain: 5 + Math.random() * 10
                });
            }
            return workouts;
        }

        function generateHRVData(days) {
            const data = [];
            for (let i = days - 1; i >= 0; i--) {
                data.push(60 + Math.random() * 60);
            }
            return data;
        }

        function generateRHRData(days) {
            const data = [];
            for (let i = days - 1; i >= 0; i--) {
                data.push(45 + Math.random() * 20);
            }
            return data;
        }

        // Initialize app
        function initApp() {
            feather.replace();
            initializeCharts();
            updateDateTime();
            setInterval(updateDateTime, 60000);
            setInterval(updateLiveHR, 1000);
            renderWorkoutList();
        }

        // Update date/time
        function updateDateTime() {
            const now = new Date();
            const options = { year: 'numeric', month: 'long', day: 'numeric' };
            const dateStr = now.toLocaleDateString(currentLang === 'th' ? 'th-TH' : 'en-US', options);
            document.getElementById('current-date').textContent = dateStr;
        }
        // Tab switching
        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Show selected tab
            document.getElementById(`tab-${tabName}`).classList.add('active');
            
            // Update nav
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            event.currentTarget.classList.add('active');
            
            // Reinitialize charts if needed
            if (tabName === 'recovery') {
                drawRecoveryCharts();
            } else if (tabName === 'sleep') {
                drawSleepCharts();
            } else if (tabName === 'trends') {
                drawTrendsCharts();
            } else if (tabName === 'advance-lab') {
                // Initialize lab tab with overview
                setTimeout(() => {
                    // Set default sub-tab
                    document.querySelectorAll('.lab-sub-tab').forEach(tab => {
                        tab.classList.remove('bg-primary/20', 'text-primary');
                        tab.classList.add('hover:bg-gray-700/30');
                    });
                    document.querySelector('.lab-sub-tab').classList.add('bg-primary/20', 'text-primary');
                    document.querySelector('.lab-sub-tab').classList.remove('hover:bg-gray-700/30');
                    
                    // Show overview, hide others
                    document.querySelectorAll('.lab-sub-content').forEach(tab => {
                        tab.classList.add('hidden');
                    });
                    document.getElementById('lab-overview').classList.remove('hidden');
                    
                    // Render overview
                    labRenderer.renderRadarChart();
                }, 100);
            }
            
            feather.replace();
        }
// Theme toggle
        function toggleTheme() {
            isDarkMode = !isDarkMode;
            document.body.classList.toggle('light-mode');
            localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
            
            // Update icon
            const icon = document.querySelector('button[onclick="toggleTheme()"] i');
            icon.setAttribute('data-feather', isDarkMode ? 'moon' : 'sun');
            feather.replace();
        }

        // Language toggle
        function toggleLanguage() {
            currentLang = currentLang === 'th' ? 'en' : 'th';
            localStorage.setItem('language', currentLang);
            document.getElementById('lang-toggle').textContent = currentLang.toUpperCase();
            
            // Update all translatable elements
            document.querySelectorAll('[data-translate]').forEach(element => {
                const key = element.getAttribute('data-translate');
                if (translations[currentLang][key]) {
                    element.textContent = translations[currentLang][key];
                }
            });
        }

        // Modal functions
        function openJournalModal() {
            document.getElementById('journal-modal').classList.add('active');
        }

        function closeJournalModal() {
            document.getElementById('journal-modal').classList.remove('active');
        }

        function openSettingsModal() {
            document.getElementById('settings-modal').classList.add('active');
        }

        function closeSettingsModal() {
            document.getElementById('settings-modal').classList.remove('active');
        }

        // Save journal
        function saveJournal() {
            const journalEntry = {
                date: new Date().toISOString(),
                mood: document.querySelector('select').value,
                entries: []
            };
            
            document.querySelectorAll('#journal-modal input[type="checkbox"]:checked').forEach(checkbox => {
                journalEntry.entries.push(checkbox.nextElementSibling.textContent);
            });
            
            mockData.journal_logs.push(journalEntry);
            closeJournalModal();
            
            // Show success message
            showToast('Journal saved successfully!');
        }

        // Workout functions
        function startWorkout() {
            document.getElementById('live-workout').classList.remove('hidden');
            workoutStartTime = Date.now();
            liveHRData = [];
            
            workoutInterval = setInterval(() => {
                updateLiveWorkout();
            }, 1000);
        }

        function endWorkout() {
            if (workoutInterval) {
                clearInterval(workoutInterval);
                workoutInterval = null;
            }
            
            // Save workout
            const workout = {
                date: new Date().toISOString().split('T')[0],
                sport: 'Workout',
                duration_min: Math.floor((Date.now() - workoutStartTime) / 60000),
                kcal: parseInt(document.getElementById('live-kcal').textContent),
                avg_hr: Math.floor(liveHRData.reduce((a, b) => a + b, 0) / liveHRData.length),
                max_hr: Math.max(...liveHRData),
                strain: parseFloat(document.getElementById('live-strain').textContent)
            };
            
            mockData.workouts.unshift(workout);
            renderWorkoutList();
            
            document.getElementById('live-workout').classList.add('hidden');
            showToast('Workout completed!');
        }

        function updateLiveWorkout() {
            const elapsed = Math.floor((Date.now() - workoutStartTime) / 1000);
            const minutes = Math.floor(elapsed / 60);
            const seconds = elapsed % 60;
            document.getElementById('live-time').textContent = 
                `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            // Update calories (rough estimate)
            const calories = Math.floor(elapsed * 0.15);
            document.getElementById('live-kcal').textContent = calories;
            
            // Update strain
            const strain = (elapsed / 60000) * 2;
            document.getElementById('live-strain').textContent = strain.toFixed(1);
            
            // Update HR with simulation
            const hr = 120 + Math.floor(Math.random() * 40);
            document.getElementById('live-hr').textContent = hr;
            liveHRData.push(hr);
            
            // Update live HR chart
            drawLiveHRChart();
        }

        // Render workout list
        function renderWorkoutList() {
            const workoutList = document.getElementById('workout-list');
            workoutList.innerHTML = '';
            
            mockData.workouts.slice(0, 5).forEach(workout => {
                const div = document.createElement('div');
                div.className = 'flex items-center gap-3 p-3 rounded-lg hover:bg-gray-800/50 transition';
                div.innerHTML = `
                    <i data-feather="activity" class="w-4 h-4 text-blue-400"></i>
                    <div class="flex-1">
                        <div class="font-medium text-sm">${workout.sport}</div>
                        <div class="text-xs opacity-75">${workout.duration_min} min • ${workout.kcal} kcal • Avg HR ${workout.avg_hr}</div>
                    </div>
                    <div class="text-sm font-semibold text-purple-400">${workout.strain.toFixed(1)}</div>
                `;
                workoutList.appendChild(div);
            });
            
            feather.replace();
        }

        // Chart functions
        function initializeCharts() {
            // HR Chart
            drawHRChart();
        }

        function drawHRChart() {
            const canvas = document.getElementById('hr-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 80;
            
            // Generate random HR data
            const data = [];
            for (let i = 0; i < 50; i++) {
                data.push(60 + Math.random() * 20);
            }
            
            // Draw line chart
            ctx.strokeStyle = '#ef4444';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            const step = canvas.width / (data.length - 1);
            data.forEach((value, index) => {
                const x = index * step;
                const y = canvas.height - (value - 60) * 3;
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            
            ctx.stroke();
        }

        function drawLiveHRChart() {
            const canvas = document.getElementById('live-hr-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 100;
            
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // Draw line chart
            ctx.strokeStyle = '#ef4444';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            const step = canvas.width / (liveHRData.length - 1);
            liveHRData.forEach((value, index) => {
                const x = index * step;
                const y = canvas.height - (value - 100) * 1.5;
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            
            ctx.stroke();
        }

        function drawRecoveryCharts() {
            drawHRVChart();
            drawRHRChart();
        }

        function drawHRVChart() {
            const canvas = document.getElementById('hrv-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 150;
            
            ctx.strokeStyle = '#10b981';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            const step = canvas.width / (mockData.hrv_data.length - 1);
            mockData.hrv_data.forEach((value, index) => {
                const x = index * step;
                const y = canvas.height - (value - 60);
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            
            ctx.stroke();
        }

        function drawRHRChart() {
            const canvas = document.getElementById('rhr-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 150;
            
            const barWidth = canvas.width / mockData.rhr_data.length - 2;
            
            mockData.rhr_data.forEach((value, index) => {
                const x = index * (barWidth + 2);
                const height = value * 2;
                const y = canvas.height - height;
                
                ctx.fillStyle = '#f59e0b';
                ctx.fillRect(x, y, barWidth, height);
            });
        }

        function drawSleepCharts() {
            drawSleepStagesChart();
            drawSleepHistoryChart();
        }

        function drawSleepStagesChart() {
            const canvas = document.getElementById('sleep-stages-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 150;
            
            const stages = mockData.sleep.stages;
            let currentX = 0;
            
            const colors = {
                'Awake': '#a855f7',
                'Light': '#60a5fa',
                'Deep': '#2563eb',
                'REM': '#06b6d4'
            };
            
            stages.forEach(stage => {
                const width = (stage.duration / 360) * canvas.width;
                ctx.fillStyle = colors[stage.stage];
                ctx.fillRect(currentX, 0, width, canvas.height);
                currentX += width;
            });
        }

        function drawSleepHistoryChart() {
            const canvas = document.getElementById('sleep-history-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 150;
            
            const data = mockData.sleep.history;
            const barWidth = canvas.width / data.length - 2;
            
            data.forEach((day, index) => {
                const x = index * (barWidth + 2);
                const height = day.efficiency;
                const y = canvas.height - height;
                
                ctx.fillStyle = '#3b82f6';
                ctx.fillRect(x, y, barWidth, height);
            });
        }

        function drawTrendsCharts() {
            drawCombinedChart();
            drawHRVRHRChart();
        }

        function drawCombinedChart() {
            const canvas = document.getElementById('combined-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 200;
            
            // Draw strain line
            ctx.strokeStyle = '#ef4444';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            const step = canvas.width / (mockData.strain_history.length - 1);
            mockData.strain_history.forEach((day, index) => {
                const x = index * step;
                const y = canvas.height - day.strain * 10;
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            ctx.stroke();
            
            // Draw recovery line
            ctx.strokeStyle = '#22c55e';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            mockData.recovery_history.slice(0, 30).forEach((day, index) => {
                const x = index * step;
                const y = canvas.height - day.recovery * 1.5;
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            ctx.stroke();
        }

        function drawHRVRHRChart() {
            const canvas = document.getElementById('hrv-rhr-chart');
            if (!canvas) return;
            
            const ctx = canvas.getContext('2d');
            canvas.width = canvas.offsetWidth;
            canvas.height = 200;
            
            // Draw scatter plot correlation
            mockData.recovery_history.forEach((day, index) => {
                const x = (day.hrv / 120) * canvas.width;
                const y = canvas.height - (day.rhr / 65) * canvas.height;
                
                ctx.fillStyle = 'rgba(16, 185, 129, 0.6)';
                ctx.beginPath();
                ctx.arc(x, y, 4, 0, Math.PI * 2);
                ctx.fill();
            });
        }

        function setTrendPeriod(period) {
            // Update button styles
            document.querySelectorAll('.flex.gap-2 button').forEach(btn => {
                btn.classList.remove('bg-primary/20', 'text-primary');
                btn.classList.add('hover:bg-gray-700/30');
            });
            event.target.classList.add('bg-primary/20', 'text-primary');
            event.target.classList.remove('hover:bg-gray-700/30');
            
            // Redraw charts with new period
            drawTrendsCharts();
        }

        // Update live HR
        function updateLiveHR() {
            const hr = 55 + Math.floor(Math.random() * 20);
            document.getElementById('current-hr').textContent = hr;
            document.getElementById('hr_current') && (document.getElementById('hr_current').textContent = hr);
        }

        // Export data
        function exportData() {
            const dataStr = JSON.stringify(mockData, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'vitaltrack-data.json';
            link.click();
            showToast('Data exported successfully!');
        }

        // Reset data
        function resetData() {
            if (confirm('Are you sure you want to reset all mock data?')) {
                location.reload();
            }
        }

        // Toast notification
        function showToast(message) {
            const toast = document.createElement('div');
            toast.className = 'fixed top-20 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50';
            toast.textContent = message;
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.remove();
            }, 3000);
        }

        // Load saved preferences
        function loadPreferences() {
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme === 'light') {
                toggleTheme();
            }
            
            const savedLang = localStorage.getItem('language');
            if (savedLang) {
                currentLang = savedLang;
                document.getElementById('lang-toggle').textContent = currentLang.toUpperCase();
                toggleLanguage();
            }
        }

        // Initialize on load
        document.addEventListener('DOMContentLoaded', () => {
            loadPreferences();
            initApp();
        });

        // Handle resize
        window.addEventListener('resize', () => {
            drawHRChart();
            if (document.getElementById('tab-recovery').classList.contains('active')) {
                drawRecoveryCharts();
            } else if (document.getElementById('tab-sleep').classList.contains('active')) {
                drawSleepCharts();
            } else if (document.getElementById('tab-trends').classList.contains('active')) {
                drawTrendsCharts();
            }
        });
    </script>
<script src="https://huggingface.co/deepsite/deepsite-badge.js"></script>
</body>
</html>