File size: 117,029 Bytes
ca9145f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
// import React, { useState, useEffect } from 'react';
// import { 
//   Brain, Sparkles, CheckCircle, XCircle, ChevronRight, RotateCcw, 
//   ThumbsUp, Award, Clock, Heart, Shield, Lightbulb, ArrowRight,
//   MessageCircle, TrendingUp, Users, Menu, X
// } from 'lucide-react';

// // --- Type Definitions (Interfaces) ---
// interface DistortionResult {
//   has_distortion: boolean;
//   distortion_types: string[];
//   explanation: string;
// }

// interface AnalysisResult {
//   emotional_impact: string;
//   underlying_beliefs: string[];
//   triggers: string[];
//   recommended_therapies: string[];
// }

// interface Candidate {
//   therapy: string;
//   reframe: string;
//   rationale: string;
//   evaluation?: {
//     [key: string]: number; // Allow dynamic evaluation keys like 'empathy', 'logic'
//   };
// }

// interface FormData {
//   situation: string;
//   thought: string;
// }

// const API_BASE_URL = 'http://localhost:8000/api'; 

// const CognitiveReframingPlatform = () => {
//   const [currentPage, setCurrentPage] = useState<string>('home');
//   const [mobileMenuOpen, setMobileMenuOpen] = useState<boolean>(false);
//   const [step, setStep] = useState<number>(1);
  
//   const [formData, setFormData] = useState<FormData>({
//     situation: '',
//     thought: ''
//   });

//   // State with explicit types allowing null
//   const [sessionId, setSessionId] = useState<string | null>(null);
//   const [distortionResult, setDistortionResult] = useState<DistortionResult | null>(null);
//   const [analysis, setAnalysis] = useState<AnalysisResult | null>(null);
//   const [candidates, setCandidates] = useState<Candidate[]>([]); // Array of Candidates
//   const [selectedReframe, setSelectedReframe] = useState<number | null>(null);
//   const [loading, setLoading] = useState<boolean>(false);
//   const [error, setError] = useState<string | null>(null);

//   useEffect(() => {
//     // Initialize session
//     const initSession = async () => {
//       try {
//         const response = await fetch(`${API_BASE_URL}/session/init`, {
//           method: 'POST',
//           headers: { 'Content-Type': 'application/json' }
//         });
//         const data = await response.json();
//         setSessionId(data.session_id);
//       } catch (err) {
//         console.error('Session init failed:', err);
//         setSessionId('demo-session-' + Date.now());
//       }
//     };
//     initSession();
//   }, []);

//   const Navigation = () => (
//     <nav className="bg-white/80 backdrop-blur-md fixed w-full top-0 z-50 shadow-sm">
//       <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
//         <div className="flex justify-between items-center h-16">
//           <div className="flex items-center">
//             <Brain className="w-8 h-8 text-indigo-600 mr-2" />
//             <span className="text-xl font-bold text-gray-900">MindReframe</span>
//           </div>
          
//           <div className="hidden md:flex space-x-8">
//             <button onClick={() => setCurrentPage('home')} className="text-gray-700 hover:text-indigo-600 transition">
//               Home
//             </button>
//             <button onClick={() => setCurrentPage('about')} className="text-gray-700 hover:text-indigo-600 transition">
//               About
//             </button>
//             <button onClick={() => setCurrentPage('therapies')} className="text-gray-700 hover:text-indigo-600 transition">
//               Therapies
//             </button>
//             <button onClick={() => setCurrentPage('app')} className="bg-indigo-600 text-white px-6 py-2 rounded-full hover:bg-indigo-700 transition">
//               Get Started
//             </button>
//           </div>

//           <button 
//             className="md:hidden"
//             onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
//           >
//             {mobileMenuOpen ? <X /> : <Menu />}
//           </button>
//         </div>

//         {mobileMenuOpen && (
//           <div className="md:hidden pb-4">
//             <button onClick={() => { setCurrentPage('home'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-gray-700">
//               Home
//             </button>
//             <button onClick={() => { setCurrentPage('about'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-gray-700">
//               About
//             </button>
//             <button onClick={() => { setCurrentPage('therapies'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-gray-700">
//               Therapies
//             </button>
//             <button onClick={() => { setCurrentPage('app'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-indigo-600 font-semibold">
//               Get Started
//             </button>
//           </div>
//         )}
//       </div>
//     </nav>
//   );

//   const HomePage = () => (
//     <div className="pt-16">
//       {/* Hero Section */}
//       <section className="relative min-h-screen flex items-center bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50">
//         <div className="absolute inset-0 overflow-hidden">
//           <div className="absolute -top-1/2 -right-1/2 w-full h-full bg-gradient-to-br from-indigo-200/30 to-transparent rounded-full blur-3xl"></div>
//           <div className="absolute -bottom-1/2 -left-1/2 w-full h-full bg-gradient-to-tr from-purple-200/30 to-transparent rounded-full blur-3xl"></div>
//         </div>

//         <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20">
//           <div className="grid md:grid-cols-2 gap-12 items-center">
//             <div>
//               <h1 className="text-5xl md:text-6xl font-bold text-gray-900 mb-6 leading-tight">
//                 Transform Your
//                 <span className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-purple-600"> Thoughts</span>
//               </h1>
//               <p className="text-xl text-gray-600 mb-8">
//                 Evidence-based cognitive reframing powered by AI and multiple therapeutic approaches. 
//                 Find the perspective that works for you.
//               </p>
//               <div className="flex flex-col sm:flex-row gap-4">
//                 <button 
//                   onClick={() => setCurrentPage('app')}
//                   className="bg-indigo-600 text-white px-8 py-4 rounded-full font-semibold hover:bg-indigo-700 transition shadow-lg hover:shadow-xl flex items-center justify-center"
//                 >
//                   Start Your Journey
//                   <ArrowRight className="ml-2 w-5 h-5" />
//                 </button>
//                 <button 
//                   onClick={() => setCurrentPage('about')}
//                   className="bg-white text-indigo-600 px-8 py-4 rounded-full font-semibold hover:bg-gray-50 transition shadow-lg flex items-center justify-center"
//                 >
//                   Learn More
//                 </button>
//               </div>
//             </div>

//             <div className="hidden md:block">
//               <div className="relative">
//                 <div className="absolute inset-0 bg-gradient-to-r from-indigo-500 to-purple-500 rounded-3xl blur-2xl opacity-20"></div>
//                 <div className="relative bg-white rounded-3xl shadow-2xl p-8">
//                   <div className="space-y-6">
//                     <div className="flex items-center space-x-4">
//                       <div className="bg-indigo-100 p-3 rounded-full">
//                         <Brain className="w-6 h-6 text-indigo-600" />
//                       </div>
//                       <div>
//                         <div className="h-4 bg-gray-200 rounded w-32 mb-2"></div>
//                         <div className="h-3 bg-gray-100 rounded w-24"></div>
//                       </div>
//                     </div>
//                     <div className="flex items-center space-x-4">
//                       <div className="bg-purple-100 p-3 rounded-full">
//                         <Sparkles className="w-6 h-6 text-purple-600" />
//                       </div>
//                       <div>
//                         <div className="h-4 bg-gray-200 rounded w-40 mb-2"></div>
//                         <div className="h-3 bg-gray-100 rounded w-28"></div>
//                       </div>
//                     </div>
//                     <div className="flex items-center space-x-4">
//                       <div className="bg-pink-100 p-3 rounded-full">
//                         <Heart className="w-6 h-6 text-pink-600" />
//                       </div>
//                       <div>
//                         <div className="h-4 bg-gray-200 rounded w-36 mb-2"></div>
//                         <div className="h-3 bg-gray-100 rounded w-32"></div>
//                       </div>
//                     </div>
//                   </div>
//                 </div>
//               </div>
//             </div>
//           </div>
//         </div>
//       </section>

//       {/* Features Section */}
//       <section className="py-20 bg-white">
//         <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
//           <div className="text-center mb-16">
//             <h2 className="text-4xl font-bold text-gray-900 mb-4">Why MindReframe?</h2>
//             <p className="text-xl text-gray-600">Science-backed features designed for your well-being</p>
//           </div>

//           <div className="grid md:grid-cols-3 gap-8">
//             <div className="bg-gradient-to-br from-indigo-50 to-indigo-100 p-8 rounded-2xl">
//               <div className="bg-indigo-600 w-14 h-14 rounded-full flex items-center justify-center mb-6">
//                 <Shield className="w-7 h-7 text-white" />
//               </div>
//               <h3 className="text-xl font-bold text-gray-900 mb-3">Evidence-Based</h3>
//               <p className="text-gray-600">
//                 Built on proven therapeutic frameworks including CBT, ACT, DBT, and 9 other modalities studied in clinical research.
//               </p>
//             </div>

//             <div className="bg-gradient-to-br from-purple-50 to-purple-100 p-8 rounded-2xl">
//               <div className="bg-purple-600 w-14 h-14 rounded-full flex items-center justify-center mb-6">
//                 <Users className="w-7 h-7 text-white" />
//               </div>
//               <h3 className="text-xl font-bold text-gray-900 mb-3">Personalized</h3>
//               <p className="text-gray-600">
//                 Choose the therapeutic approach that resonates with you. Different perspectives for different people.
//               </p>
//             </div>

//             <div className="bg-gradient-to-br from-pink-50 to-pink-100 p-8 rounded-2xl">
//               <div className="bg-pink-600 w-14 h-14 rounded-full flex items-center justify-center mb-6">
//                 <Lightbulb className="w-7 h-7 text-white" />
//               </div>
//               <h3 className="text-xl font-bold text-gray-900 mb-3">AI-Powered</h3>
//               <p className="text-gray-600">
//                 Advanced language models trained to provide empathetic, safe, and clinically appropriate reframes.
//               </p>
//             </div>
//           </div>
//         </div>
//       </section>

//       {/* How It Works */}
//       <section className="py-20 bg-gradient-to-br from-gray-50 to-gray-100">
//         <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
//           <div className="text-center mb-16">
//             <h2 className="text-4xl font-bold text-gray-900 mb-4">How It Works</h2>
//             <p className="text-xl text-gray-600">Your journey to healthier thinking in 5 simple steps</p>
//           </div>

//           <div className="grid md:grid-cols-5 gap-8">
//             {[
//               { icon: MessageCircle, title: 'Share', desc: 'Tell us your situation and thoughts' },
//               { icon: Brain, title: 'Detect', desc: 'We identify cognitive distortions' },
//               { icon: TrendingUp, title: 'Analyze', desc: 'Deep analysis of thought patterns' },
//               { icon: Sparkles, title: 'Reframe', desc: 'Multiple therapeutic perspectives' },
//               { icon: Heart, title: 'Choose', desc: 'Select what works for you' }
//             ].map((item, idx) => (
//               <div key={idx} className="text-center">
//                 <div className="bg-white w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg">
//                   <item.icon className="w-10 h-10 text-indigo-600" />
//                 </div>
//                 <h3 className="font-bold text-gray-900 mb-2">{item.title}</h3>
//                 <p className="text-sm text-gray-600">{item.desc}</p>
//               </div>
//             ))}
//           </div>
//         </div>
//       </section>

//       {/* CTA Section */}
//       <section className="py-20 bg-gradient-to-r from-indigo-600 to-purple-600">
//         <div className="max-w-4xl mx-auto text-center px-4 sm:px-6 lg:px-8">
//           <h2 className="text-4xl font-bold text-white mb-6">Ready to Transform Your Thinking?</h2>
//           <p className="text-xl text-indigo-100 mb-8">
//             Join thousands who have discovered healthier perspectives through cognitive reframing
//           </p>
//           <button 
//             onClick={() => setCurrentPage('app')}
//             className="bg-white text-indigo-600 px-10 py-4 rounded-full font-bold text-lg hover:bg-gray-100 transition shadow-xl inline-flex items-center"
//           >
//             Start Free Today
//             <ArrowRight className="ml-2 w-5 h-5" />
//           </button>
//         </div>
//       </section>
//     </div>
//   );

//   const AboutPage = () => (
//     <div className="pt-24 pb-20 min-h-screen bg-gradient-to-br from-indigo-50 via-white to-purple-50">
//       <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
//         <h1 className="text-5xl font-bold text-gray-900 mb-8">About MindReframe</h1>
        
//         <div className="bg-white rounded-3xl shadow-xl p-8 mb-8">
//           <h2 className="text-2xl font-bold text-gray-900 mb-4">Our Mission</h2>
//           <p className="text-gray-700 mb-4">
//             MindReframe combines cutting-edge AI technology with evidence-based psychotherapy to make mental health 
//             support accessible, personalized, and effective for everyone.
//           </p>
//           <p className="text-gray-700">
//             We believe that mental well-being should be within reach for all, and that the right perspective 
//             can make a profound difference in how we experience life's challenges.
//           </p>
//         </div>

//         <div className="bg-white rounded-3xl shadow-xl p-8 mb-8">
//           <h2 className="text-2xl font-bold text-gray-900 mb-4">The Science Behind It</h2>
//           <p className="text-gray-700 mb-4">
//             Our platform is built on <strong>ReframeBench</strong>, a comprehensive benchmark evaluating large 
//             language models across 12 distinct therapeutic modalities. This research ensures that our AI 
//             provides clinically appropriate and safe cognitive reframes.
//           </p>
//           <p className="text-gray-700">
//             We integrate principles from CBT, ACT, DBT, REBT, Schema Therapy, MBCT, CFT, Narrative Therapy, 
//             SFBT, and Motivational Interviewing - giving you access to diverse therapeutic perspectives.
//           </p>
//         </div>

//         <div className="bg-white rounded-3xl shadow-xl p-8">
//           <h2 className="text-2xl font-bold text-gray-900 mb-4">Important Note</h2>
//           <p className="text-gray-700">
//             MindReframe is designed as a self-help tool and educational resource. It is not a replacement 
//             for professional mental health care. If you're experiencing severe distress, please reach out 
//             to a qualified mental health professional.
//           </p>
//         </div>
//       </div>
//     </div>
//   );

//   const TherapiesPage = () => (
//     <div className="pt-24 pb-20 min-h-screen bg-gradient-to-br from-purple-50 via-white to-pink-50">
//       <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
//         <h1 className="text-5xl font-bold text-gray-900 mb-4 text-center">Therapeutic Approaches</h1>
//         <p className="text-xl text-gray-600 mb-12 text-center">
//           Explore the diverse perspectives we offer
//         </p>

//         <div className="grid md:grid-cols-2 gap-6">
//           {[
//             { name: 'CBT', full: 'Cognitive Behavioral Therapy', color: 'indigo', desc: 'Challenge and change unhelpful thoughts through evidence and logic' },
//             { name: 'ACT', full: 'Acceptance & Commitment Therapy', color: 'purple', desc: 'Accept thoughts and commit to value-driven actions' },
//             { name: 'DBT', full: 'Dialectical Behavior Therapy', color: 'pink', desc: 'Balance acceptance with change through mindfulness' },
//             { name: 'REBT', full: 'Rational Emotive Behavior Therapy', color: 'blue', desc: 'Dispute irrational beliefs with rational alternatives' },
//             { name: 'MBCT', full: 'Mindfulness-Based Cognitive Therapy', color: 'green', desc: 'Combine mindfulness with cognitive techniques' },
//             { name: 'CFT', full: 'Compassion-Focused Therapy', color: 'rose', desc: 'Cultivate self-compassion and kindness' },
//             { name: 'Schema Therapy', full: 'Schema Therapy', color: 'violet', desc: 'Identify and heal deep-rooted patterns' },
//             { name: 'Narrative', full: 'Narrative Therapy', color: 'amber', desc: 'Rewrite your story and externalize problems' },
//             { name: 'SFBT', full: 'Solution-Focused Brief Therapy', color: 'cyan', desc: 'Focus on solutions rather than problems' },
//             { name: 'MI', full: 'Motivational Interviewing', color: 'emerald', desc: 'Enhance motivation for positive change' }
//           ].map((therapy, idx) => (
//             <div key={idx} className={`bg-gradient-to-br from-${therapy.color}-50 to-${therapy.color}-100 p-6 rounded-2xl border-2 border-${therapy.color}-200`}>
//               <h3 className="text-xl font-bold text-gray-900 mb-2">{therapy.name}</h3>
//               <p className="text-sm text-gray-600 mb-3 font-medium">{therapy.full}</p>
//               <p className="text-gray-700">{therapy.desc}</p>
//             </div>
//           ))}
//         </div>
//       </div>
//     </div>
//   );

//   const detectDistortion = async () => {
//     setLoading(true);
//     setError(null);
//     try {
//       const response = await fetch(`${API_BASE_URL}/detect`, {
//         method: 'POST',
//         headers: { 'Content-Type': 'application/json' },
//         body: JSON.stringify({
//           session_id: sessionId,
//           situation: formData.situation,
//           thought: formData.thought
//         })
//       });
      
//       if (!response.ok) throw new Error('Detection failed');
      
//       const data = await response.json();
//       setDistortionResult(data);
//       if (data.has_distortion) {
//         setStep(2);
//       }
//     } catch (err) {
//       setError('Failed to detect distortions. Please try again.');
//       console.error(err);
//     }
//     setLoading(false);
//   };

//   const analyzeThought = async () => {
//     if (!distortionResult) return;
    
//     setLoading(true);
//     setError(null);
//     try {
//       const response = await fetch(`${API_BASE_URL}/analyze`, {
//         method: 'POST',
//         headers: { 'Content-Type': 'application/json' },
//         body: JSON.stringify({
//           session_id: sessionId,
//           situation: formData.situation,
//           thought: formData.thought,
//           distortions: distortionResult.distortion_types
//         })
//       });
      
//       if (!response.ok) throw new Error('Analysis failed');
      
//       const data = await response.json();
//       setAnalysis(data);
//       setStep(3);
//     } catch (err) {
//       setError('Failed to analyze thought. Please try again.');
//       console.error(err);
//     }
//     setLoading(false);
//   };

//   const generateCandidates = async () => {
//     if (!analysis) return;

//     setLoading(true);
//     setError(null);
//     try {
//       const response = await fetch(`${API_BASE_URL}/reframe`, {
//         method: 'POST',
//         headers: { 'Content-Type': 'application/json' },
//         body: JSON.stringify({
//           session_id: sessionId,
//           situation: formData.situation,
//           thought: formData.thought,
//           recommended_therapies: analysis.recommended_therapies
//         })
//       });
      
//       if (!response.ok) throw new Error('Generation failed');
      
//       const data = await response.json();
//       setCandidates(data.candidates);
//       setStep(4);
//     } catch (err) {
//       setError('Failed to generate reframes. Please try again.');
//       console.error(err);
//     }
//     setLoading(false);
//   };

//   const saveSelection = async () => {
//     if (selectedReframe === null) return;
    
//     try {
//       await fetch(`${API_BASE_URL}/save`, {
//         method: 'POST',
//         headers: { 'Content-Type': 'application/json' },
//         body: JSON.stringify({
//           session_id: sessionId,
//           selected_reframe: candidates[selectedReframe],
//           original_thought: formData.thought
//         })
//       });
//       setStep(5);
//     } catch (err) {
//       console.error('Failed to save selection:', err);
//       setStep(5); // Continue anyway
//     }
//   };

//   const reset = () => {
//     setStep(1);
//     setFormData({ situation: '', thought: '' });
//     setDistortionResult(null);
//     setAnalysis(null);
//     setCandidates([]);
//     setSelectedReframe(null);
//     setError(null);
//   };

//   const AppPage = () => (
//     <div className="pt-20 pb-12 min-h-screen bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50">
//       <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
//         {/* Progress Bar */}
//         <div className="mb-8 bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6">
//           <div className="flex items-center justify-between">
//             {['Input', 'Detect', 'Analyze', 'Reframe', 'Select'].map((label, idx) => (
//               <React.Fragment key={idx}>
//                 <div className="flex flex-col items-center">
//                   <div className={`w-12 h-12 rounded-full flex items-center justify-center font-bold transition-all duration-300 ${
//                     step > idx + 1 ? 'bg-green-500 text-white shadow-lg scale-110' : 
//                     step === idx + 1 ? 'bg-indigo-600 text-white shadow-lg animate-pulse' : 
//                     'bg-gray-200 text-gray-400'
//                   }`}>
//                     {step > idx + 1 ? <CheckCircle className="w-6 h-6" /> : idx + 1}
//                   </div>
//                   <span className="mt-2 text-xs font-medium text-gray-700">{label}</span>
//                 </div>
//                 {idx < 4 && <div className={`flex-1 h-1 mx-2 rounded ${step > idx + 1 ? 'bg-green-500' : 'bg-gray-200'}`}></div>}
//               </React.Fragment>
//             ))}
//           </div>
//         </div>

//         {error && (
//           <div className="mb-6 bg-red-50 border-2 border-red-200 rounded-xl p-4 flex items-center">
//             <XCircle className="w-5 h-5 text-red-600 mr-2" />
//             <p className="text-red-800">{error}</p>
//           </div>
//         )}

//         {/* Step 1: Input */}
//         {step === 1 && (
//           <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
//             <div className="flex items-center mb-6">
//               <div className="bg-indigo-100 p-3 rounded-full mr-4">
//                 <MessageCircle className="w-6 h-6 text-indigo-600" />
//               </div>
//               <h2 className="text-3xl font-bold text-gray-900">Share Your Thoughts</h2>
//             </div>
            
//             <p className="text-gray-600 mb-8">
//               Let's start by understanding what's on your mind. Be as honest and detailed as you'd like.
//             </p>

//             <div className="mb-6">
//               <label className="block text-sm font-semibold text-gray-700 mb-3">
//                 What's the situation?
//               </label>
//               <textarea
//                 className="w-full p-4 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 focus:outline-none resize-none transition-all"
//                 rows={4} // FIXED: number instead of string
//                 placeholder="Describe what happened or what's happening..."
//                 value={formData.situation}
//                 onChange={(e) => setFormData({ ...formData, situation: e.target.value })}
//               />
//             </div>

//             <div className="mb-8">
//               <label className="block text-sm font-semibold text-gray-700 mb-3">
//                 What thoughts came to mind?
//               </label>
//               <textarea
//                 className="w-full p-4 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 focus:outline-none resize-none transition-all"
//                 rows={4} // FIXED: number instead of string
//                 placeholder="What were you thinking or telling yourself?"
//                 value={formData.thought}
//                 onChange={(e) => setFormData({ ...formData, thought: e.target.value })}
//               />
//             </div>

//             <button
//               onClick={detectDistortion}
//               disabled={!formData.situation || !formData.thought || loading}
//               className="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl transform hover:scale-105"
//             >
//               {loading ? (
//                 <>
//                   <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
//                   Analyzing Your Thoughts...
//                 </>
//               ) : (
//                 <>
//                   Begin Analysis
//                   <ChevronRight className="w-5 h-5 ml-2" />
//                 </>
//               )}
//             </button>
//           </div>
//         )}

//         {/* Step 2: Detection */}
//         {step === 2 && distortionResult && (
//           <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
//             <div className="flex items-center mb-6">
//               <div className="bg-yellow-100 p-3 rounded-full mr-4">
//                 <Brain className="w-6 h-6 text-yellow-600" />
//               </div>
//               <h2 className="text-3xl font-bold text-gray-900">Distortion Detection</h2>
//             </div>

//             <div className="bg-gradient-to-r from-yellow-50 to-amber-50 border-2 border-yellow-300 rounded-xl p-6 mb-6">
//               <div className="flex items-start mb-4">
//                 <XCircle className="w-8 h-8 text-yellow-600 mr-3 flex-shrink-0 mt-1" />
//                 <div>
//                   <h3 className="text-xl font-bold text-gray-900 mb-2">Cognitive Distortions Detected</h3>
//                   <p className="text-gray-700">
//                     We've identified some thinking patterns that may be affecting your perspective.
//                   </p>
//                 </div>
//               </div>

//               <div className="mb-4">
//                 <p className="font-semibold text-gray-700 mb-3">Distortion Types:</p>
//                 <div className="flex flex-wrap gap-2">
//                   {distortionResult.distortion_types.map((type, idx) => (
//                     <span key={idx} className="bg-yellow-200 text-yellow-900 px-4 py-2 rounded-full text-sm font-semibold">
//                       {type}
//                     </span>
//                   ))}
//                 </div>
//               </div>

//               <div className="bg-white/50 rounded-lg p-4">
//                 <p className="text-sm text-gray-600 font-medium mb-1">Understanding:</p>
//                 <p className="text-gray-800">{distortionResult.explanation}</p>
//               </div>
//             </div>

//             <button
//               onClick={analyzeThought}
//               disabled={loading}
//               className="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
//             >
//               {loading ? (
//                 <>
//                   <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
//                   Deep Analysis in Progress...
//                 </>
//               ) : (
//                 <>
//                   Continue to Deep Analysis
//                   <ChevronRight className="w-5 h-5 ml-2" />
//                 </>
//               )}
//             </button>
//           </div>
//         )}

//         {/* Step 3: Analysis */}
//         {step === 3 && analysis && (
//           <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
//             <div className="flex items-center mb-6">
//               <div className="bg-purple-100 p-3 rounded-full mr-4">
//                 <TrendingUp className="w-6 h-6 text-purple-600" />
//               </div>
//               <h2 className="text-3xl font-bold text-gray-900">Deep Analysis</h2>
//             </div>

//             <p className="text-gray-600 mb-6">
//               Here's what we've learned about your thought pattern:
//             </p>

//             <div className="space-y-4 mb-8">
//               <div className="bg-gradient-to-r from-blue-50 to-blue-100 border-l-4 border-blue-500 rounded-lg p-5">
//                 <div className="flex items-start">
//                   <Heart className="w-5 h-5 text-blue-600 mr-3 mt-1 flex-shrink-0" />
//                   <div>
//                     <h3 className="font-bold text-gray-900 mb-2">Emotional Impact</h3>
//                     <p className="text-gray-700">{analysis.emotional_impact}</p>
//                   </div>
//                 </div>
//               </div>

//               <div className="bg-gradient-to-r from-purple-50 to-purple-100 border-l-4 border-purple-500 rounded-lg p-5">
//                 <div className="flex items-start">
//                   <Lightbulb className="w-5 h-5 text-purple-600 mr-3 mt-1 flex-shrink-0" />
//                   <div>
//                     <h3 className="font-bold text-gray-900 mb-2">Underlying Beliefs</h3>
//                     <ul className="space-y-1">
//                       {analysis.underlying_beliefs.map((belief, idx) => (
//                         <li key={idx} className="text-gray-700 flex items-start">
//                           <span className="text-purple-600 mr-2">•</span>
//                           <span>{belief}</span>
//                         </li>
//                       ))}
//                     </ul>
//                   </div>
//                 </div>
//               </div>

//               <div className="bg-gradient-to-r from-pink-50 to-pink-100 border-l-4 border-pink-500 rounded-lg p-5">
//                 <div className="flex items-start">
//                   <Clock className="w-5 h-5 text-pink-600 mr-3 mt-1 flex-shrink-0" />
//                   <div>
//                     <h3 className="font-bold text-gray-900 mb-3">Common Triggers</h3>
//                     <div className="flex flex-wrap gap-2">
//                       {analysis.triggers.map((trigger, idx) => (
//                         <span key={idx} className="bg-pink-200 text-pink-900 px-3 py-1 rounded-full text-sm font-medium">
//                           {trigger}
//                         </span>
//                       ))}
//                     </div>
//                   </div>
//                 </div>
//               </div>

//               <div className="bg-gradient-to-r from-green-50 to-green-100 border-l-4 border-green-500 rounded-lg p-5">
//                 <div className="flex items-start">
//                   <Sparkles className="w-5 h-5 text-green-600 mr-3 mt-1 flex-shrink-0" />
//                   <div>
//                     <h3 className="font-bold text-gray-900 mb-3">Recommended Therapeutic Approaches</h3>
//                     <div className="flex flex-wrap gap-2">
//                       {analysis.recommended_therapies.map((therapy, idx) => (
//                         <span key={idx} className="bg-green-200 text-green-900 px-4 py-2 rounded-full text-sm font-bold">
//                           {therapy}
//                         </span>
//                       ))}
//                     </div>
//                   </div>
//                 </div>
//               </div>
//             </div>

//             <button
//               onClick={generateCandidates}
//               disabled={loading}
//               className="w-full bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
//             >
//               {loading ? (
//                 <>
//                   <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
//                   Generating Personalized Reframes...
//                 </>
//               ) : (
//                 <>
//                   Generate Reframes
//                   <Sparkles className="w-5 h-5 ml-2" />
//                 </>
//               )}
//             </button>
//           </div>
//         )}

//         {/* Step 4: Candidates */}
//         {step === 4 && candidates.length > 0 && (
//           <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
//             <div className="flex items-center mb-6">
//               <div className="bg-green-100 p-3 rounded-full mr-4">
//                 <Sparkles className="w-6 h-6 text-green-600" />
//               </div>
//               <h2 className="text-3xl font-bold text-gray-900">Your Reframe Options</h2>
//             </div>

//             <p className="text-gray-600 mb-6">
//               We've generated multiple perspectives based on different therapeutic approaches. 
//               Choose the one that resonates most with you.
//             </p>

//             <div className="space-y-4 mb-8">
//               {candidates.map((candidate, idx) => (
//                 <div
//                   key={idx}
//                   onClick={() => setSelectedReframe(idx)}
//                   className={`p-6 border-2 rounded-xl cursor-pointer transition-all duration-300 transform hover:scale-102 ${
//                     selectedReframe === idx
//                       ? 'border-indigo-500 bg-gradient-to-r from-indigo-50 to-purple-50 shadow-lg'
//                       : 'border-gray-200 hover:border-indigo-300 bg-white hover:shadow-md'
//                   }`}
//                 >
//                   <div className="flex items-center justify-between mb-4">
//                     <span className="bg-indigo-600 text-white px-4 py-2 rounded-full text-sm font-bold">
//                       {candidate.therapy}
//                     </span>
//                     {selectedReframe === idx && (
//                       <div className="flex items-center text-indigo-600">
//                         <ThumbsUp className="w-5 h-5 mr-2" />
//                         <span className="font-semibold">Selected</span>
//                       </div>
//                     )}
//                   </div>

//                   <p className="text-gray-900 font-medium text-lg mb-4 leading-relaxed">
//                     "{candidate.reframe}"
//                   </p>

//                   <div className="bg-white/50 rounded-lg p-4 mb-4">
//                     <p className="text-sm text-gray-600 font-semibold mb-1">Why this works:</p>
//                     <p className="text-gray-700 text-sm">{candidate.rationale}</p>
//                   </div>

//                   {candidate.evaluation && (
//                     <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 pt-4 border-t border-gray-200">
//                       {Object.entries(candidate.evaluation).map(([key, value]) => (
//                         <div key={key} className="text-center">
//                           <p className="text-xs text-gray-500 uppercase font-semibold mb-1">{key}</p>
//                           <div className="flex items-center justify-center">
//                             {[...Array(5)].map((_, i) => (
//                               <Award
//                                 key={i}
//                                 className={`w-4 h-4 ${
//                                   i < value ? 'text-yellow-500 fill-yellow-500' : 'text-gray-300'
//                                 }`}
//                               />
//                             ))}
//                           </div>
//                         </div>
//                       ))}
//                     </div>
//                   )}
//                 </div>
//               ))}
//             </div>

//             <div className="flex gap-4">
//               <button
//                 onClick={reset}
//                 className="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center"
//               >
//                 <RotateCcw className="w-5 h-5 mr-2" />
//                 Start Over
//               </button>

//               <button
//                 onClick={saveSelection}
//                 disabled={selectedReframe === null}
//                 className="flex-1 bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
//               >
//                 Confirm Choice
//                 <CheckCircle className="w-5 h-5 ml-2" />
//               </button>
//             </div>
//           </div>
//         )}

//         {/* Step 5: Success */}
//         {step === 5 && selectedReframe !== null && candidates[selectedReframe] && (
//           <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 text-center animate-fade-in">
//             <div className="inline-block p-4 bg-green-100 rounded-full mb-6">
//               <CheckCircle className="w-20 h-20 text-green-600" />
//             </div>

//             <h2 className="text-4xl font-bold text-gray-900 mb-4">Congratulations!</h2>
//             <p className="text-xl text-gray-600 mb-8">
//               You've taken an important step toward healthier thinking
//             </p>

//             <div className="bg-gradient-to-r from-indigo-50 via-purple-50 to-pink-50 rounded-2xl p-8 mb-8 text-left">
//               <div className="mb-6">
//                 <p className="text-sm text-gray-500 uppercase font-semibold mb-2">Original Thought</p>
//                 <p className="text-gray-800 italic">"{formData.thought}"</p>
//               </div>

//               <div className="flex items-center justify-center my-6">
//                 <ArrowRight className="w-8 h-8 text-indigo-600" />
//               </div>

//               <div>
//                 <p className="text-sm text-gray-500 uppercase font-semibold mb-2">
//                   Your New Perspective ({candidates[selectedReframe].therapy})
//                 </p>
//                 <p className="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-purple-600">
//                   "{candidates[selectedReframe].reframe}"
//                 </p>
//               </div>
//             </div>

//             <div className="bg-blue-50 border-2 border-blue-200 rounded-xl p-6 mb-8 text-left">
//               <div className="flex items-start">
//                 <Lightbulb className="w-6 h-6 text-blue-600 mr-3 mt-1 flex-shrink-0" />
//                 <div>
//                   <h3 className="font-bold text-gray-900 mb-2">Practice Makes Progress</h3>
//                   <p className="text-gray-700 text-sm">
//                     Try using this reframe when you notice similar thoughts. It may feel unnatural at first, 
//                     but with repetition, these healthier thinking patterns will become more automatic.
//                   </p>
//                 </div>
//               </div>
//             </div>

//             <button
//               onClick={reset}
//               className="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
//             >
//               <RotateCcw className="w-5 h-5 mr-2" />
//               Work on Another Thought
//             </button>
//           </div>
//         )}
//       </div>
//     </div>
//   );

//   return (
//     <div className="min-h-screen">
//       <Navigation />
//       {currentPage === 'home' && <HomePage />}
//       {currentPage === 'about' && <AboutPage />}
//       {currentPage === 'therapies' && <TherapiesPage />}
//       {currentPage === 'app' && <AppPage />}

//       {/* Footer */}
//       <footer className="bg-gray-900 text-white py-12">
//         <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
//           <div className="grid md:grid-cols-3 gap-8 mb-8">
//             <div>
//               <div className="flex items-center mb-4">
//                 <Brain className="w-6 h-6 text-indigo-400 mr-2" />
//                 <span className="text-lg font-bold">MindReframe</span>
//               </div>
//               <p className="text-gray-400 text-sm">
//                 Evidence-based cognitive reframing powered by AI and clinical psychology.
//               </p>
//             </div>
            
//             <div>
//               <h3 className="font-bold mb-4">Resources</h3>
//               <ul className="space-y-2 text-sm text-gray-400">
//                 <li>Crisis Hotline: 988</li>
//                 <li>NAMI Helpline: 1-800-950-6264</li>
//                 <li>Crisis Text Line: Text HOME to 741741</li>
//               </ul>
//             </div>

//             <div>
//               <h3 className="font-bold mb-4">Important</h3>
//               <p className="text-sm text-gray-400">
//                 This tool is for educational and self-help purposes. 
//                 If you're in crisis, please seek professional help immediately.
//               </p>
//             </div>
//           </div>

//           <div className="border-t border-gray-800 pt-8 text-center text-sm text-gray-400">
//             <p>&copy; 2025 MindReframe. Based on ReframeBench research.</p>
//           </div>
//         </div>
//       </footer>
//     </div>
//   );
// };

// export default CognitiveReframingPlatform;

import React, { useState, useEffect } from 'react';
import { 
  Brain, Sparkles, CheckCircle, XCircle, ChevronRight, RotateCcw, 
  ThumbsUp, Award, Clock, Heart, Shield, Lightbulb, ArrowRight,
  MessageCircle, TrendingUp, Users, Menu, X
} from 'lucide-react';

// --- Type Definitions (Interfaces) ---
interface DistortionResult {
  has_distortion: boolean;
  distortion_types: string[];
  explanation: string;
}

interface AnalysisResult {
  emotional_impact: string;
  underlying_beliefs: string[];
  triggers: string[];
  recommended_therapies: string[];
  therapy_rationales: Record<string, string>;
}

interface Candidate {
  therapy: string;
  reframe: string;
  rationale: string;
  evaluation?: {
    [key: string]: number; // Allow dynamic evaluation keys like 'empathy', 'logic'
  };
}

interface FormData {
  situation: string;
  thought: string;
}

const API_BASE_URL = '/api';
const THERAPY_FULL_NAMES: Record<string, string> = {
  "CBT": "Cognitive Behavioral Therapy",
  "ACT": "Acceptance and Commitment Therapy",
  "DBT": "Dialectical Behavior Therapy",
  "REBT": "Rational Emotive Behavior Therapy",
  "MBCT": "Mindfulness-Based Cognitive Therapy",
  "CFT": "Compassion-Focused Therapy",
  "SFBT": "Solution-Focused Brief Therapy",
  "MI": "Motivational Interviewing",
  "Schema Therapy": "Schema Therapy",
  "Narrative Therapy": "Narrative Therapy"
};

const CognitiveReframingPlatform = () => {
  const [currentPage, setCurrentPage] = useState<string>('home');
  const [mobileMenuOpen, setMobileMenuOpen] = useState<boolean>(false);
  const [step, setStep] = useState<number>(1);
  
  const [formData, setFormData] = useState<FormData>({
    situation: '',
    thought: ''
  });
  
  // ... các state cũ (step, formData, etc.)
  

  // // --- NEW: State cho Feedback (Demo Mode) ---
  // const [feedback, setFeedback] = useState({
  //   relevance: 0,   // Sát với situation
  //   suitability: 0, // Phù hợp với cá nhân
  //   realism: 0,     // Tính thực tế
  // });
  // const [isFeedbackSubmitted, setIsFeedbackSubmitted] = useState(false);

  // // Hàm xử lý chọn sao
  // const handleRate = (criteria: keyof typeof feedback, rating: number) => {
  //   setFeedback(prev => ({ ...prev, [criteria]: rating }));
  // };

  // // Helper render ngôi sao
  // const renderStars = (criteria: keyof typeof feedback) => {
  //   return (
  //     <div className="flex gap-1">
  //       {[1, 2, 3, 4, 5].map((star) => (
  //         <button
  //           key={star}
  //           onClick={() => handleRate(criteria, star)}
  //           className={`transition-all duration-200 focus:outline-none ${
  //             star <= feedback[criteria] 
  //               ? "text-yellow-400 fill-yellow-400 scale-110" 
  //               : "text-gray-300 hover:text-yellow-200 hover:scale-105"
  //           }`}
  //           type="button"
  //         >
  //           <Star className="w-6 h-6" />
  //         </button>
  //       ))}
  //     </div>
  //   );
  // };

  // --- NEW: State cho Feedback (Likert Scale) ---
  // Định nghĩa kiểu dữ liệu cho Feedback mới
  interface FeedbackState {
    belief: number | null;      // Tin tưởng vào reframe
    helpfulness: number | null; // Giúp ích cho cảm xúc
    recall: number | null;      // Khả năng nhớ lại
    learning: number | null;    // Bài học rút ra
  }

  const [feedback, setFeedback] = useState<FeedbackState>({
    belief: null,
    helpfulness: null,
    recall: null,
    learning: null
  });

  const [isFeedbackSubmitted, setIsFeedbackSubmitted] = useState(false);

  // Các lựa chọn trả lời (Likert Scale)
  const LIKERT_OPTIONS = [
    { value: 4, label: "Strongly Agree" },
    { value: 3, label: "Somewhat Agree" },
    { value: 2, label: "Somewhat Disagree" },
    { value: 1, label: "Strongly Disagree" }
  ];

  // Helper xử lý chọn đáp án
  const handleFeedbackChange = (question: keyof FeedbackState, value: number) => {
    setFeedback(prev => ({ ...prev, [question]: value }));
  };

  

  const [sessionId, setSessionId] = useState<string | null>(null);
  const [distortionResult, setDistortionResult] = useState<DistortionResult | null>(null);
  const [analysis, setAnalysis] = useState<AnalysisResult | null>(null);
  const [candidates, setCandidates] = useState<Candidate[]>([]);
  const [selectedReframe, setSelectedReframe] = useState<number | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const initSession = async () => {
      try {
        const response = await fetch(`${API_BASE_URL}/session/init`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' }
        });
        const data = await response.json();
        setSessionId(data.session_id);
      } catch (err) {
        console.error('Session init failed:', err);
        setSessionId('demo-session-' + Date.now());
      }
    };
    initSession();
  }, []);

  // --- API Functions ---
  const detectDistortion = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch(`${API_BASE_URL}/detect`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: sessionId,
          situation: formData.situation,
          thought: formData.thought
        })
      });
      if (!response.ok) throw new Error('Detection failed');
      const data = await response.json();
      setDistortionResult(data);
      setStep(2);
    } catch (err) {
      setError('Failed to detect distortions. Please try again.');
      console.error(err);
    }
    setLoading(false);
  };

  const analyzeThought = async () => {
    if (!distortionResult) return;
    
    setLoading(true);
    setError(null);
    try {
      const response = await fetch(`${API_BASE_URL}/analyze`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: sessionId,
          situation: formData.situation,
          thought: formData.thought,
          distortions: distortionResult.distortion_types
        })
      });
      
      if (!response.ok) throw new Error('Analysis failed');
      
      const data = await response.json();
      setAnalysis(data);
      setStep(3);
    } catch (err) {
      setError('Failed to analyze thought. Please try again.');
      console.error(err);
    }
    setLoading(false);
  };

  // ... các state cũ
  interface ReframeIteration {
    reframe: string;
    iteration: number;
  }

  const [reframeHistory, setReframeHistory] = useState<ReframeIteration[]>([]);
  const [activeHistoryIndex, setActiveHistoryIndex] = useState<number>(0); // Trỏ tới phiên bản đang xem

  const [selectedTherapies, setSelectedTherapies] = useState<string[]>([]);
  const [aiFeedback, setAiFeedback] = useState<string | null>(null);
  const [aiFeedback_summ, setAiFeedback_summ] = useState<string | null>(null);
  const [showExample, setShowExample] = useState(false);
  const [improveCount, setImproveCount] = useState<number>(0);
  const [isImproving, setIsImproving] = useState<boolean>(false);

  // Thêm useEffect này để khi có kết quả phân tích (Step 3), 
  // ta tự động điền các liệu pháp AI gợi ý vào danh sách chọn.
  useEffect(() => {
    if (analysis && analysis.recommended_therapies) {
      setSelectedTherapies(analysis.recommended_therapies);
    }
  }, [analysis]);

  const fillExample = () => {
    setFormData({
      ...formData,
      situation: "I sent a message to my friend 3 hours ago and saw they were online, but they haven't replied yet.",
      thought: "They are ignoring me because they find me annoying. I must have said something wrong and now they hate me."
    });
    setShowExample(false);
  };

  // Hàm xử lý chọn/bỏ chọn liệu pháp
  const toggleTherapy = (therapyKey: string) => {
    setSelectedTherapies(prev => {
      if (prev.includes(therapyKey)) {
        // Nếu đã có thì bỏ đi (nhưng cảnh báo hoặc chặn nếu muốn giữ ít nhất 1 cái)
        return prev.filter(t => t !== therapyKey);
      } else {
        // Nếu chưa có thì thêm vào
        return [...prev, therapyKey];
      }
    });
  };
  // const generateCandidates = async () => {
  //   if (!analysis) return;

  //   setLoading(true);
  //   setError(null);
  //   try {
  //     const response = await fetch(`${API_BASE_URL}/reframe`, {
  //       method: 'POST',
  //       headers: { 'Content-Type': 'application/json' },
  //       body: JSON.stringify({
  //         session_id: sessionId,
  //         situation: formData.situation,
  //         thought: formData.thought,
  //         recommended_therapies: analysis.recommended_therapies
  //       })
  //     });
      
  //     if (!response.ok) throw new Error('Generation failed');
      
  //     const data = await response.json();
  //     setCandidates(data.candidates);
  //     setStep(4);
  //   } catch (err) {
  //     setError('Failed to generate reframes. Please try again.');
  //     console.error(err);
  //   }
  //   setLoading(false);
  // };

  // Khởi tạo lịch sử khi vừa bước vào Step 5
  // useEffect(() => {
  //   if (step === 5 && selectedReframe !== null && candidates[selectedReframe]) {
  //     const initialReframe: ReframeIteration = {
  //       reframe: candidates[selectedReframe].reframe,
  //       iteration: 0
  //     };
  //     setReframeHistory([initialReframe]);
  //     setActiveHistoryIndex(0);
  //     setImproveCount(0);
  //   }
  // }, [step, selectedReframe, candidates]);

  useEffect(() => {
    // 1. Khai báo một hàm async bên trong
    const initializeStep5 = async () => {
      // 2. Vẫn giữ nguyên điều kiện kiểm tra
      if (step === 5 && selectedReframe !== null && candidates[selectedReframe]) {
        
        try {
          // Bạn có thể bật một state loading ở đây nếu cần (ví dụ: setIsImproving(true))

          // 3. Thực hiện gọi API
          const response = await fetch(`${API_BASE_URL}/instruction_feedback`, {
            method: 'POST', // Hoặc GET tùy thiết kế backend của bạn
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              session_id: sessionId, // Gửi kèm session_id nếu cần
              situation: formData.situation,
              thought: formData.thought,
              current_reframe: candidates[selectedReframe].reframe,
            })
          });

          if (!response.ok) {
            throw new Error('Network response was not ok');
          }

          const apiData = await response.json();

          // 4. Khởi tạo state với dữ liệu từ API kết hợp với dữ liệu local
          const initialReframe: ReframeIteration = {
            reframe: candidates[selectedReframe].reframe,
            iteration: 0
          };
          
          setReframeHistory([initialReframe]);
          const feedbackObject = JSON.parse(apiData.ai_feedback);
          setAiFeedback_summ(feedbackObject.summary);
          setAiFeedback(apiData.ai_feedback);
          setActiveHistoryIndex(0);
          setImproveCount(0);

        } catch (error) {
          console.error('Lỗi khi khởi tạo dữ liệu ở step 5:', error);
          
          // 5. Luôn có phương án dự phòng (fallback) nếu gọi API thất bại
          // Để UI không bị treo hoặc trắng trang
          const fallbackReframe: ReframeIteration = {
            reframe: candidates[selectedReframe].reframe,
            iteration: 0
          };
          setReframeHistory([fallbackReframe]);
          setActiveHistoryIndex(0);
          setImproveCount(0);
          
        } finally {
        }
      }
    };

    initializeStep5();

  }, [step, selectedReframe, candidates]); 

  const handleImprove = async () => {
    if (improveCount >= 5 || selectedReframe === null || reframeHistory.length === 0) return;
    
    setIsImproving(true);
    try {
      const currentReframeObj = reframeHistory[reframeHistory.length - 1]; 

      const response = await fetch(`${API_BASE_URL}/improve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: sessionId,
          situation: formData.situation,
          thought: formData.thought,
          current_reframe: currentReframeObj.reframe,
          history_response: reframeHistory,
          feedback: aiFeedback
        })
      });
      
      if (!response.ok) throw new Error('Improvement failed');
      
      const data = await response.json();

      const feedback_response = await fetch(`${API_BASE_URL}/instruction_feedback`, {
        method: 'POST', // Hoặc GET tùy thiết kế backend của bạn
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: sessionId, // Gửi kèm session_id nếu cần
          situation: formData.situation,
          thought: formData.thought,
          current_reframe: data.new_reframe,
        })
      });

      if (!response.ok) {
        throw new Error('Network response was not ok');
      }

      const feedbackData = await feedback_response.json();

      const feedbackObject = JSON.parse(feedbackData.ai_feedback);
      setAiFeedback_summ(feedbackObject.summary);
      setAiFeedback(feedbackData.ai_feedback);
      
      // Tạo object mới và đưa vào lịch sử
      const newIteration: ReframeIteration = {
        reframe: data.new_reframe,
        iteration: improveCount + 1
      };

      setReframeHistory(prev => [...prev, newIteration]);
      setImproveCount(prev => prev + 1);
      setActiveHistoryIndex(improveCount + 1); // Tự động chuyển view sang tab mới nhất 
      
      // Reset form đánh giá Likert
      setIsFeedbackSubmitted(false);
      setFeedback({ belief: null, helpfulness: null, recall: null, learning: null });
      
    } catch (err) {
      console.error('Failed to improve reframe:', err);
    } finally {
      setIsImproving(false);
    }
  };

  const generateCandidates = async () => {
    // Kiểm tra selectedTherapies thay vì analysis
    if (!selectedTherapies.length) return; 

    setLoading(true);
    setError(null);
    try {
      const response = await fetch(`${API_BASE_URL}/reframe`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: sessionId,
          situation: formData.situation,
          thought: formData.thought,
          recommended_therapies: selectedTherapies
        })
      });
      
      if (!response.ok) throw new Error('Generation failed');
      
      const data = await response.json();
      setCandidates(data.candidates);
      setStep(4);
    } catch (err) {
      setError('Failed to generate reframes. Please try again.');
      console.error(err);
    }
    setLoading(false);
  };

  const submitFeedback = async () => {
    // 1. Chuẩn bị payload dữ liệu
    const feedbackPayload = {
      session_id: sessionId,
      timestamp: new Date().toISOString(),
      input: {
        situation: formData.situation,
        thought: formData.thought,
      },
      output: {
        therapy_type: candidates[selectedReframe!]?.therapy,
        reframe: candidates[selectedReframe!]?.reframe,
      },
      ratings: feedback // { relevance, suitability, realism }
    };

    try {
      // 2. Gửi về Backend
      const response = await fetch(`${API_BASE_URL}/feedback`, { // API endpoint mới
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(feedbackPayload)
      });

      if (!response.ok) throw new Error('Failed to save feedback');

      // 3. Cập nhật UI
      console.log("✅ Feedback saved to server");
      setIsFeedbackSubmitted(true);
    } catch (err) {
      console.error("❌ Error saving feedback:", err);
      // Có thể hiển thị thông báo lỗi nhẹ ở đây nếu cần
      alert("Could not save feedback. Please check your connection.");
    }
  };

  const saveSelection = async () => {
    if (selectedReframe === null) return;
    
    try {
      await fetch(`${API_BASE_URL}/save`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: sessionId,
          selected_reframe: candidates[selectedReframe],
          original_thought: formData.thought
        })
      });
      setStep(5);
    } catch (err) {
      console.error('Failed to save selection:', err);
      setStep(5); 
    }
  };
  
  // const reset = () => {
  //   // 1. Reset các luồng chính
  //   setStep(1);
  //   setFormData({ situation: '', thought: '' });
    
  //   // 2. Xóa kết quả phân tích cũ
  //   setDistortionResult(null);
  //   setAnalysis(null);
  //   setCandidates([]);
  //   setSelectedReframe(null);
  //   setError(null);

  //   // 3. Reset danh sách liệu pháp đã chọn (QUAN TRỌNG: để lần sau AI tự gợi ý lại từ đầu)
  //   setSelectedTherapies([]);

  //   // 4. Reset Feedback về null (trạng thái chưa chọn)
  //   setFeedback({
  //     belief: null,
  //     helpfulness: null,
  //     recall: null,
  //     learning: null
  //   });
  //   setIsFeedbackSubmitted(false);
  // };
  const reset = () => {
    setStep(1);
    setFormData({ situation: '', thought: '' });
    setDistortionResult(null);
    setAnalysis(null);
    setCandidates([]);
    setSelectedReframe(null);
    setError(null);
    setSelectedTherapies([]);
    setFeedback({ belief: null, helpfulness: null, recall: null, learning: null });
    setIsFeedbackSubmitted(false);
    
    // Clear state improve
    setImproveCount(0);
    setIsImproving(false);

    setReframeHistory([]);
    setActiveHistoryIndex(0);
    setAiFeedback(null);
  };


  const renderNavigation = () => (
    <nav className="bg-white/80 backdrop-blur-md fixed w-full top-0 z-50 shadow-sm">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-16">
          <div className="flex items-center">
            <Brain className="w-8 h-8 text-indigo-600 mr-2" />
            <span className="text-xl font-bold text-gray-900">MindReframe</span>
          </div>
          
          <div className="hidden md:flex space-x-8">
            <button onClick={() => setCurrentPage('home')} className="text-gray-700 hover:text-indigo-600 transition">
              Home
            </button>
            <button onClick={() => setCurrentPage('about')} className="text-gray-700 hover:text-indigo-600 transition">
              About
            </button>
            <button onClick={() => setCurrentPage('therapies')} className="text-gray-700 hover:text-indigo-600 transition">
              Therapies
            </button>
            <button onClick={() => setCurrentPage('app')} className="bg-indigo-600 text-white px-6 py-2 rounded-full hover:bg-indigo-700 transition">
              Get Started
            </button>
          </div>

          <button 
            className="md:hidden"
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          >
            {mobileMenuOpen ? <X /> : <Menu />}
          </button>
        </div>

        {mobileMenuOpen && (
          <div className="md:hidden pb-4">
            <button onClick={() => { setCurrentPage('home'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-gray-700">
              Home
            </button>
            <button onClick={() => { setCurrentPage('about'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-gray-700">
              About
            </button>
            <button onClick={() => { setCurrentPage('therapies'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-gray-700">
              Therapies
            </button>
            <button onClick={() => { setCurrentPage('app'); setMobileMenuOpen(false); }} className="block w-full text-left py-2 text-indigo-600 font-semibold">
              Get Started
            </button>
          </div>
        )}
      </div>
    </nav>
  );

  const renderHomePage = () => (
    <div className="pt-16">
      <section className="relative min-h-screen flex items-center bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50">
        <div className="absolute inset-0 overflow-hidden">
          <div className="absolute -top-1/2 -right-1/2 w-full h-full bg-gradient-to-br from-indigo-200/30 to-transparent rounded-full blur-3xl"></div>
          <div className="absolute -bottom-1/2 -left-1/2 w-full h-full bg-gradient-to-tr from-purple-200/30 to-transparent rounded-full blur-3xl"></div>
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20">
          <div className="grid md:grid-cols-2 gap-12 items-center">
            <div>
              <h1 className="text-5xl md:text-6xl font-bold text-gray-900 mb-6 leading-tight">
                Transform Your
                <span className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-purple-600"> Thoughts</span>
              </h1>
              <p className="text-xl text-gray-600 mb-8">
                Evidence-based cognitive reframing powered by AI and multiple therapeutic approaches. 
                Find the perspective that works for you.
              </p>
              <div className="flex flex-col sm:flex-row gap-4">
                <button 
                  onClick={() => setCurrentPage('app')}
                  className="bg-indigo-600 text-white px-8 py-4 rounded-full font-semibold hover:bg-indigo-700 transition shadow-lg hover:shadow-xl flex items-center justify-center"
                >
                  Start Your Journey
                  <ArrowRight className="ml-2 w-5 h-5" />
                </button>
                <button 
                  onClick={() => setCurrentPage('about')}
                  className="bg-white text-indigo-600 px-8 py-4 rounded-full font-semibold hover:bg-gray-50 transition shadow-lg flex items-center justify-center"
                >
                  Learn More
                </button>
              </div>
            </div>

            <div className="hidden md:block">
              <div className="relative">
                <div className="absolute inset-0 bg-gradient-to-r from-indigo-500 to-purple-500 rounded-3xl blur-2xl opacity-20"></div>
                <div className="relative bg-white rounded-3xl shadow-2xl p-8">
                  <div className="space-y-6">
                    <div className="flex items-center space-x-4">
                      <div className="bg-indigo-100 p-3 rounded-full">
                        <Brain className="w-6 h-6 text-indigo-600" />
                      </div>
                      <div className="space-y-2">
                        <div className="h-4 bg-gray-200 rounded w-32"></div>
                        <div className="h-3 bg-gray-100 rounded w-24"></div>
                      </div>
                    </div>
                    <div className="flex items-center space-x-4">
                      <div className="bg-purple-100 p-3 rounded-full">
                        <Sparkles className="w-6 h-6 text-purple-600" />
                      </div>
                      <div className="space-y-2">
                        <div className="h-4 bg-gray-200 rounded w-40"></div>
                        <div className="h-3 bg-gray-100 rounded w-28"></div>
                      </div>
                    </div>
                    <div className="flex items-center space-x-4">
                      <div className="bg-pink-100 p-3 rounded-full">
                        <Heart className="w-6 h-6 text-pink-600" />
                      </div>
                      <div className="space-y-2">
                        <div className="h-4 bg-gray-200 rounded w-36"></div>
                        <div className="h-3 bg-gray-100 rounded w-32"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">Why MindReframe?</h2>
            <p className="text-xl text-gray-600">Science-backed features designed for your well-being</p>
          </div>

          <div className="grid md:grid-cols-3 gap-8">
            <div className="bg-gradient-to-br from-indigo-50 to-indigo-100 p-8 rounded-2xl">
              <div className="bg-indigo-600 w-14 h-14 rounded-full flex items-center justify-center mb-6">
                <Shield className="w-7 h-7 text-white" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-3">Evidence-Based</h3>
              <p className="text-gray-600">
                Built on proven therapeutic frameworks including CBT, ACT, DBT, and 9 other modalities studied in clinical research.
              </p>
            </div>

            <div className="bg-gradient-to-br from-purple-50 to-purple-100 p-8 rounded-2xl">
              <div className="bg-purple-600 w-14 h-14 rounded-full flex items-center justify-center mb-6">
                <Users className="w-7 h-7 text-white" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-3">Personalized</h3>
              <p className="text-gray-600">
                Choose the therapeutic approach that resonates with you. Different perspectives for different people.
              </p>
            </div>

            <div className="bg-gradient-to-br from-pink-50 to-pink-100 p-8 rounded-2xl">
              <div className="bg-pink-600 w-14 h-14 rounded-full flex items-center justify-center mb-6">
                <Lightbulb className="w-7 h-7 text-white" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-3">AI-Powered</h3>
              <p className="text-gray-600">
                Advanced language models trained to provide empathetic, safe, and clinically appropriate reframes.
              </p>
            </div>
          </div>
        </div>
      </section>

      {/* How It Works */}
      <section className="py-20 bg-gradient-to-br from-gray-50 to-gray-100">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">How It Works</h2>
            <p className="text-xl text-gray-600">Your journey to healthier thinking in 5 simple steps</p>
          </div>

          <div className="grid md:grid-cols-5 gap-8">
            {[
              { icon: MessageCircle, title: 'Share', desc: 'Tell us your situation and thoughts' },
              { icon: Brain, title: 'Detect', desc: 'We identify cognitive distortions' },
              { icon: TrendingUp, title: 'Analyze', desc: 'Deep analysis of thought patterns' },
              { icon: Sparkles, title: 'Reframe', desc: 'Multiple therapeutic perspectives' },
              { icon: Heart, title: 'Choose', desc: 'Select what works for you' }
            ].map((item, idx) => (
              <div key={idx} className="text-center">
                <div className="bg-white w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg">
                  <item.icon className="w-10 h-10 text-indigo-600" />
                </div>
                <h3 className="font-bold text-gray-900 mb-2">{item.title}</h3>
                <p className="text-sm text-gray-600">{item.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA Section */}
      <section className="py-20 bg-gradient-to-r from-indigo-600 to-purple-600">
        <div className="max-w-4xl mx-auto text-center px-4 sm:px-6 lg:px-8">
          <h2 className="text-4xl font-bold text-white mb-6">Ready to Transform Your Thinking?</h2>
          <p className="text-xl text-indigo-100 mb-8">
            Join thousands who have discovered healthier perspectives through cognitive reframing
          </p>
          <button 
            onClick={() => setCurrentPage('app')}
            className="bg-white text-indigo-600 px-10 py-4 rounded-full font-bold text-lg hover:bg-gray-100 transition shadow-xl inline-flex items-center"
          >
            Start Free Today
            <ArrowRight className="ml-2 w-5 h-5" />
          </button>
        </div>
      </section>
    </div>
  );

  const renderAboutPage = () => (
    <div className="pt-24 pb-20 min-h-screen bg-gradient-to-br from-indigo-50 via-white to-purple-50">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <h1 className="text-5xl font-bold text-gray-900 mb-8">About MindReframe</h1>
        
        <div className="bg-white rounded-3xl shadow-xl p-8 mb-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">Our Mission</h2>
          <p className="text-gray-700 mb-4">
            MindReframe combines cutting-edge AI technology with evidence-based psychotherapy to make mental health 
            support accessible, personalized, and effective for everyone.
          </p>
          <p className="text-gray-700">
            We believe that mental well-being should be within reach for all, and that the right perspective 
            can make a profound difference in how we experience life's challenges.
          </p>
        </div>

        <div className="bg-white rounded-3xl shadow-xl p-8 mb-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">The Science Behind It</h2>
          <p className="text-gray-700 mb-4">
            Our platform is built on <strong>ReframeBench</strong>, a comprehensive benchmark evaluating large 
            language models across 12 distinct therapeutic modalities. This research ensures that our AI 
            provides clinically appropriate and safe cognitive reframes.
          </p>
          <p className="text-gray-700">
            We integrate principles from CBT, ACT, DBT, REBT, Schema Therapy, MBCT, CFT, Narrative Therapy, 
            SFBT, and Motivational Interviewing - giving you access to diverse therapeutic perspectives.
          </p>
        </div>

        <div className="bg-white rounded-3xl shadow-xl p-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">Important Note</h2>
          <p className="text-gray-700">
            MindReframe is designed as a self-help tool and educational resource. It is not a replacement 
            for professional mental health care. If you're experiencing severe distress, please reach out 
            to a qualified mental health professional.
          </p>
        </div>
      </div>
    </div>
  );

  const renderTherapiesPage = () => (
    <div className="pt-24 pb-20 min-h-screen bg-gradient-to-br from-purple-50 via-white to-pink-50">
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
        <h1 className="text-5xl font-bold text-gray-900 mb-4 text-center">Therapeutic Approaches</h1>
        <p className="text-xl text-gray-600 mb-12 text-center">
          Explore the diverse perspectives we offer
        </p>

        <div className="grid md:grid-cols-2 gap-6">
          {[
            { name: 'CBT', full: 'Cognitive Behavioral Therapy', color: 'indigo', desc: 'Challenge and change unhelpful thoughts through evidence and logic' },
            { name: 'ACT', full: 'Acceptance & Commitment Therapy', color: 'purple', desc: 'Accept thoughts and commit to value-driven actions' },
            { name: 'DBT', full: 'Dialectical Behavior Therapy', color: 'pink', desc: 'Balance acceptance with change through mindfulness' },
            { name: 'REBT', full: 'Rational Emotive Behavior Therapy', color: 'blue', desc: 'Dispute irrational beliefs with rational alternatives' },
            { name: 'MBCT', full: 'Mindfulness-Based Cognitive Therapy', color: 'green', desc: 'Combine mindfulness with cognitive techniques' },
            { name: 'CFT', full: 'Compassion-Focused Therapy', color: 'rose', desc: 'Cultivate self-compassion and kindness' },
            { name: 'Schema Therapy', full: 'Schema Therapy', color: 'violet', desc: 'Identify and heal deep-rooted patterns' },
            { name: 'Narrative', full: 'Narrative Therapy', color: 'amber', desc: 'Rewrite your story and externalize problems' },
            { name: 'SFBT', full: 'Solution-Focused Brief Therapy', color: 'cyan', desc: 'Focus on solutions rather than problems' },
            { name: 'MI', full: 'Motivational Interviewing', color: 'emerald', desc: 'Enhance motivation for positive change' }
          ].map((therapy, idx) => (
            <div key={idx} className={`bg-gradient-to-br from-${therapy.color}-50 to-${therapy.color}-100 p-6 rounded-2xl border-2 border-${therapy.color}-200`}>
              <h3 className="text-xl font-bold text-gray-900 mb-2">{therapy.name}</h3>
              <p className="text-sm text-gray-600 mb-3 font-medium">{therapy.full}</p>
              <p className="text-gray-700">{therapy.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const renderAppPage = () => (
    <div className="pt-20 pb-12 min-h-screen bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Progress Bar */}
        <div className="mb-8 bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6">
          <div className="flex items-center justify-between">
            {['Input', 'Detect', 'Analyze', 'Reframe', 'Select'].map((label, idx) => (
              <React.Fragment key={idx}>
                <div className="flex flex-col items-center">
                  <div className={`w-12 h-12 rounded-full flex items-center justify-center font-bold transition-all duration-300 ${
                    step > idx + 1 ? 'bg-green-500 text-white shadow-lg scale-110' : 
                    step === idx + 1 ? 'bg-indigo-600 text-white shadow-lg animate-pulse' : 
                    'bg-gray-200 text-gray-400'
                  }`}>
                    {step > idx + 1 ? <CheckCircle className="w-6 h-6" /> : idx + 1}
                  </div>
                  <span className="mt-2 text-xs font-medium text-gray-700">{label}</span>
                </div>
                {idx < 4 && <div className={`flex-1 h-1 mx-2 rounded ${step > idx + 1 ? 'bg-green-500' : 'bg-gray-200'}`}></div>}
              </React.Fragment>
            ))}
          </div>
        </div>

        {error && (
          <div className="mb-6 bg-red-50 border-2 border-red-200 rounded-xl p-4 flex items-center">
            <XCircle className="w-5 h-5 text-red-600 mr-2" />
            <p className="text-red-800">{error}</p>
          </div>
        )}

        {/* Step 1: Input */}
        {step === 1 && (
  <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
    <div className="flex items-center justify-between mb-6">
      <div className="flex items-center">
        <div className="bg-indigo-100 p-3 rounded-full mr-4">
          <MessageCircle className="w-6 h-6 text-indigo-600" />
        </div>
        <h2 className="text-3xl font-bold text-gray-900">Share Your Thoughts</h2>
      </div>
      
      {/* Nút bật/tắt ví dụ */}
      <button
        onClick={() => setShowExample(!showExample)}
        className="text-sm font-medium text-indigo-600 hover:text-indigo-800 flex items-center transition-colors"
      >
        <Lightbulb className="w-4 h-4 mr-1" />
        {showExample ? 'Hide Example' : 'See Example'}
      </button>
    </div>

    {/* Khu vực hiển thị Example */}
    {showExample && (
      <div className="mb-8 bg-blue-50 border border-blue-100 rounded-xl p-5 relative animate-fade-in">
        <button 
          onClick={() => setShowExample(false)}
          className="absolute top-2 right-2 text-gray-400 hover:text-gray-600"
        >
          <X className="w-4 h-4" />
        </button>
        <h3 className="text-sm font-bold text-blue-800 uppercase tracking-wide mb-3">Example Scenario</h3>
        <div className="grid md:grid-cols-2 gap-4">
          <div>
            <p className="text-xs font-semibold text-gray-500 mb-1">THE SITUATION (Facts only)</p>
            <p className="text-sm text-gray-700 bg-white p-3 rounded-lg border border-blue-100 italic">
              "I sent a message to my friend 3 hours ago and haven't received a reply yet."
            </p>
          </div>
          <div>
            <p className="text-xs font-semibold text-gray-500 mb-1">THE THOUGHT (Interpretation)</p>
            <p className="text-sm text-gray-700 bg-white p-3 rounded-lg border border-blue-100 italic">
              "They are ignoring me because they hate me. I always mess up relationships."
            </p>
          </div>
        </div>
        <button
          onClick={fillExample}
          className="mt-4 text-xs font-semibold text-blue-600 hover:text-blue-800 hover:underline"
        >
          Click to use this example
        </button>
      </div>
    )}
    
    <p className="text-gray-600 mb-8">
      Let's start by understanding what's on your mind. Be as honest and detailed as you'd like.
    </p>

    <div className="mb-6">
      <div className="flex justify-between items-baseline mb-3">
        <label className="block text-sm font-semibold text-gray-700">
          What's the situation?
        </label>
        <span className="text-xs text-gray-400 font-medium">Objective facts (Who, what, where)</span>
      </div>
      <textarea
        className="w-full p-4 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 focus:outline-none resize-none transition-all placeholder:text-gray-400"
        rows={3}
        placeholder="E.g., I made a mistake during my presentation..."
        value={formData.situation}
        onChange={(e) => setFormData({ ...formData, situation: e.target.value })}
        key="situation-input"
      />
    </div>

    <div className="mb-8">
      <div className="flex justify-between items-baseline mb-3">
        <label className="block text-sm font-semibold text-gray-700">
          What thoughts came to mind?
        </label>
        <span className="text-xs text-gray-400 font-medium">Your interpretation or feeling</span>
      </div>
      <textarea
        className="w-full p-4 border-2 border-gray-200 rounded-xl focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 focus:outline-none resize-none transition-all placeholder:text-gray-400"
        rows={3}
        placeholder="E.g., Everyone thinks I'm incompetent. I'll get fired..."
        value={formData.thought}
        onChange={(e) => setFormData({ ...formData, thought: e.target.value })}
        key="thought-input"
      />
    </div>

    <button
      onClick={detectDistortion}
      disabled={!formData.situation || !formData.thought || loading}
      className="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl transform hover:scale-[1.02]"
    >
      {loading ? (
        <>
          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
          Analyzing Your Thoughts...
        </>
      ) : (
        <>
          Begin Analysis
          <ChevronRight className="w-5 h-5 ml-2" />
        </>
      )}
    </button>
  </div>
)}

        {/* Step 2: Detection */}
        {step === 2 && distortionResult && (
          <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
            <div className="flex items-center mb-6">
              <div className={`${distortionResult.has_distortion ? 'bg-yellow-100' : 'bg-green-100'} p-3 rounded-full mr-4`}>
                {distortionResult.has_distortion ? (
                  <Brain className="w-6 h-6 text-yellow-600" />
                ) : (
                  <CheckCircle className="w-6 h-6 text-green-600" />
                )}
              </div>
              <h2 className="text-3xl font-bold text-gray-900">
                {distortionResult.has_distortion ? 'Distortion Detection' : 'Great News!'}
              </h2>
            </div>

            {distortionResult.has_distortion ? (
              <>
                {/* Distortion Detected - Original UI */}
                <div className="bg-gradient-to-r from-yellow-50 to-amber-50 border-2 border-yellow-300 rounded-xl p-6 mb-6">
                  <div className="flex items-start mb-4">
                    <XCircle className="w-8 h-8 text-yellow-600 mr-3 flex-shrink-0 mt-1" />
                    <div>
                      <h3 className="text-xl font-bold text-gray-900 mb-2">Cognitive Distortions Detected</h3>
                      <p className="text-gray-700">
                        We've identified some thinking patterns that may be affecting your perspective.
                      </p>
                    </div>
                  </div>

                  <div className="mb-4">
                    <p className="font-semibold text-gray-700 mb-3">Distortion Types:</p>
                    <div className="flex flex-wrap gap-2">
                      {distortionResult.distortion_types.map((type, idx) => (
                        <span key={idx} className="bg-yellow-200 text-yellow-900 px-4 py-2 rounded-full text-sm font-semibold">
                          {type}
                        </span>
                      ))}
                    </div>
                  </div>

                  <div className="bg-white/50 rounded-lg p-4">
                    <p className="text-sm text-gray-600 font-medium mb-1">Understanding:</p>
                    <p className="text-gray-800">{distortionResult.explanation}</p>
                  </div>
                </div>

                <button
                  onClick={analyzeThought}
                  disabled={loading}
                  className="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
                >
                  {loading ? (
                    <>
                      <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                      Deep Analysis in Progress...
                    </>
                  ) : (
                    <>
                      Continue to Deep Analysis
                      <ChevronRight className="w-5 h-5 ml-2" />
                    </>
                  )}
                </button>
              </>
            ) : (
              <>
                {/* No Distortion Detected - New UI */}
                <div className="bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-300 rounded-xl p-6 mb-6">
                  <div className="flex items-start mb-4">
                    <CheckCircle className="w-8 h-8 text-green-600 mr-3 flex-shrink-0 mt-1" />
                    <div>
                      <h3 className="text-xl font-bold text-gray-900 mb-2">Healthy Thinking Pattern</h3>
                      <p className="text-gray-700">
                        Your thought appears to be balanced and realistic. We didn't detect any cognitive distortions.
                      </p>
                    </div>
                  </div>

                  <div className="bg-white/50 rounded-lg p-4">
                    <p className="text-sm text-gray-600 font-medium mb-1">Analysis:</p>
                    <p className="text-gray-800">{distortionResult.explanation}</p>
                  </div>
                </div>

                <div className="bg-blue-50 border-2 border-blue-200 rounded-xl p-6 mb-6">
                  <div className="flex items-start">
                    <Lightbulb className="w-6 h-6 text-blue-600 mr-3 mt-1 flex-shrink-0" />
                    <div>
                      <h3 className="font-bold text-gray-900 mb-2">Keep It Up!</h3>
                      <p className="text-gray-700 text-sm">
                        Your thinking seems clear and grounded. This is a sign of good mental health. 
                        If you're still feeling distressed about the situation, consider whether the 
                        situation itself needs attention rather than your thoughts about it.
                      </p>
                    </div>
                  </div>
                </div>

                <div className="flex gap-4">
                  <button
                    onClick={() => setStep(1)}
                    className="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center"
                  >
                    <RotateCcw className="w-5 h-5 mr-2" />
                    Try Another Thought
                  </button>

                  <button
                    onClick={() => setCurrentPage('home')}
                    className="flex-1 bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
                  >
                    <CheckCircle className="w-5 h-5 mr-2" />
                    Back to Home
                  </button>
                </div>
              </>
            )}
          </div>
        )}

        {/* Step 3: Analysis */}
        {/* Step 3: Analysis */}
        {step === 3 && analysis && (
          <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
            <div className="flex items-center mb-6">
              <div className="bg-purple-100 p-3 rounded-full mr-4">
                <TrendingUp className="w-6 h-6 text-purple-600" />
              </div>
              <h2 className="text-3xl font-bold text-gray-900">Deep Analysis</h2>
            </div>

            {/* ... (Giữ nguyên phần hiển thị Emotional Impact, Beliefs, Triggers cũ) ... */}
            <div className="space-y-4 mb-8">
              {/* Code hiển thị Emotional Impact, Beliefs, Triggers giữ nguyên như cũ... */}
              <div className="bg-gradient-to-r from-blue-50 to-blue-100 border-l-4 border-blue-500 rounded-lg p-5">
                  {/* ... nội dung Emotional Impact ... */}
                  <div className="flex items-start">
                      <Heart className="w-5 h-5 text-blue-600 mr-3 mt-1 flex-shrink-0" />
                      <div>
                        <h3 className="font-bold text-gray-900 mb-2">Emotional Impact</h3>
                        <p className="text-gray-700">{analysis.emotional_impact}</p>
                      </div>
                    </div>
              </div>
              
              {/* ... Các block Underlying Beliefs và Triggers giữ nguyên ... */}
                <div className="bg-gradient-to-r from-purple-50 to-purple-100 border-l-4 border-purple-500 rounded-lg p-5">
                  {/* ... nội dung Beliefs ... */}
                    <div className="flex items-start">
                          <Lightbulb className="w-5 h-5 text-purple-600 mr-3 mt-1 flex-shrink-0" />
                          <div>
                            <h3 className="font-bold text-gray-900 mb-2">Underlying Beliefs</h3>
                            <ul className="space-y-1">
                              {analysis.underlying_beliefs.map((belief, idx) => (
                                <li key={idx} className="text-gray-700 flex items-start">
                                  <span className="text-purple-600 mr-2"></span>
                                  <span>{belief}</span>
                                </li>
                              ))}
                            </ul>
                          </div>
                        </div>
                </div>
                
                <div className="bg-gradient-to-r from-pink-50 to-pink-100 border-l-4 border-pink-500 rounded-lg p-5">
                    {/* ... nội dung Triggers ... */}
                    <div className="flex items-start">
                          <Clock className="w-5 h-5 text-pink-600 mr-3 mt-1 flex-shrink-0" />
                          <div>
                            <h3 className="font-bold text-gray-900 mb-3">Common Triggers</h3>
                            <div className="flex flex-wrap gap-2">
                              {analysis.triggers.map((trigger, idx) => (
                                <span key={idx} className="bg-pink-200 text-pink-900 px-3 py-1 rounded-full text-sm font-medium">
                                  {trigger}
                                </span>
                              ))}
                            </div>
                          </div>
                        </div>
                </div>
            </div>

            {/* --- NEW SECTION: CUSTOMIZE THERAPIES --- */}
            <div className="mb-8">
              <div className="flex items-center mb-4">
                <Sparkles className="w-5 h-5 text-indigo-600 mr-2" />
                <h3 className="text-xl font-bold text-gray-900">Select Perspectives</h3>
              </div>
              
              <p className="text-gray-600 text-sm mb-4">
                Based on your analysis, we've selected the best approaches (highlighted). 
                You can tap to add or remove other perspectives you'd like to explore.
              </p>

              {/* Grid lựa chọn liệu pháp */}
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                {Object.entries(THERAPY_FULL_NAMES).map(([key, fullName]) => {
                  const isSelected = selectedTherapies.includes(key);
                  const isRecommended = analysis.recommended_therapies.includes(key);

                  return (
                    <button
                      key={key}
                      onClick={() => toggleTherapy(key)}
                      className={`
                        relative p-3 rounded-xl border-2 text-left transition-all duration-200
                        ${isSelected 
                          ? 'border-indigo-500 bg-indigo-50 shadow-md' 
                          : 'border-gray-200 bg-white hover:border-indigo-200 hover:bg-gray-50 text-gray-400'
                        }
                      `}
                    >
                      {/* Badge "Recommended" nếu AI gợi ý */}
                      {isRecommended && (
                        <span className="absolute -top-2 -right-2 bg-green-100 text-green-700 text-[10px] font-bold px-2 py-0.5 rounded-full border border-green-200 shadow-sm">
                          Recommended
                        </span>
                      )}

                      <div className="flex items-center justify-between mb-1">
                        <span className={`font-bold text-sm ${isSelected ? 'text-indigo-900' : 'text-gray-500'}`}>
                          {key}
                        </span>
                        {isSelected && <CheckCircle className="w-4 h-4 text-indigo-600" />}
                      </div>
                      <p className={`text-[10px] leading-tight line-clamp-2 ${isSelected ? 'text-indigo-700' : 'text-gray-400'}`}>
                        {fullName}
                      </p>
                    </button>
                  );
                })}
              </div>
              
              {/* Hiển thị lý do tại sao AI chọn liệu pháp (chỉ hiện cho những cái AI recommend) */}
              <div className="mt-4 bg-gray-50 rounded-lg p-4 border border-gray-200">
                <p className="text-xs font-bold text-gray-500 uppercase mb-2">Why these were recommended:</p>
                <div className="space-y-2">
                  {analysis.recommended_therapies.map((therapy) => (
                    selectedTherapies.includes(therapy) && ( // Chỉ hiện nếu user vẫn đang chọn nó
                      <div key={therapy} className="text-sm">
                        <span className="font-bold text-gray-800">{therapy}: </span>
                        <span className="text-gray-600">{analysis.therapy_rationales?.[therapy]}</span>
                      </div>
                    )
                  ))}
                </div>
              </div>
            </div>

            {/* Button Generate */}
            <button
              onClick={generateCandidates}
              disabled={loading || selectedTherapies.length === 0} // Disable nếu không chọn liệu pháp nào
              className="w-full bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
            >
              {loading ? (
                <>
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                  Generating {selectedTherapies.length} Perspectives...
                </>
              ) : (
                <>
                  Generate Reframes ({selectedTherapies.length} Selected)
                  <Sparkles className="w-5 h-5 ml-2" />
                </>
              )}
            </button>
          </div>
        )}

        {/* Step 4: Candidates */}
        {step === 4 && candidates.length > 0 && (
          <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 animate-fade-in">
            <div className="flex items-center mb-6">
              <div className="bg-green-100 p-3 rounded-full mr-4">
                <Sparkles className="w-6 h-6 text-green-600" />
              </div>
              <h2 className="text-3xl font-bold text-gray-900">Your Reframe Options</h2>
            </div>

            <p className="text-gray-600 mb-6">
              We've generated multiple perspectives based on different therapeutic approaches. 
              Choose the one that resonates most with you.
            </p>

            <div className="space-y-4 mb-8">
              {candidates.map((candidate, idx) => (
                <div
                  key={idx}
                  onClick={() => setSelectedReframe(idx)}
                  className={`p-6 border-2 rounded-xl cursor-pointer transition-all duration-300 transform hover:scale-102 ${
                    selectedReframe === idx
                      ? 'border-indigo-500 bg-gradient-to-r from-indigo-50 to-purple-50 shadow-lg'
                      : 'border-gray-200 hover:border-indigo-300 bg-white hover:shadow-md'
                  }`}
                >
                  <div className="flex items-center justify-between mb-4">
                    <span className="bg-indigo-600 text-white px-4 py-2 rounded-full text-sm font-bold">
                      {candidate.therapy}
                    </span>
                    {selectedReframe === idx && (
                      <div className="flex items-center text-indigo-600">
                        <ThumbsUp className="w-5 h-5 mr-2" />
                        <span className="font-semibold">Selected</span>
                      </div>
                    )}
                  </div>

                  <p className="text-gray-900 font-medium text-lg mb-4 leading-relaxed">
                    "{candidate.reframe}"
                  </p>

                  <div className="bg-white/50 rounded-lg p-4 mb-4">
                    <p className="text-sm text-gray-600 font-semibold mb-1">Why this works:</p>
                    <p className="text-gray-700 text-sm">{candidate.rationale}</p>
                  </div>

                  {candidate.evaluation && (
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 pt-4 border-t border-gray-200">
                      {Object.entries(candidate.evaluation).map(([key, value]) => (
                        <div key={key} className="text-center">
                          <p className="text-xs text-gray-500 uppercase font-semibold mb-1">{key}</p>
                          <div className="flex items-center justify-center">
                            {[...Array(5)].map((_, i) => (
                              <Award
                                key={i}
                                className={`w-4 h-4 ${
                                  i < value ? 'text-yellow-500 fill-yellow-500' : 'text-gray-300'
                                }`}
                              />
                            ))}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>

            <div className="flex gap-4">
              <button
                onClick={reset}
                className="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center"
              >
                <RotateCcw className="w-5 h-5 mr-2" />
                Start Over
              </button>

              <button
                onClick={saveSelection}
                disabled={selectedReframe === null}
                className="flex-1 bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 disabled:from-gray-400 disabled:to-gray-400 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
              >
                Confirm Choice
                <CheckCircle className="w-5 h-5 ml-2" />
              </button>
            </div>
          </div>
        )}

        {/* Step 5: Success */}
{step === 5 && selectedReframe !== null && candidates[selectedReframe] && (
  <div className="bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-8 text-center animate-fade-in max-w-2xl mx-auto">
    <div className="inline-block p-4 bg-green-100 rounded-full mb-6">
      <CheckCircle className="w-20 h-20 text-green-600" />
    </div>

    <h2 className="text-4xl font-bold text-gray-900 mb-4">Congratulations!</h2>
    <p className="text-xl text-gray-600 mb-8">
      You've taken an important step toward healthier thinking
    </p>

    {/* Reframe Result Card */}
    {reframeHistory.length > 0 && (
      <div className="bg-gradient-to-r from-indigo-50 via-purple-50 to-pink-50 rounded-2xl p-8 mb-8 text-left relative transition-all duration-500">
        
        {/* --- NEW: History Navigation Tabs --- */}
        {reframeHistory.length > 1 && (
          <div className="mb-6 flex space-x-2 overflow-x-auto pb-2 scrollbar-hide">
            {reframeHistory.map((_, idx) => (
              <button
                key={idx}
                onClick={() => setActiveHistoryIndex(idx)}
                className={`px-4 py-1.5 text-xs font-bold rounded-full transition-all whitespace-nowrap ${
                  activeHistoryIndex === idx
                    ? 'bg-indigo-600 text-white shadow-md'
                    : 'bg-white text-indigo-600 border border-indigo-200 hover:bg-indigo-50'
                }`}
              >
                {idx === 0 ? 'Original' : `Version ${idx + 1}`}
              </button>
            ))}
          </div>
        )}

        <div className="mb-6">
          <p className="text-sm text-gray-500 uppercase font-semibold mb-2">Situation</p>
          <p className="text-gray-800 italic">"{formData.situation}"</p>
        </div>
        <div className="mb-6">
          <p className="text-sm text-gray-500 uppercase font-semibold mb-2">Original Thought</p>
          <p className="text-gray-800 italic">"{formData.thought}"</p>
        </div>

        <div className="flex items-center justify-center my-6">
          <ArrowRight className="w-8 h-8 text-indigo-600" />
        </div>

        <div>
          <p className="text-sm text-gray-500 uppercase font-semibold mb-2 flex justify-between items-center">
            <span>Your New Perspective ({candidates[selectedReframe].therapy})</span>
            {/* Hiển thị version đang xem ở góc phải */}
            <span className="text-xs bg-purple-200 text-purple-800 px-2 py-0.5 rounded-md">
              {activeHistoryIndex === 0 ? 'Original' : `Iteration ${activeHistoryIndex}`}
            </span>
          </p>
          <p className="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-purple-600 min-h-[3rem]">
            "{reframeHistory[activeHistoryIndex].reframe}"
          </p>
        </div>

        {/* LLM Insight & Improve Button */}
        <div className="mt-8 pt-6 border-t border-purple-200/50">
          <div className="flex items-start mb-6 bg-white/60 p-4 rounded-xl">
            <Brain className="w-5 h-5 text-purple-600 mr-3 mt-0.5 flex-shrink-0" />
            <div>
              <p className="text-sm font-bold text-gray-800 mb-1">AI Feedback</p>
              <p className="text-sm text-gray-700 leading-relaxed">
                {aiFeedback_summ}
              </p>
            </div>
          </div>

          <div className="flex justify-end">
            <button
              onClick={handleImprove}
              //  hiệu hoá nút nếu đang loading, đã tới giới hạn 5 lần, hoặc đang xem lại lịch sử  (chỉ cho phép improve từ bản mới nhất)
              disabled={isImproving || improveCount >= 5 || activeHistoryIndex !== reframeHistory.length - 1}
              className={`text-sm font-bold py-2.5 px-5 rounded-xl flex items-center transition-all shadow-sm
                ${(isImproving || improveCount >= 5 || activeHistoryIndex !== reframeHistory.length - 1)
                  ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                  : 'bg-white border-2 border-purple-200 text-purple-600 hover:bg-purple-50 hover:border-purple-400 hover:shadow-md'
                }`}
            >
              {isImproving ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-purple-600 mr-2"></div>
                  Refining...
                </>
              ) : activeHistoryIndex !== reframeHistory.length - 1 ? (
                <>
                  <RotateCcw className="w-4 h-4 mr-2" />
                  View Latest to Improve
                </>
              ) : (
                <>
                  <Sparkles className="w-4 h-4 mr-2" />
                  {improveCount >= 5 ? 'Max Refinements Reached' : `Improve Reframe (${improveCount}/5)`}
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    )}

    {/* --- NEW: FEEDBACK UI (Likert Scale) --- */}
    {!isFeedbackSubmitted ? (
      <div className="bg-white border border-gray-200 shadow-sm rounded-xl p-6 mb-8 text-left animate-fade-in transition-all">
        <div className="mb-6 border-b border-gray-100 pb-4">
          <h3 className="text-lg font-bold text-gray-800 flex items-center">
            <MessageCircle className="w-5 h-5 mr-2 text-indigo-600" />
            Evaluation
          </h3>
          <p className="text-sm text-gray-500 mt-1">
            How strongly do you agree with the following statements regarding your chosen perspective?
          </p>
        </div>
        
        <div className="space-y-8">
          {/* Question 1: Belief */}
          <div>
            <p className="text-gray-800 font-medium mb-3 text-sm">
              1. I genuinely believe in this new perspective.
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {LIKERT_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => handleFeedbackChange('belief', opt.value)}
                  className={`py-2 px-3 text-xs rounded-lg border transition-all duration-200 ${
                    feedback.belief === opt.value
                      ? 'bg-indigo-600 text-white border-indigo-600 shadow-md font-semibold'
                      : 'bg-white text-gray-600 border-gray-200 hover:border-indigo-300 hover:bg-indigo-50'
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Question 2: Helpfulness */}
          <div>
            <p className="text-gray-800 font-medium mb-3 text-sm">
              2. This perspective helps me reduce my distress.
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {LIKERT_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => handleFeedbackChange('helpfulness', opt.value)}
                  className={`py-2 px-3 text-xs rounded-lg border transition-all duration-200 ${
                    feedback.helpfulness === opt.value
                      ? 'bg-indigo-600 text-white border-indigo-600 shadow-md font-semibold'
                      : 'bg-white text-gray-600 border-gray-200 hover:border-indigo-300 hover:bg-indigo-50'
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Question 3: Memorability */}
          <div>
            <p className="text-gray-800 font-medium mb-3 text-sm">
              3. I will likely recall this perspective next time I feel this way.
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {LIKERT_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => handleFeedbackChange('recall', opt.value)}
                  className={`py-2 px-3 text-xs rounded-lg border transition-all duration-200 ${
                    feedback.recall === opt.value
                      ? 'bg-indigo-600 text-white border-indigo-600 shadow-md font-semibold'
                      : 'bg-white text-gray-600 border-gray-200 hover:border-indigo-300 hover:bg-indigo-50'
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Question 4: Learning */}
          <div>
            <p className="text-gray-800 font-medium mb-3 text-sm">
              4. This exercise improved my ability to cope with negative thoughts.
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {LIKERT_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => handleFeedbackChange('learning', opt.value)}
                  className={`py-2 px-3 text-xs rounded-lg border transition-all duration-200 ${
                    feedback.learning === opt.value
                      ? 'bg-indigo-600 text-white border-indigo-600 shadow-md font-semibold'
                      : 'bg-white text-gray-600 border-gray-200 hover:border-indigo-300 hover:bg-indigo-50'
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Nút Submit chỉ hiện khi đã trả lời hết (hoặc ít nhất 1 câu tùy bạn) */}
        <div className="mt-8 text-center animate-fade-in">
          <button 
            onClick={submitFeedback}
            disabled={!feedback.belief || !feedback.helpfulness || !feedback.recall || !feedback.learning}
            className="text-sm bg-indigo-50 text-indigo-600 hover:bg-indigo-100 disabled:opacity-50 disabled:cursor-not-allowed px-8 py-3 rounded-full font-bold transition-all shadow-sm hover:shadow-md"
          >
            Submit Evaluation
          </button>
        </div>
      </div>
    ) : (
      // UI sau khi đã submit (Cảm ơn)
      <div className="bg-green-50 border border-green-100 rounded-xl p-6 mb-8 flex flex-col items-center justify-center animate-fade-in">
        <div className="bg-green-100 p-3 rounded-full mb-3">
          <ThumbsUp className="w-8 h-8 text-green-600" />
        </div>
        <p className="text-green-800 font-bold text-lg">Thank You!</p>
        <p className="text-green-600 text-sm mt-1 text-center max-w-md">
          Your feedback is invaluable for improving our therapeutic models. 
          Keep practicing this reframe whenever you need it.
        </p>
      </div>
    )}
    {/* --- END FEEDBACK UI --- */}

    <div className="bg-blue-50 border-2 border-blue-200 rounded-xl p-6 mb-8 text-left">
      <div className="flex items-start">
        <Lightbulb className="w-6 h-6 text-blue-600 mr-3 mt-1 flex-shrink-0" />
        <div>
          <h3 className="font-bold text-gray-900 mb-2">Practice Makes Progress</h3>
          <p className="text-gray-700 text-sm">
            Try using this reframe when you notice similar thoughts. It may feel unnatural at first, 
            but with repetition, these healthier thinking patterns will become more automatic.
          </p>
        </div>
      </div>
    </div>

    <button
      onClick={reset}
      className="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-semibold py-4 px-6 rounded-xl transition-all duration-300 flex items-center justify-center shadow-lg hover:shadow-xl"
    >
      <RotateCcw className="w-5 h-5 mr-2" />
      Work on Another Thought
    </button>
  </div>
)}
      </div>
    </div>
  );

  return (
    <div className="min-h-screen">
      {renderNavigation()}
      {currentPage === 'home' && renderHomePage()}
      {currentPage === 'about' && renderAboutPage()}
      {currentPage === 'therapies' && renderTherapiesPage()}
      {currentPage === 'app' && renderAppPage()}

      <footer className="bg-gray-900 text-white py-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid md:grid-cols-3 gap-8 mb-8">
            <div>
              <div className="flex items-center mb-4">
                <Brain className="w-6 h-6 text-indigo-400 mr-2" />
                <span className="text-lg font-bold">MindReframe</span>
              </div>
              <p className="text-gray-400 text-sm">
                Evidence-based cognitive reframing powered by AI and clinical psychology.
              </p>
            </div>
            
            {/* <div> */}
              {/* <h3 className="font-bold mb-4">About & Contact</h3> */}
              {/* <ul className="space-y-2 text-sm text-gray-400"> */}
                {/* <li>Affiliation: Anonymous</li> */}
                {/* <li>Contact Email: alpha.utehy@gmail.com</li> */}
                {/* <li>Crisis Text Line: Text HOME to 741741</li> */}
              {/* </ul> */}
            {/* </div> */}

            <div>
              <h3 className="font-bold mb-4">Important</h3>
              <p className="text-sm text-gray-400">
                This tool is for educational and self-help purposes. 
                If you're in crisis, please seek professional help immediately.
              </p>
            </div>
          </div>

          <div className="border-t border-gray-800 pt-8 text-center text-sm text-gray-400">
            <p>&copy; 2026 MindReframe. Based on MindReframe research.</p>
          </div>
        </div>
      </footer>
    </div>
  );
};

export default CognitiveReframingPlatform;