File size: 86,311 Bytes
5f0282c
6dbbcff
481feb4
cfa14d5
b1b97d5
cfa14d5
3141ff1
cfa14d5
9395816
481feb4
 
 
8ef3e15
5802429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481feb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01c7609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dbbcff
 
 
 
 
 
 
 
81bf27c
 
 
 
 
 
e633ed0
81bf27c
 
 
 
 
 
e633ed0
 
 
 
 
 
81bf27c
 
 
 
 
 
 
 
 
 
5c33771
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a92a5
5c33771
 
 
 
 
e0a92a5
5c33771
 
 
 
 
 
81bf27c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a92a5
e633ed0
 
 
 
 
 
 
81bf27c
 
 
ff9dc95
 
 
 
 
 
cfdb4ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9dc95
8f61a74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9dc95
 
 
 
 
 
 
8f61a74
ff9dc95
 
 
8f61a74
 
 
 
 
 
 
 
 
ff9dc95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f61a74
ff9dc95
 
 
8f61a74
 
 
 
 
 
 
 
 
 
 
 
ff9dc95
 
 
f9dc30a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a92a5
9395816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a92a5
aa8ef98
 
e0a92a5
 
 
aa8ef98
 
 
 
 
 
9395816
 
 
 
 
 
 
aa8ef98
 
 
 
9395816
aa8ef98
9395816
 
 
 
 
 
 
 
 
 
 
01c7609
9395816
174de03
 
 
 
 
 
9395816
01c7609
174de03
9395816
 
 
 
 
 
 
 
 
 
 
 
 
 
2b736fa
9395816
 
 
 
 
 
 
 
 
 
 
 
 
3141ff1
9395816
 
 
 
 
 
 
 
 
 
 
481feb4
 
 
 
 
 
238b1d4
 
 
47f7514
81bf27c
481feb4
 
 
ab56967
481feb4
 
 
cfa14d5
 
 
481feb4
 
 
 
 
 
 
b7b7391
 
 
 
 
 
 
b31126c
cfa14d5
481feb4
5f0282c
 
 
 
 
 
 
 
 
 
238b1d4
 
5f0282c
 
 
 
 
 
 
 
238b1d4
 
5f0282c
 
 
 
 
238b1d4
5f0282c
 
 
238b1d4
5f0282c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3141ff1
5f0282c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9dc95
5f0282c
 
 
 
238b1d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
053e91a
238b1d4
 
 
5f0282c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3141ff1
5f0282c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b736fa
5f0282c
 
 
 
 
 
 
 
 
 
 
 
 
 
481feb4
 
 
0bfc226
481feb4
 
 
2d49242
e44cd00
481feb4
18ce9e9
8b7f392
8351b7d
fc3cbe4
b7b7391
bade0a1
b7b7391
69d2775
01c7609
98000c8
01c7609
 
 
 
 
 
 
 
44c9c99
 
 
 
 
01c7609
5802429
 
 
 
 
69d2775
b7b7391
 
69d2775
42fe7da
a8dd9de
65408e2
 
a8dd9de
 
0e31a80
a8dd9de
 
 
 
 
 
 
74aa195
 
a8dd9de
 
69d2775
 
 
 
 
 
481feb4
95e46fa
45aa399
b7b7391
481feb4
0bfc226
481feb4
e7b9195
0bfc226
e7b9195
 
 
 
 
 
 
 
 
 
 
 
481feb4
 
007304e
0bfc226
 
 
 
 
61dc592
481feb4
da88b57
b7b7391
da88b57
b7b7391
 
 
da88b57
481feb4
4f274b5
 
 
 
 
 
2d49242
4f274b5
65712bb
e3c34b3
65712bb
 
 
 
 
 
 
 
 
e3c34b3
4f274b5
 
481feb4
2d49242
481feb4
 
 
 
 
 
 
 
 
 
 
 
2d49242
e44cd00
481feb4
 
cfa14d5
481feb4
 
 
 
 
 
afabd06
81bf27c
481feb4
 
 
 
45aa399
 
 
acee8e2
9d84509
acee8e2
481feb4
cfa14d5
95e46fa
 
61dc592
 
 
 
cfa14d5
61dc592
 
 
 
33cd8ab
481feb4
61dc592
481feb4
69d2775
 
8351b7d
481feb4
95e46fa
481feb4
 
 
b41cbf5
 
 
 
 
 
 
 
 
 
481feb4
 
 
 
 
 
 
 
 
 
 
0596f65
 
 
 
 
 
 
 
 
 
 
e837790
 
 
 
 
 
 
 
 
 
0596f65
 
 
 
 
 
 
 
e837790
 
 
 
 
 
 
 
 
 
0596f65
e837790
 
 
 
 
 
 
0596f65
 
 
 
 
8195c94
481feb4
 
 
a0b6810
0596f65
 
 
6bfa6ea
d39ef07
6bfa6ea
a0b6810
 
481feb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
825dbe4
481feb4
053e91a
 
 
 
 
 
 
 
 
 
0596f65
 
 
 
 
 
 
 
2c6f767
0596f65
 
 
 
 
 
 
 
481feb4
0596f65
 
 
 
 
6a820ad
e837790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1c6ce0
0596f65
 
cfa14d5
85290f8
e837790
 
 
 
 
 
 
 
481feb4
0596f65
 
 
 
053e91a
 
0596f65
053e91a
 
 
 
 
 
 
 
 
 
04ac907
85290f8
e336498
d2a1df1
cfa14d5
e0a92a5
d1c6f54
 
d2a1df1
37c2f1b
d1c6f54
e0a92a5
 
 
 
 
 
 
 
 
e336498
e0a92a5
d1c6f54
e0a92a5
 
 
 
 
 
 
d1c6f54
 
cfa14d5
e336498
d2a1df1
cfa14d5
d2a1df1
cfa14d5
e336498
cfa14d5
d1c6f54
e336498
 
e837790
 
 
 
 
 
 
 
6b95b48
0596f65
 
 
 
 
 
7d80c59
 
 
 
 
 
6b95b48
2d49242
d39ef07
6b95b48
81bf27c
0596f65
 
 
27e3ae8
0596f65
 
 
8f61a74
 
 
0596f65
 
 
9d84509
 
 
 
 
 
 
 
 
 
 
7d80c59
 
 
 
 
 
 
 
 
 
04ac907
7d80c59
04ac907
7d80c59
 
0596f65
 
8f61a74
7d80c59
 
0596f65
 
 
81bf27c
481feb4
0596f65
cfa14d5
481feb4
2d49242
d39ef07
481feb4
 
 
 
 
 
 
81bf27c
481feb4
 
 
 
 
 
 
 
acee8e2
95e46fa
acee8e2
95e46fa
 
 
45aa399
 
95e46fa
481feb4
 
acee8e2
d39ef07
481feb4
bae955d
481feb4
 
 
 
 
bae955d
81bf27c
481feb4
 
 
 
 
39b53b1
 
 
 
 
acee8e2
 
 
 
39b53b1
 
 
acee8e2
481feb4
 
 
 
 
 
 
 
 
 
eb0cad8
b7b7391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a92a5
b7b7391
bade0a1
b7b7391
 
 
 
 
 
 
 
 
 
 
 
bade0a1
b7b7391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bade0a1
b7b7391
 
bade0a1
b7b7391
 
 
 
 
 
eb0cad8
 
5f0282c
e336498
 
 
e936155
cfa14d5
e336498
 
 
 
 
e936155
e336498
 
e936155
 
 
 
 
5f0282c
e936155
5f0282c
f827b32
 
 
 
 
cfa14d5
f827b32
 
 
 
cfa14d5
f827b32
 
 
 
 
 
 
 
 
 
 
 
 
cfa14d5
f827b32
 
 
 
 
 
 
 
 
 
 
 
 
5f0282c
 
 
 
 
f827b32
238b1d4
 
 
 
f5fac5b
 
42fe7da
f5fac5b
0bfc226
61dc592
 
 
481feb4
 
bade0a1
 
 
 
 
 
 
 
 
 
481feb4
 
8617819
b7b7391
 
 
 
 
cfa14d5
95e46fa
 
 
 
 
cfa14d5
8617819
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa14d5
6503956
b7b7391
6503956
 
 
 
 
 
007304e
 
61dc592
 
 
 
 
007304e
 
61dc592
007304e
 
 
 
 
0bfc226
61dc592
481feb4
 
 
bade0a1
 
481feb4
 
 
 
 
 
 
01c7609
cfa14d5
b7b7391
 
 
 
 
 
 
 
 
 
 
 
42fe7da
 
b7b7391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01c7609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7b7391
 
 
 
 
 
 
 
 
 
 
cfa14d5
b7b7391
 
 
 
 
 
 
 
 
 
cfa14d5
b7b7391
 
 
 
 
 
 
cfa14d5
 
b7b7391
 
d630f62
b7b7391
 
 
f3a13c5
42fe7da
f3a13c5
645dad3
b7b7391
42fe7da
02971b8
0e31a80
 
2b736fa
0e31a80
 
 
 
 
 
02971b8
 
ceea2c9
b7b7391
 
238b1d4
5f0282c
 
 
 
 
 
 
238b1d4
 
5f0282c
 
b7b7391
 
238b1d4
cfa14d5
b7b7391
 
 
 
 
 
 
 
 
cfa14d5
 
 
b7b7391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
e0a92a5
b7b7391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0a92a5
 
 
 
b7b7391
 
 
 
 
 
 
8b7f392
b7b7391
 
 
 
 
 
 
 
 
5802429
b7b7391
2d49242
b7b7391
 
8351b7d
 
 
 
 
 
 
 
 
 
 
b7b7391
 
 
 
5015c4f
e0a92a5
5015c4f
b7b7391
 
 
 
2d49242
5015c4f
b7b7391
5015c4f
2d49242
4f274b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5015c4f
8b7f392
e0a92a5
481feb4
b7b7391
cfa14d5
01c7609
481feb4
 
7db0d3e
da8d860
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
import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import remarkMath from 'remark-math';
import remarkGfm from 'remark-gfm';
import rehypeKatex from 'rehype-katex';
import rehypeRaw from 'rehype-raw';
import 'katex/dist/katex.min.css';
import katex from 'katex';
import Login from './Login';
import './App.css';


const LOGIC_SAYINGS = [
  "Logic is disciplined honesty",
  "Logic tames intuition",
  "Logic survives scrutiny",
  "Logic resists wishful thinking",
  "Logic clarifies chaos",
  "Logic enforces consistency",
  "Logic demands consequences",
  "Logic hates contradiction",
  "Logic respects structure",
  "Logic questions assumptions",
  "Logic over loud opinions",
  "Logic scales beyond intuition",
  "Logic is structured doubt",
  "Logic follows necessity",
  "Logic earns trust",
  "Logic trims nonsense",
  "Logic values implication",
  "Logic prevents self-deception",
  "Logic is careful thinking",
  "Logic disciplines belief",
  "Logic outlives emotion",
  "Logic defines fairness",
  "Logic reveals errors",
  "Logic needs no applause",
  "Logic is patient clarity",
  "Logic refuses shortcuts",
  "Logic enforces coherence",
  "Logic invites verification",
  "Logic keeps promises",
  "Logic respects evidence",
  "Logic cuts cleanly",
  "Logic exposes contradictions",
  "Logic is structured reasoning",
  "Logic defeats ambiguity",
  "Logic rejects special pleading",
  "Logic anchors truth",
  "Logic strengthens arguments",
  "Logic filters belief",
  "Logic withstands pressure",
  "Logic enables understanding",
  "Logic is mental hygiene",
  "Logic values consistency",
  "Logic guards intelligence",
  "Logic is intellectual integrity",
  "Logic reveals necessity",
  "Logic is consequence-aware",
  "Logic clarifies premises",
  "Logic enforces discipline",
  "Logic refines thought",
  "Logic avoids contradiction",
  "Logic resists manipulation",
  "Logic empowers truth",
  "Logic disciplines intuition",
  "Logic respects implication",
  "Logic is rigorous thinking",
  "Logic survives opposition",
  "Logic rejects ambiguity",
  "Logic is systematic clarity",
  "Logic curbs bias",
  "Logic anchors reasoning",
  "Logic exposes fallacies",
  "Logic enforces structure",
  "Logic is formal honesty",
  "Logic strengthens insight",
  "Logic trims assumptions",
  "Logic invites challenge",
  "Logic prefers coherence",
  "Logic defeats confusion",
  "Logic remains impartial",
  "Logic respects consequences",
  "Logic makes sense durable",
  "Logic tests belief",
  "Logic values precision",
  "Logic demands justification",
  "Logic refines arguments",
  "Logic guards truth",
  "Logic stabilizes thought",
  "Logic is disciplined skepticism",
  "Logic clarifies meaning",
  "Logic enforces necessity",
  "Logic rejects contradictions",
  "Logic sustains reasoning",
  "Logic keeps ideas honest",
  "Logic enforces fairness",
  "Logic structures understanding",
  "Logic prevents nonsense",
  "Logic respects reality",
  "Logic rejects inconsistency",
  "Logic sharpens clarity",
  "Logic enables precision",
  "Logic stabilizes belief",
  "Logic resists illusion",
  "Logic enforces truthfulness",
  "Logic exposes inconsistency",
  "Logic refines clarity",
  "Logic demands coherence",
  "Logic preserves meaning",
  "Logic strengthens truth",
  "Logic clarifies necessity",
  "Logic enforces rationality",
];

// Eye-health optimized warm syntax highlighting theme
const terminalTheme = {
  'code[class*="language-"]': {
    color: '#c9b8a3',
    fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
    fontSize: '0.9em',
    background: '#1a1614',
  },
  'pre[class*="language-"]': {
    color: '#c9b8a3',
    fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
    fontSize: '0.9em',
    background: '#1a1614',
    padding: '1rem',
    margin: '0.75rem 0',
    overflow: 'auto',
    border: '1px solid #3a342e',
    borderRadius: '6px',
  },
  comment: {
    color: '#6e5d4d',
    fontStyle: 'italic',
  },
  prolog: { color: '#6e5d4d' },
  doctype: { color: '#6e5d4d' },
  cdata: { color: '#6e5d4d' },
  punctuation: { color: '#a89784' },
  property: { color: '#c9b8a3' },
  tag: { color: '#d4a574' },
  boolean: { color: '#b89968' },
  number: { color: '#b89968' },
  constant: { color: '#c9b8a3' },
  symbol: { color: '#c9b8a3' },
  deleted: { color: '#d49999' },
  selector: { color: '#d4a574' },
  'attr-name': { color: '#d4a574' },
  string: { color: '#9d8264' },
  char: { color: '#9d8264' },
  builtin: { color: '#c9b8a3' },
  inserted: { color: '#9d8264' },
  operator: { color: '#a89784' },
  entity: { color: '#d4a574' },
  url: { color: '#8b7355' },
  '.language-css .token.string': { color: '#9d8264' },
  '.style .token.string': { color: '#9d8264' },
  variable: { color: '#c9b8a3' },
  atrule: { color: '#d4a574' },
  'attr-value': { color: '#9d8264' },
  function: { color: '#d4a574' },
  'class-name': { color: '#d4a574' },
  keyword: { color: '#b89968', fontWeight: 'bold' },
  regex: { color: '#9d8264' },
  important: { color: '#d4a574', fontWeight: 'bold' },
};

// Light syntax highlighting theme
const lightCodeTheme = {
  'code[class*="language-"]': {
    color: '#383a42',
    fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
    fontSize: '0.9em',
    background: '#f0f0f0',
  },
  'pre[class*="language-"]': {
    color: '#383a42',
    fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
    fontSize: '0.9em',
    background: '#f0f0f0',
    padding: '1rem',
    margin: '0.75rem 0',
    overflow: 'auto',
    border: '1px solid #dcdcdc',
    borderRadius: '6px',
  },
  comment: { color: '#a0a1a7', fontStyle: 'italic' },
  prolog: { color: '#a0a1a7' },
  doctype: { color: '#a0a1a7' },
  cdata: { color: '#a0a1a7' },
  punctuation: { color: '#383a42' },
  property: { color: '#4078f2' },
  tag: { color: '#e45649' },
  boolean: { color: '#986801' },
  number: { color: '#986801' },
  constant: { color: '#4078f2' },
  symbol: { color: '#4078f2' },
  deleted: { color: '#e45649' },
  selector: { color: '#50a14f' },
  'attr-name': { color: '#986801' },
  string: { color: '#50a14f' },
  char: { color: '#50a14f' },
  builtin: { color: '#0184bc' },
  inserted: { color: '#50a14f' },
  operator: { color: '#383a42' },
  entity: { color: '#986801' },
  url: { color: '#0184bc' },
  variable: { color: '#e45649' },
  atrule: { color: '#0184bc' },
  'attr-value': { color: '#50a14f' },
  function: { color: '#4078f2' },
  'class-name': { color: '#c18401' },
  keyword: { color: '#a626a4', fontWeight: 'bold' },
  regex: { color: '#50a14f' },
  important: { color: '#e45649', fontWeight: 'bold' },
};

// Context used by out-of-component code renderers to pick the right syntax theme
const CodeThemeContext = React.createContext<object>(terminalTheme);

const allowDataImageUrl = (url: string): string => {
  if (url.startsWith('data:image/')) {
    return url;
  }

  return defaultUrlTransform(url);
};

const splitStreamingContent = (content: string): { safe: string; tail: string } => {
  if (!content) {
    return { safe: '', tail: '' };
  }

  let inCodeFence = false;
  let codeFenceStartIndex = 0;
  let inInlineMath = false;
  let inDisplayMath = false;
  let mathStartIndex = 0;

  for (let i = 0; i < content.length; i += 1) {
    if (content.startsWith('```', i)) {
      if (!inCodeFence) {
        inCodeFence = true;
        codeFenceStartIndex = i;
      } else {
        inCodeFence = false;
      }
      i += 2;
      continue;
    }

    if (inCodeFence) {
      continue;
    }

    const char = content[i];

    // Detect \begin{env}...\end{env} for display math environments BEFORE the generic
    // escape-skip below (which would consume the 'b' in \begin and miss it).
    // If the environment is unclosed (still streaming), treat it as an unsafe tail.
    if (char === '\\' && !inDisplayMath && !inInlineMath && !inCodeFence &&
        content.startsWith('\\begin{', i)) {
      const endBrace = content.indexOf('}', i + 7);
      if (endBrace !== -1) {
        const envName = content.slice(i + 7, endBrace);
        const baseEnv = envName.replace(/\*$/, ''); // strip trailing * for align*, etc.
        const displayEnvNames = [
          'aligned', 'align', 'equation', 'gather', 'multline',
          'array', 'matrix', 'pmatrix', 'bmatrix', 'vmatrix', 'Vmatrix',
          'cases', 'split', 'eqnarray',
        ];
        if (displayEnvNames.includes(baseEnv)) {
          const endPattern = `\\end{${envName}}`;
          const endIdx = content.indexOf(endPattern, endBrace);
          if (endIdx === -1) {
            // \end{env} not yet received — keep as raw tail until it arrives
            return {
              safe: content.slice(0, i),
              tail: content.slice(i),
            };
          }
          // Complete block present — skip past \end{env} so the rest is scanned normally
          i = endIdx + endPattern.length - 1;
          continue;
        }
      }
    }

    if (char === '\\') {
      i += 1;
      continue;
    }

    if (!inInlineMath && content.startsWith('\\[', i)) {
      if (!inDisplayMath) {
        inDisplayMath = true;
        mathStartIndex = i;
      }
      i += 1;
      continue;
    }

    if (!inInlineMath && content.startsWith('\\]', i)) {
      if (inDisplayMath) {
        inDisplayMath = false;
      }
      i += 1;
      continue;
    }

    if (!inInlineMath && content.startsWith('$$', i)) {
      if (!inDisplayMath) {
        inDisplayMath = true;
        mathStartIndex = i;
      } else {
        inDisplayMath = false;
      }
      i += 1;
      continue;
    }

    if (inDisplayMath) {
      continue;
    }

    if (char === '$') {
      if (!inInlineMath) {
        inInlineMath = true;
        mathStartIndex = i;
      } else {
        inInlineMath = false;
      }
    }
  }

  if (inInlineMath || inDisplayMath) {
    return {
      safe: content.slice(0, mathStartIndex),
      tail: content.slice(mathStartIndex),
    };
  }

  // Treat an unclosed code fence as unsafe — show as raw tail until it closes.
  if (inCodeFence) {
    return {
      safe: content.slice(0, codeFenceStartIndex),
      tail: content.slice(codeFenceStartIndex),
    };
  }

  return { safe: content, tail: '' };
};

const normalizeUserLatex = (content: string): string => {
  if (!content) {
    return content;
  }

  let normalized = content;
  const trimmed = normalized.trim();

  // Support bare display-style square-bracket wrappers used by some users,
  // e.g.:
  // [y = (3x^2 - 2x + 1)e^x.]
  // or multi-line:
  // [
  // y = (3x^2 - 2x + 1)e^x.
  // ]
  // Avoid converting JSON-like arrays or matrix literals handled elsewhere.
  if (
    trimmed.startsWith('[') &&
    trimmed.endsWith(']') &&
    !/^\[\s*\[/.test(trimmed) &&
    /(?:=|\^|_|\\|[+\-*/]|\b(?:sin|cos|tan|log|ln|exp)\b)/.test(trimmed.slice(1, -1))
  ) {
    const inner = trimmed.slice(1, -1).trim();
    if (inner) {
      return `$$${inner}$$`;
    }
  }

  // Convert simple 2D array literals into LaTeX matrices, e.g. [[2,1],[1,2]].
  normalized = normalized.replace(
    /\[\s*\[[^[\]]+\](?:\s*,\s*\[[^[\]]+\])+\s*\]/g,
    (raw) => {
      try {
        const parsed = JSON.parse(raw);
        if (
          !Array.isArray(parsed) ||
          parsed.length === 0 ||
          !parsed.every((row) => Array.isArray(row) && row.length > 0)
        ) {
          return raw;
        }

        const width = (parsed[0] as any[]).length;
        if (!parsed.every((row) => (row as any[]).length === width)) {
          return raw; // not rectangular
        }

        if (
          !parsed.every((row) =>
            (row as any[]).every((cell) =>
              typeof cell === 'number' || typeof cell === 'string' || typeof cell === 'boolean'
            )
          )
        ) {
          return raw;
        }

        const body = parsed
          .map((row) => (row as any[]).map((cell) => String(cell)).join(' & '))
          .join(' \\\\ ');
        return `$$\\begin{bmatrix}${body}\\end{bmatrix}$$`;
      } catch {
        return raw;
      }
    }
  );

  // Auto-close dangling $$ display-math blocks so KaTeX can render.
  // Convert explicit LaTeX delimiters \( ... \) and \[ ... \].
  normalized = normalized.replace(/\\\(([\s\S]*?)\\\)/g, (_m, expr) => `$${expr.trim()}$`);
  normalized = normalized.replace(/\\\[([\s\S]*?)\\\]/g, (_m, expr) => `$$${expr.trim()}$$`);

  // Wrap common block environments if user forgot $$ delimiters.
  normalized = normalized.replace(
    /\\begin\{(aligned|align\*?|alignat\*?|alignedat\*?|equation\*?|gather\*?|multline\*?|array|smallmatrix|matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}[\s\S]*?\\end\{\1\}/g,
    (m) => `$$${m}$$`
  );

  // Generic fallback for any bare \begin{env}...\end{env} block not already wrapped.
  normalized = normalized.replace(
    /(^|[^\$])\\begin\{([A-Za-z*]+)\}[\s\S]*?\\end\{\2\}/g,
    (m, prefix) => {
      const body = String(m).slice(String(prefix).length);
      return `${prefix}$$${body}$$`;
    }
  );

  // Wrap bare parenthesized chunks that look like LaTeX, e.g. (\mathbb{R}) or (x_n).
  normalized = normalized.replace(
    /\(([^()\n]*(?:\\[A-Za-z]+|[A-Za-z0-9]+_[A-Za-z0-9]+|[A-Za-z0-9]+\^[A-Za-z0-9]+)[^()\n]*)\)/g,
    (_m, expr) => `$${expr.trim()}$`
  );

  // If any rule above introduced delimiters, stop here to avoid double-wrapping
  // in subsequent regex passes.
  if (normalized.includes('$')) {
    // Repair malformed "$$(...latex...)" into "$...latex...$" for user input.
    // This can appear from odd delimiter interactions in partially-normalized text.
    normalized = normalized.replace(
      /\$\$\((\\[A-Za-z][^)\n]*)\)/g,
      (_m, expr) => `$${expr.trim()}$`
    );

    // Repair malformed "$(...latex...)" into "$...latex...$".
    normalized = normalized.replace(
      /\$\((\\[A-Za-z][^)\n]*)\)/g,
      (_m, expr) => `$${expr.trim()}$`
    );

    const displayDelimiters = normalized.match(/\$\$/g);
    if (displayDelimiters && displayDelimiters.length % 2 === 1) {
      normalized = `${normalized}\n$$`;
    }
    return normalized;
  }

  // Wrap common inline commands if user forgot $ delimiters.
  normalized = normalized.replace(
    /\\(?:frac|dfrac|tfrac|binom|sqrt|sum|int|iint|iiint|oint|prod|lim|sup|inf|min|max|argmax|argmin|alpha|beta|gamma|delta|epsilon|varepsilon|theta|vartheta|lambda|pi|rho|sigma|mu|nu|omega|partial|nabla|cdot|times|leq|geq|neq|approx|sim|infty|forall|exists|in|notin|subset|subseteq|supset|supseteq|cup|cap|to|mapsto|left|right|sin|cos|tan|sec|csc|cot|log|ln|exp|mathbb|mathbf|mathcal|mathrm|operatorname|text|overline|underline|hat|bar|vec)(?:\s*\{[^{}]*\}){0,4}(?:\s*\^[^\s{}]+)?(?:\s*_[^\s{}]+)?/g,
    (m) => `$${m}$`
  );

  // Fallback: wrap broader bare LaTeX segments with at least one command token.
  normalized = normalized.replace(
    /(^|[\s(,:;])((?:[A-Za-z0-9{}()[\]^_+\-*/=|]+\s+){0,8}\\[A-Za-z]+(?:\*?)(?:\s*\{[^{}]*\}){0,4}(?:\s+[A-Za-z0-9{}()[\]^_+\-*/=|\\]+){0,8})(?=$|[\s),.;:!?])/g,
    (_m, prefix, expr) => `${prefix}$${String(expr).trim()}$`
  );

  // Catch bare superscript/subscript tokens like x_n, a^2, x_i^2.
  normalized = normalized.replace(
    /(^|[\s(,:;])([A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9{}]+|\^[A-Za-z0-9{}]+){1,2})(?=$|[\s),.;:!?])/g,
    (_m, prefix, expr) => `${prefix}$${expr}$`
  );

  return normalized;
};

const PlotImage: React.FC<{ src?: string; alt?: string }> = ({ src, alt, ...props }) => {
  const [currentSrc, setCurrentSrc] = useState<string | undefined>(src);
  const [fallbackSrc, setFallbackSrc] = useState<string | undefined>(undefined);

  useEffect(() => {
    if (!src) {
      setCurrentSrc(undefined);
      setFallbackSrc(undefined);
      return;
    }

    if (src.startsWith('data:image/')) {
      try {
        const [meta, data] = src.split(',', 2);
        const mimeMatch = meta.match(/^data:(image\/[^;]+);base64$/);

        if (mimeMatch && data) {
          const byteChars = atob(data);
          const byteNumbers = new Array(byteChars.length);
          for (let i = 0; i < byteChars.length; i += 1) {
            byteNumbers[i] = byteChars.charCodeAt(i);
          }

          const blob = new Blob([new Uint8Array(byteNumbers)], { type: mimeMatch[1] });
          const objectUrl = URL.createObjectURL(blob);

          setCurrentSrc(objectUrl);
          setFallbackSrc(src);

          return () => {
            URL.revokeObjectURL(objectUrl);
          };
        }
      } catch {
        setCurrentSrc(src);
        setFallbackSrc(undefined);
      }
    }

    setCurrentSrc(src);
    setFallbackSrc(undefined);
  }, [src]);

  if (!currentSrc) {
    return null;
  }

  return (
    <img
      src={currentSrc}
      alt={alt || 'Plot'}
      style={{ maxWidth: '100%', height: 'auto', margin: '1rem 0' }}
      onError={() => {
        if (fallbackSrc && fallbackSrc !== currentSrc) {
          setCurrentSrc(fallbackSrc);
        }
      }}
      {...props}
    />
  );
};

// ─── Per-block KaTeX rendering (memoized — never re-render once a math block completes) ───

const KatexDisplay = React.memo(function KatexDisplay({ math }: { math: string }) {
  const html = useMemo(() => {
    try {
      return katex.renderToString(math, { throwOnError: false, strict: false, displayMode: true });
    } catch {
      return `<span class="katex-error">${math.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</span>`;
    }
  }, [math]);
  return <div className="math math-display" dangerouslySetInnerHTML={{ __html: html }} />;
});

const KatexInline = React.memo(function KatexInline({ math }: { math: string }) {
  const html = useMemo(() => {
    try {
      return katex.renderToString(math, { throwOnError: false, strict: false });
    } catch {
      return `<span class="katex-error">${math.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</span>`;
    }
  }, [math]);
  return <span className="math math-inline" dangerouslySetInnerHTML={{ __html: html }} />;
});

type ContentSegment =
  | { type: 'markdown'; content: string }
  | { type: 'display'; content: string }
  | { type: 'inline'; content: string };

/** Split preprocessed markdown into interleaved text and completed-math segments. */
function segmentMath(content: string): ContentSegment[] {
  const segments: ContentSegment[] = [];
  // Display math env names — ordered so longer names (aligned, eqnarray*) come before shorter prefixes.
  const displayEnvNames = 'aligned|align\\*|align|equation\\*|equation|gather\\*|gather|multline\\*|multline|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\\*|eqnarray';
  // Match (in priority order):
  //   1. $$...$$ display math            → group 1 = math content
  //   2. \begin{env}..\end{env}          → group 2 = env name, group 3 = env body (pass full m[0] to KaTeX)
  //   3. $...$ inline math (no newlines) → group 4 = math content
  const mathRegex = new RegExp(
    '\\$\\$([\\s\\S]*?)\\$\\$(?!\\$)' +
    `|\\\\begin\\{(${displayEnvNames})\\}([\\s\\S]*?)\\\\end\\{\\2\\}` +
    '|\\$(?!\\$)((?:[^$\\\\\\n]|\\\\.)+?)\\$(?!\\$)',
    'g'
  );
  let lastIndex = 0;
  let m: RegExpExecArray | null;
  while ((m = mathRegex.exec(content)) !== null) {
    if (m.index > lastIndex) {
      segments.push({ type: 'markdown', content: content.slice(lastIndex, m.index) });
    }
    if (m[0].startsWith('$$')) {
      segments.push({ type: 'display', content: (m[1] ?? '').trim() });
    } else if (m[0].startsWith('\\begin{')) {
      // Bare \begin{env}...\end{env} not wrapped in $$: pass full expression to KaTeX
      segments.push({ type: 'display', content: m[0].trim() });
    } else {
      segments.push({ type: 'inline', content: (m[4] ?? '').trim() });
    }
    lastIndex = m.index + m[0].length;
  }
  if (lastIndex < content.length) {
    segments.push({ type: 'markdown', content: content.slice(lastIndex) });
  }
  return segments;
}

const mdOnlyComponents = {
  code({ className, children, ...props }: any) {
    const codeTheme = React.useContext(CodeThemeContext);
    const match = /language-(\w+)/.exec(className || '');
    const rawContent = String(children).replace(/\n$/, '');
    // If the code block contains a LaTeX display math environment, render as KaTeX.
    // This handles cases where the LLM wraps \begin{aligned} etc. in code fences.
    if (/\\begin\{(?:aligned|align\*?|equation\*?|gather\*?|multline\*?|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}/.test(rawContent)) {
      return <KatexDisplay math={rawContent} />;
    }
    return match ? (
      <SyntaxHighlighter style={codeTheme as any} language={match[1]} PreTag="div" {...props}>
        {rawContent}
      </SyntaxHighlighter>
    ) : (
      <code className={className} {...props}>{children}</code>
    );
  },
  img({ src, alt, ...props }: any) { return <PlotImage src={src} alt={alt} {...props} />; },
};

/**
 * Renders content as interleaved Markdown + per-block KaTeX.
 * Each completed math block renders once and is stable (memoized by content).
 * Only the trailing partial-text segment re-renders on each stream chunk.
 */
const SegmentedMarkdown = React.memo(function SegmentedMarkdown({ content }: { content: string }) {
  const segments = useMemo(() => segmentMath(content), [content]);
  return (
    <>
      {segments.map((seg, i) => {
        if (seg.type === 'display') {
          return <KatexDisplay key={`d-${i}-${seg.content.length}`} math={seg.content} />;
        }
        if (seg.type === 'inline') {
          return <KatexInline key={`i-${i}-${seg.content.length}`} math={seg.content} />;
        }
        return (
          <ReactMarkdown
            key={`m-${i}`}
            remarkPlugins={[remarkGfm]}
            rehypePlugins={[rehypeRaw]}
            urlTransform={allowDataImageUrl}
            components={mdOnlyComponents}
          >
            {seg.content}
          </ReactMarkdown>
        );
      })}
    </>
  );
});

interface Message {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: Date;
  toolCalls?: ToolCall[];
  thinkingContent?: string;   // V3 status/tool log shown in Thinking panel
  thinkingExpanded?: boolean; // Whether the Thinking panel is open
  reasoningContent?: string;  // DeepSeek-Reasoner reasoning trace
  reasoningExpanded?: boolean; // Whether the reasoning panel is open
  isStreaming?: boolean;
}

interface ToolCall {
  id?: string;
  name: string;
  input: string;
  output: string;
  error?: boolean;         // Tool execution failed
  isGenerating?: boolean;  // AI is writing the code
  isExecuting?: boolean;   // Code is running in sandbox
}

interface User {
  username: string;
  name: string;
}

interface ConversationItem {
  id: string;
  title: string;
  timestamp: Date;
  messages: Message[];
}

const GATEWAY_URL = import.meta.env.VITE_GATEWAY_URL || 'https://deepthoughtai-evo-gateway.hf.space';
console.log('App Gateway URL:', GATEWAY_URL); // Debug log

// ---------------------------------------------------------------------------
// MessageItem – memoized so keystroke-driven re-renders don't re-render every
// historical message. Only the specific message that changes re-renders.
// ---------------------------------------------------------------------------
interface MessageItemProps {
  message: Message;
  userName: string | undefined;
  onCopyMarkdown: (content: string, event: React.MouseEvent) => void;
  onCopyEverything: (message: Message, event: React.MouseEvent) => void;
  onToggleReasoning: (messageId: string, open: boolean) => void;
  onToggleThinking: (messageId: string, open: boolean) => void;
  showThinking?: boolean;
}

const MessageItem = React.memo(function MessageItem({
  message,
  userName,
  onCopyMarkdown,
  onCopyEverything,
  onToggleReasoning,
  onToggleThinking,
  showThinking = false,
}: MessageItemProps) {
  const codeTheme = React.useContext(CodeThemeContext);
  if (
    message.role === 'assistant' &&
    !message.content &&
    !message.thinkingContent &&
    !message.reasoningContent &&
    (!message.toolCalls || message.toolCalls.length === 0)
  ) {
    if (!showThinking) return null;
  }
  return (
    <div className={`message message-${message.role}`}>
      <div className="message-avatar">
        {message.role === 'user' ? (
          <div className="avatar avatar--user">{userName?.[0]?.toUpperCase() ?? 'U'}</div>
        ) : (
          <div className="avatar avatar--assistant">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>
            </svg>
          </div>
        )}
      </div>
      <div className="message-body">
        <div className="message-meta">
          <span className="message-role-label">
            {message.role === 'user' ? (userName ?? 'You') : 'EVO'}
          </span>
          <span className="message-time">{message.timestamp.toLocaleTimeString()}</span>
          {message.role === 'assistant' && (
            <div className="message-actions">
              <button
                className="action-btn"
                onClick={(e) => onCopyEverything(message, e)}
                title="Copy all (with tool outputs)"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                  <circle cx="11.5" cy="11.5" r="1.5" fill="currentColor"></circle>
                  <circle cx="16.5" cy="11.5" r="1.5" fill="currentColor"></circle>
                  <circle cx="11.5" cy="16.5" r="1.5" fill="currentColor"></circle>
                  <circle cx="16.5" cy="16.5" r="1.5" fill="currentColor"></circle>
                </svg>
              </button>
              <button
                className="action-btn"
                onClick={(e) => onCopyMarkdown(message.content, e)}
                title="Copy markdown"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                </svg>
              </button>
            </div>
          )}
        </div>
        {message.content && (
          <div className="message-content">
            {message.role === 'assistant' && message.isStreaming ? (
              (() => {
                const { safe, tail } = splitStreamingContent(message.content);
                return (
                  <>
                    {safe && <SegmentedMarkdown content={safe} />}
                    {tail && <div className="streaming-content">{tail}</div>}
                  </>
                );
              })()
            ) : (
              <ReactMarkdown
                remarkPlugins={[[remarkMath, { singleDollarTextMath: true }], remarkGfm]}
                rehypePlugins={[rehypeRaw, [rehypeKatex, { throwOnError: false, strict: false }]]}
                urlTransform={allowDataImageUrl}
                components={{
                  code({ className, children, ...props }: any) {
                    const match = /language-(\w+)/.exec(className || '');
                    const rawContent = String(children).replace(/\n$/, '');
                    if (/\\begin\{(?:aligned|align\*?|equation\*?|gather\*?|multline\*?|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}/.test(rawContent)) {
                      return <KatexDisplay math={rawContent} />;
                    }
                    return match ? (
                      <SyntaxHighlighter style={codeTheme as any} language={match[1]} PreTag="div" {...props}>
                        {rawContent}
                      </SyntaxHighlighter>
                    ) : (
                      <code className={className} {...props}>{children}</code>
                    );
                  },
                  img({ src, alt, ...props }: any) { return <PlotImage src={src} alt={alt} {...props} />; },
                }}
              >
                {message.role === 'user' ? normalizeUserLatex(message.content) : message.content}
              </ReactMarkdown>
            )}
          </div>
        )}
        {showThinking && !message.content && !message.reasoningContent && !message.thinkingContent && (!message.toolCalls || message.toolCalls.length === 0) && (
          <div className="typing-dots thinking-inline">
            <span></span><span></span><span></span>
            <em className="status-message">Thinking...</em>
          </div>
        )}
        {message.thinkingContent && (
          <details
            className={`reasoning-trace thinking-trace${message.isStreaming ? ' reasoning-streaming' : ''}`}
            open={message.thinkingExpanded}
            onToggle={(e) => {
              const open = (e.currentTarget as HTMLDetailsElement).open;
              onToggleThinking(message.id, open);
            }}
          >
            <summary className="reasoning-header">
              <span>Thinking</span>
              {message.isStreaming && (
                <span className="reasoning-live-indicator">
                  <span className="reasoning-live-dot" />
                  <span className="reasoning-live-dot" />
                  <span className="reasoning-live-dot" />
                </span>
              )}
            </summary>
            <div
              className="reasoning-content thinking-log"
            >
              {(message.thinkingContent || '').replace(/\n{3,}/g, '\n\n')}
            </div>
          </details>
        )}
        {message.reasoningContent && (
          <details
            className={`reasoning-trace${message.isStreaming ? ' reasoning-streaming' : ''}`}
            open={message.reasoningExpanded}
            onToggle={(e) => {
              const open = (e.currentTarget as HTMLDetailsElement).open;
              onToggleReasoning(message.id, open);
            }}
          >
            <summary className="reasoning-header">
              <span className="reasoning-icon"></span>
              <span>Reasoning</span>
              {message.isStreaming && (
                <span className="reasoning-live-indicator">
                  <span className="reasoning-live-dot" />
                  <span className="reasoning-live-dot" />
                  <span className="reasoning-live-dot" />
                </span>
              )}
            </summary>
            <div
              className="reasoning-content"
            >
              {message.reasoningContent}
            </div>
          </details>
        )}
        {message.toolCalls && message.toolCalls.length > 0 && (
          <div className="tool-calls">
            {message.toolCalls.map((tool, idx) => (
              <details key={idx} className="tool-call">
                <summary className="tool-call-header">
                  <span className="tool-name">{tool.name.replace(/_exec$/, '').replace(/_/g, ' ')}</span>
                  {tool.isGenerating && (
                    <span className="tool-status generating">
                      <span className="dot"></span><span className="dot"></span><span className="dot"></span>
                      <span className="status-text">Generating...</span>
                    </span>
                  )}
                  {tool.isExecuting && (
                    <span className="tool-status executing">
                      <span className="dot"></span><span className="dot"></span><span className="dot"></span>
                      <span className="status-text">Executing...</span>
                    </span>
                  )}
                  {tool.output && !tool.isGenerating && !tool.isExecuting && (
                    tool.error ? <span className="crossmark">✗</span> : <span className="checkmark">✓</span>
                  )}
                </summary>
                <div className="tool-call-content">
                  <details className="tool-section">
                    <summary className="tool-section-label">Input:</summary>
                    <pre className="tool-code tool-input-scroll">{tool.input}</pre>
                  </details>
                  {tool.output && (
                    <div className="tool-section">
                      <div className="tool-section-label">Output:</div>
                      <div className="tool-output">
                        <ReactMarkdown
                          remarkPlugins={[[remarkMath, { singleDollarTextMath: true }], remarkGfm]}
                          rehypePlugins={[rehypeRaw, [rehypeKatex, { throwOnError: false, strict: false }]]}
                          urlTransform={allowDataImageUrl}
                          components={{
                            code({ className, children, ...props }: any) {
                              const match = /language-(\w+)/.exec(className || '');
                              const rawContent = String(children).replace(/\n$/, '');
                              if (/\\begin\{(?:aligned|align\*?|equation\*?|gather\*?|multline\*?|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}/.test(rawContent)) {
                                return <KatexDisplay math={rawContent} />;
                              }
                              return match ? (
                                <SyntaxHighlighter style={codeTheme as any} language={match[1]} PreTag="div" {...props}>
                                  {rawContent}
                                </SyntaxHighlighter>
                              ) : (
                                <code className={className} {...props}>{children}</code>
                              );
                            },
                            img({ src, alt, ...props }: any) { return <PlotImage src={src} alt={alt} {...props} />; },
                          }}
                        >
                          {tool.output}
                        </ReactMarkdown>
                      </div>
                    </div>
                  )}
                </div>
              </details>
            ))}
          </div>
        )}
      </div>
    </div>
  );
});

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState<User | null>(null);
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [responseComplete, setResponseComplete] = useState(false);
  const [statusMessage, setStatusMessage] = useState('');
  const [activeSymbolCategory, setActiveSymbolCategory] = useState('greek');
  const [showMathSymbols, setShowMathSymbols] = useState(false);
  const [webSearchEnabled, setWebSearchEnabled] = useState(true);
  const [selectedModel, setSelectedModel] = useState<string>('deepseek-chat');
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [conversations, setConversations] = useState<ConversationItem[]>([]);
  const [currentConvId, setCurrentConvId] = useState<string | null>(null);

  const [theme, setTheme] = useState<'dark' | 'light'>(() => {
    return (localStorage.getItem('evo_theme') as 'dark' | 'light') || 'light';
  });

  useEffect(() => {
    document.documentElement.dataset.theme = theme;
    localStorage.setItem('evo_theme', theme);
  }, [theme]);

  const toggleTheme = () => setTheme(t => t === 'dark' ? 'light' : 'dark');
  // Memoize so CodeThemeContext.Provider doesn't re-render all consumers on every render
  const codeTheme = useMemo(
    () => (theme === 'dark' ? terminalTheme : lightCodeTheme),
    [theme]
  );

  const chatPlaceholder = useMemo(
    () => LOGIC_SAYINGS[Math.floor(Math.random() * LOGIC_SAYINGS.length)],
    []
  );

  const AVAILABLE_MODELS = [
    { id: 'deepseek-chat', label: 'DeepSeek V3', title: 'DeepSeek V3 (fast)' },
    { id: 'deepseek-reasoner', label: 'DeepSeek R1', title: 'DeepSeek R1 (deep reasoning)' },
  ];
  const examples = [
    {
      label: 'Prove $\\sqrt{2}$ is irrational',
      prompt: 'Prove that sqrt(2) is irrational using first principles.',
    },
    {
      label: 'Solve integral $x^2\\sin(x)$',
      prompt: 'Solve the integral of x^2 sin(x) with SymPy and show the result.',
    },
    {
      label: 'Find primes with Prolog',
      prompt: 'Find all prime numbers less than 100 using Prolog.',
    },
    {
      label: 'Eigenvalues of $\\begin{bmatrix}2&1\\\\1&2\\end{bmatrix}$',
      prompt: 'Find the eigenvalues and eigenvectors of the matrix [[2,1],[1,2]] and verify by substitution.',
    },
  ];

  const toggleModel = () => {
    setSelectedModel((prev) =>
      prev === 'deepseek-chat' ? 'deepseek-reasoner' : 'deepseek-chat'
    );
  };
  const messagesContainerRef = useRef<HTMLDivElement>(null);
  const abortControllerRef = useRef<AbortController | null>(null);
  const requestIdRef = useRef<number>(0);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Logout on page close or refresh
  useEffect(() => {
    const handleBeforeUnload = () => {
      if (sessionId) {
        // keepalive allows the request to continue during page unload.
        fetch(`${GATEWAY_URL}/api/auth/logout`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${sessionId}`,
          },
          body: JSON.stringify({}),
          keepalive: true,
        }).catch(() => {
          // Best-effort logout during unload; ignore failures.
        });
      }
    };
    
    window.addEventListener('beforeunload', handleBeforeUnload);
    
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [sessionId]);

  // Auto-save conversation when a response fully completes (not during streaming)
  useEffect(() => {
    if (responseComplete && !isGenerating && messages.length > 0) {
      const newId = saveConversation(messages, currentConvId);
      if (newId && !currentConvId) setCurrentConvId(String(newId));
    }
  }, [responseComplete, isGenerating, messages, currentConvId]);

  const handleStopGeneration = () => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
    setIsLoading(false);
    setIsGenerating(false);
    setStatusMessage('');
    // Stop all streaming animations and tool executing states
    setMessages((prev) =>
      prev.map((msg) => ({
        ...msg,
        isStreaming: false,
        toolCalls: msg.toolCalls?.map((tc) =>
          tc.isGenerating || tc.isExecuting
            ? { ...tc, isGenerating: false, isExecuting: false }
            : tc
        ),
      }))
    );
  };

  const handleSendMessage = async () => {
    if (!input.trim() || isGenerating) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: input,
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    const currentInput = input;
    setInput('');
    setIsLoading(true);
    setIsGenerating(true);
    setResponseComplete(false);
    setStatusMessage('Connecting to AI model...');

    // Create a temporary assistant message that will be updated
    const assistantId = (Date.now() + 1).toString();
    const assistantMessage: Message = {
      id: assistantId,
      role: 'assistant',
      content: '',
      timestamp: new Date(),
      toolCalls: [],
      isStreaming: false,
    };

    setMessages((prev) => [...prev, assistantMessage]);

    // Stamp this request so stale finally/catch blocks can't clobber a newer request
    requestIdRef.current += 1;
    const myRequestId = requestIdRef.current;
    let wasAborted = false;
    const isR1 = selectedModel === 'deepseek-reasoner';

    try {
      // Create new AbortController for this request
      abortControllerRef.current = new AbortController();
      
      const headers: HeadersInit = {
        'Content-Type': 'application/json'
      };
      
      // Add Authorization header with session ID
      if (sessionId) {
        headers['Authorization'] = `Bearer ${sessionId}`;
      }
      
      const response = await fetch(`${GATEWAY_URL}/api/chat`, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          message: currentInput,
          model: selectedModel,
          webSearchEnabled,
        }),
        signal: abortControllerRef.current.signal,
      });

      if (!response.ok) {
        // Try to get error message from response
        let errorMessage = `Backend returned an error ${response.status}`;
        try {
          const errorData = await response.json();
          errorMessage = errorData.error || errorData.message || errorMessage;
        } catch (e) {
          // Response wasn't JSON, use status text
          errorMessage = response.statusText || errorMessage;
        }
        throw new Error(errorMessage);
      }

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();

      if (!reader) {
        throw new Error('No response body');
      }

      let buffer = '';

      // Local mirrors – avoid reading React state in the hot path.
      let localThinkingContent = '';
      let finalBuffer = '';
      let toolsUsed = false;

      // RAF batching for content_chunk / reasoning_chunk.
      // Accumulate text locally; flush to React state at most once per frame.
      let pendingThinkingFlush = '';
      let pendingReasoningFlush = '';
      let rafId: number | null = null;
      let firstChunkSeen = false;
      const updateAssistantMessage = (updater: (msg: Message) => Message) => {
        setMessages((prev) => {
          let idx = prev.length - 1;
          while (idx >= 0 && prev[idx].id !== assistantId) idx -= 1;
          if (idx < 0) return prev;
          const next = prev.slice();
          next[idx] = updater(prev[idx]);
          return next;
        });
      };

      const flushChunks = () => {
        rafId = null;
        const tc = pendingThinkingFlush;
        const rc = pendingReasoningFlush;
        pendingThinkingFlush = '';
        pendingReasoningFlush = '';
        if (!tc && !rc) return;
        updateAssistantMessage((msg) => {
          const next: typeof msg = { ...msg, isStreaming: true };
          if (tc) {
            if (isR1) {
              // R1: content chunks are the final answer, not thinking — route
              // directly to content so the Thinking panel never shows for R1.
              next.content = (msg.content || '') + tc;
            } else {
              next.thinkingContent = (msg.thinkingContent || '') + tc;
              next.thinkingExpanded = true;
            }
          }
          if (rc) {
            next.reasoningContent = (msg.reasoningContent || '') + rc;
            next.reasoningExpanded = true;
          }
          return next;
        });
      };

      const scheduleFlush = () => {
        if (rafId === null) rafId = requestAnimationFrame(flushChunks);
      };

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          // Cancel any pending RAF and do a final synchronous flush
          if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
          flushChunks();
          setIsLoading(false);
          setResponseComplete(true);
          setStatusMessage('');
          break;
        }

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (!line.trim()) continue;

          const eventMatch = line.match(/^event: (.+)$/m);
          const dataMatch = line.match(/^data: (.+)$/m);

          if (!eventMatch || !dataMatch) continue;

          const event = eventMatch[1];
          const data = JSON.parse(dataMatch[1]);

          if (event === 'status') {
            setStatusMessage(data.message || 'Processing...');
          } else if (event === 'content_chunk') {
            // For V3 only: strip leading newlines when the buffer already ends with
            // a newline, to avoid consecutive blank lines in the Thinking panel.
            // R1 routes content_chunks to the final answer, so we must not alter them.
            let chunk: string = data.chunk;
            if (!isR1 && localThinkingContent.endsWith('\n') && chunk.startsWith('\n')) {
              chunk = chunk.replace(/^\n+/, '');
            }
            localThinkingContent += chunk;
            finalBuffer += chunk;
            pendingThinkingFlush += chunk;
            // One-time: hide spinner on first content
            if (!firstChunkSeen) {
              firstChunkSeen = true;
              setIsLoading(false);
              setResponseComplete(true);
              setStatusMessage('');
            }
            scheduleFlush();
          } else if (event === 'reasoning_chunk') {
            pendingReasoningFlush += data.chunk;
            if (!firstChunkSeen) {
              firstChunkSeen = true;
              setIsLoading(false);
              setResponseComplete(true);
              setStatusMessage('');
            }
            scheduleFlush();
          } else if (event === 'tool_start') {
            // Flush before handling structural events so ordering is correct
            if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
            flushChunks();
            toolsUsed = true;
            finalBuffer = '';
            setStatusMessage(`Generating ${data.name}...`);
            updateAssistantMessage((msg) => ({
              ...msg,
              isStreaming: true,
              toolCalls: [
                ...(msg.toolCalls || []),
                {
                  id: data.id,
                  name: data.name,
                  input: data.input,
                  output: '',
                  isGenerating: true,
                  isExecuting: false,
                },
              ],
            }));
          } else if (event === 'tool_executing') {
            if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
            flushChunks();
            // Tool is now executing - update status
            setStatusMessage(`Executing ${data.name}...`);
            updateAssistantMessage((msg) => ({
              ...msg,
              toolCalls: (msg.toolCalls || []).map((tc) =>
                tc.id === data.id
                  ? { ...tc, isGenerating: false, isExecuting: true }
                  : tc
              ),
            }));
          } else if (event === 'tool_complete') {
            if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
            flushChunks();
            // Reset finalBuffer: any content_chunks that arrive after this
            // are candidates for the final response.
            // For V3 only: add a smart newline separator (avoid double blank lines).
            // R1 routes pendingThinkingFlush to final content, so leave it unchanged.
            finalBuffer = '';
            if (!isR1) {
              if (!localThinkingContent.endsWith('\n\n')) {
                const sep = localThinkingContent.endsWith('\n') ? '\n' : '\n\n';
                localThinkingContent += sep;
                pendingThinkingFlush += sep;
              }
            } else {
              localThinkingContent += '\n\n';
              pendingThinkingFlush += '\n\n';
            }
            scheduleFlush();
            setStatusMessage('');
            const output = data.output || '';
            
            // Strategy: Check the LAST line for success/failure indicators
            // This avoids false positives from status markers (❌ Not needed) in the middle
            const lines = output.trim().split('\n');
            const lastLine = lines[lines.length - 1] || '';
            
            // Success indicators on the last line OR anywhere in full output
            const hasFinalSuccess = 
              lastLine.includes('✅ Classification stored') ||
              lastLine.includes('✅ Lean 4 code compiled successfully') ||
              lastLine.includes('✅ Python code executed successfully') ||
              lastLine.includes('✅ SymPy code executed successfully') ||
              lastLine.includes('✅ Prolog code executed') ||
              lastLine.includes('✅ Found in Mathlib') ||
              /✅.*completed/i.test(lastLine) ||
              lastLine.includes('✅') ||
              output.includes('✅ **Compilation Successful**');  // Lean 4 success (bold markdown)
            
            // Actual failure indicators (not status markers like "❌ Not needed")
            const hasActualFailure = 
              output.includes('❌ BLOCKED') ||
              output.includes('❌ Python execution failed') ||
              output.includes('❌ SymPy execution failed') ||
              output.includes('❌ Lean 4 compilation failed') ||
              output.includes('❌ **Compilation Failed**') ||  // Lean 4 failure (bold markdown)
              output.includes('❌ Compilation Failed') ||      // Lean 4 failure (plain)
              output.includes('❌ Not found in Mathlib') ||
              output.includes('Exit code: 0') === false && /Exit code: \d+/.test(output);
            
            // Determine error state
            let hasError = false;
            if (hasFinalSuccess) {
              hasError = false; // Explicit success on last line
            } else if (hasActualFailure) {
              hasError = true; // Explicit failure
            } else {
              // Fallback: check for Error: prefix
              hasError = output.startsWith('Error:') || output.includes('\nError:');
            }
            
            updateAssistantMessage((msg) => ({
              ...msg,
              toolCalls: (msg.toolCalls || []).map((tc) =>
                tc.id === data.id
                  ? { ...tc, output: data.output, error: hasError, isGenerating: false, isExecuting: false }
                  : tc
              ),
            }));
          } else if (event === 'done') {
            // Flush any remaining buffered chunks synchronously before routing
            if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
            flushChunks();
            // Route content correctly:
            // - No tools fired → thinkingContent is actually the final response,
            //   move it to content and hide the Thinking panel.
            // - Tools fired → everything before the first blank-line break in
            //   finalBuffer is preamble (LLM commentary like "The result looks
            //   good, let me summarise...") → append to thinkingContent.
            //   Everything from the first blank-line break onward is the real
            //   final answer → content.  If finalBuffer already starts with
            //   structured markdown, treat the whole thing as the final answer.
            setIsLoading(false);
            setIsGenerating(false);
            setResponseComplete(true);
            setStatusMessage('');
            setMessages((prev) =>
              prev.map((msg) => {
                if (msg.id !== assistantId) return msg;
                if (!toolsUsed) {
                  // Pure V3 response without tools – show as normal content,
                  // no Thinking panel needed.
                  return {
                    ...msg,
                    content: localThinkingContent,
                    thinkingContent: undefined,
                    thinkingExpanded: undefined,
                    isStreaming: false,
                  };
                }
                // R1: content chunks were already routed to msg.content during
                // streaming — just clear any residual thinkingContent and stop.
                if (isR1) {
                  return {
                    ...msg,
                    thinkingContent: undefined,
                    thinkingExpanded: undefined,
                    isStreaming: false,
                  };
                }
                // V3 tools were used.
                // Determine the split point inside finalBuffer.
                // If finalBuffer starts with structured markdown, don't split.
                const alreadyStructured = /^\s*(#{1,6} |\*\*|\d+\.\s|\-\s)/.test(finalBuffer);
                const blankLineIdx = alreadyStructured ? -1 : finalBuffer.indexOf('\n\n');
                const preamble = blankLineIdx !== -1 ? finalBuffer.slice(0, blankLineIdx) : '';
                const answer   = blankLineIdx !== -1 ? finalBuffer.slice(blankLineIdx + 2) : finalBuffer;

                const thinkingBase = localThinkingContent.slice(
                  0,
                  localThinkingContent.length - finalBuffer.length
                ).trimEnd();
                const newThinking = preamble
                  ? (thinkingBase + '\n\n' + preamble.trimEnd())
                  : (thinkingBase || undefined);

                return {
                  ...msg,
                  content: answer,
                  thinkingContent: newThinking || undefined,
                  thinkingExpanded: !!newThinking,
                  isStreaming: false,
                };
              })
            );
          } else if (event === 'error') {
            if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
            // Error occurred
            setIsLoading(false);
            setIsGenerating(false);
            setResponseComplete(true);
            setStatusMessage('');
            setMessages((prev) =>
              prev.map((msg) =>
                msg.id === assistantId
                  ? {
                      ...msg,
                      content: `Error: ${data.error}\n${data.details || ''}`,
                      isStreaming: false,
                    }
                  : msg
              )
            );
          }
        }
      }
    } catch (error) {
      // Don't show error message if request was aborted (stop button)
      if (error instanceof Error && error.name === 'AbortError') {
        wasAborted = true;
        console.log('Request aborted by user');
        return;
      }
      // Only update state if this is still the active request
      if (myRequestId !== requestIdRef.current) return;
      
      console.error('Error sending message:', error);
      setIsLoading(false);
      setIsGenerating(false);
      setResponseComplete(true);
      setStatusMessage('');
      const errorDetail = error instanceof Error ? error.message : String(error);
      setMessages((prev) =>
        prev.map((msg) =>
          msg.id === assistantId
            ? {
                ...msg,
                content: `Sorry, there was an error processing your request.\n\n**Error:** ${errorDetail}`,
                isStreaming: false,
              }
            : msg
        )
      );
    } finally {
      // Always clean up loading state for this request — even on abort.
      // handleStopGeneration schedules the same updates synchronously, but
      // React state updates are async; clearing here as well guarantees the
      // UI unlocks regardless of timing so the user can send a new message.
      if (myRequestId === requestIdRef.current) {
        setIsLoading(false);
        setIsGenerating(false);
        setStatusMessage('');
        abortControllerRef.current = null;
        if (!wasAborted) {
          setResponseComplete(true);
        }
      }
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const insertSymbol = (symbol: string) => {
    const textarea = textareaRef.current;
    if (textarea) {
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const newValue = input.slice(0, start) + symbol + input.slice(end);
      setInput(newValue);
      setTimeout(() => {
        textarea.selectionStart = textarea.selectionEnd = start + symbol.length;
        textarea.focus();
      }, 0);
    } else {
      setInput((prev) => prev + symbol);
    }
  };

  const saveConversation = (msgs: Message[], convId: string | null) => {
    if (msgs.length === 0) return;
    const firstUserMsg = msgs.find(m => m.role === 'user');
    const title = firstUserMsg
      ? firstUserMsg.content.slice(0, 60) + (firstUserMsg.content.length > 60 ? '…' : '')
      : 'New conversation';
    const storageKey = `evo_conversations_${user?.username}`;
    setConversations(prev => {
      const existing = prev.findIndex(c => c.id === convId);
      const updated: ConversationItem = {
        id: convId || Date.now().toString(),
        title,
        timestamp: new Date(),
        messages: msgs,
      };
      const next = existing >= 0
        ? prev.map(c => c.id === convId ? updated : c)
        : [updated, ...prev];
      const limited = next.slice(0, 50);
      try { localStorage.setItem(storageKey, JSON.stringify(limited)); } catch {}
      return limited;
    });
    return convId || Date.now().toString();
  };

  const loadConversation = (conv: ConversationItem) => {
    setMessages(conv.messages.map(m => ({ ...m, timestamp: new Date(m.timestamp) })));
    setCurrentConvId(conv.id);
    setInput('');
    setIsLoading(false);
    setResponseComplete(false);
    setStatusMessage('');
    setSidebarOpen(false);
  };

  const deleteConversation = (convId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const storageKey = `evo_conversations_${user?.username}`;
    setConversations(prev => {
      const next = prev.filter(c => c.id !== convId);
      try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch {}
      return next;
    });
    if (currentConvId === convId) {
      setMessages([]);
      setCurrentConvId(null);
    }
  };

  const copyAsMarkdown = useCallback((content: string, event: React.MouseEvent) => {
    const btn = event.currentTarget as HTMLElement;
    const svg = btn.querySelector('svg');
    
    navigator.clipboard.writeText(content).then(() => {
      // Change icon to checkmark
      if (svg) {
        const originalSVG = svg.innerHTML;
        svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
        btn.classList.add('copied');
        
        setTimeout(() => {
          svg.innerHTML = originalSVG;
          btn.classList.remove('copied');
        }, 2000);
      }
    }).catch(err => {
      console.error('Failed to copy:', err);
    });
  }, []);

  const copyEverything = useCallback((message: Message, event: React.MouseEvent) => {
    const btn = event.currentTarget as HTMLElement;
    const svg = btn.querySelector('svg');
    
    let fullText = '';
    
    // Add main message content
    if (message.content) {
      fullText += message.content + '\n\n';
    }
    
    // Add all tool calls with their inputs and outputs
    if (message.toolCalls && message.toolCalls.length > 0) {
      fullText += '=== Tool Calls ===\n\n';
      message.toolCalls.forEach((tool, idx) => {
        fullText += `[${idx + 1}] Tool: ${tool.name}\n`;
        fullText += `Input:\n${tool.input}\n\n`;
        if (tool.output) {
          fullText += `Output:\n${tool.output}\n\n`;
        }
        fullText += '---\n\n';
      });
    }
    
    navigator.clipboard.writeText(fullText.trim()).then(() => {
      // Change icon to checkmark
      if (svg) {
        const originalSVG = svg.innerHTML;
        svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
        btn.classList.add('copied');
        
        setTimeout(() => {
          svg.innerHTML = originalSVG;
          btn.classList.remove('copied');
        }, 2000);
      }
    }).catch(err => {
      console.error('Failed to copy:', err);
    });
  }, []);

  const handleToggleReasoning = useCallback((messageId: string, open: boolean) => {
    setMessages((prev) => prev.map((m) => m.id === messageId ? { ...m, reasoningExpanded: open } : m));
  }, []);

  const handleToggleThinking = useCallback((messageId: string, open: boolean) => {
    setMessages((prev) => prev.map((m) => m.id === messageId ? { ...m, thinkingExpanded: open } : m));
  }, []);

  const handleLogin = (
    sessionId: string,
    userData: User
  ) => {
    // Keep session only in memory - will be lost on refresh
    if (sessionId) {
      setSessionId(sessionId);
    }
    setUser(userData);
    setIsAuthenticated(true);
    // Load this user's conversation history
    try {
      const stored = localStorage.getItem(`evo_conversations_${userData.username}`);
      if (stored) {
        const parsed = JSON.parse(stored);
        setConversations(parsed.map((c: any) => ({ ...c, timestamp: new Date(c.timestamp) })));
      } else {
        setConversations([]);
      }
    } catch { setConversations([]); }
  };

  const handleNewChat = async () => {
    // Save current conversation before clearing
    if (messages.length > 0) {
      saveConversation(messages, currentConvId);
    }

    // Cancel any ongoing request
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
    
    // Clear backend conversation history
    try {
      const headers: HeadersInit = {
        'Content-Type': 'application/json'
      };
      if (sessionId) {
        headers['Authorization'] = `Bearer ${sessionId}`;
      }
      
      await fetch(`${GATEWAY_URL}/api/chat/clear`, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          user: user
        })
      });
    } catch (error) {
      console.error('Failed to clear chat history:', error);
    }
    
    // Clear frontend state
    setMessages([]);
    setCurrentConvId(null);
    setInput('');
    setIsLoading(false);
    setResponseComplete(false);
    setStatusMessage('');
  };

  const handleLogout = async () => {
    try {
      const headers: HeadersInit = {};
      if (sessionId) {
        headers['Authorization'] = `Bearer ${sessionId}`;
      }
      
      await fetch(`${GATEWAY_URL}/api/auth/logout`, {
        method: 'POST',
        headers
      });
    } catch (error) {
      console.error('Logout failed:', error);
    }
    
    // Clear session state
    setSessionId(null);
    setUser(null);
    setIsAuthenticated(false);
    setMessages([]);
    setConversations([]);
    setCurrentConvId(null);
  };

  if (!isAuthenticated) {
    return <Login onLogin={handleLogin} />;
  }

  return (
    <CodeThemeContext.Provider value={codeTheme}>
    <div className="app">
      {/* Sidebar overlay (mobile) */}
      {sidebarOpen && (
        <div className="sidebar-overlay" onClick={() => setSidebarOpen(false)} />
      )}
      {/* Left sidebar */}
      <aside className={`sidebar${sidebarOpen ? ' sidebar--open' : ''}`}>
        <div className="sidebar-header">
          <span className="sidebar-logo">evo</span>
          <button className="sidebar-collapse-btn" onClick={() => setSidebarOpen(false)} title="Collapse sidebar">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M15 18l-6-6 6-6" />
            </svg>
          </button>
        </div>
        <button className="new-chat-btn" onClick={handleNewChat}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
          </svg>
          New Chat
        </button>
        <div className="sidebar-conversations">
          {conversations.length > 0 && (
            <div className="sidebar-section-label">Recent</div>
          )}
          {conversations.map(conv => (
            <div
              key={conv.id}
              className={`conv-item${currentConvId === conv.id ? ' conv-item--active' : ''}`}
              onClick={() => loadConversation(conv)}
            >
              <svg className="conv-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
              </svg>
              <span className="conv-title">{conv.title}</span>
              <button
                className="conv-delete-btn"
                onClick={(e) => deleteConversation(conv.id, e)}
                title="Delete"
              >
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
                </svg>
              </button>
            </div>
          ))}
        </div>
        <div className="sidebar-footer">
          <div className="model-selector">
            <div className="model-selector-label">Model</div>
            <button
              className={`model-option${selectedModel === 'deepseek-chat' ? ' model-option--active' : ''}`}
              onClick={() => setSelectedModel('deepseek-chat')}
            >
              <span className="model-dot" />
              DeepSeek V3
              <span className="model-tag">Fast</span>
            </button>
            <button
              className={`model-option${selectedModel === 'deepseek-reasoner' ? ' model-option--active' : ''}`}
              onClick={() => setSelectedModel('deepseek-reasoner')}
            >
              <span className="model-dot model-dot--r1" />
              DeepSeek R1
              <span className="model-tag model-tag--r1">Reason</span>
            </button>
          </div>
          <button className="theme-toggle-btn" onClick={toggleTheme} title="Toggle theme">
            {theme === 'dark' ? (
              <>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="5" />
                  <line x1="12" y1="1" x2="12" y2="3" /><line x1="12" y1="21" x2="12" y2="23" />
                  <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" /><line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
                  <line x1="1" y1="12" x2="3" y2="12" /><line x1="21" y1="12" x2="23" y2="12" />
                  <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" /><line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
                </svg>
                Light mode
              </>
            ) : (
              <>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
                </svg>
                Dark mode
              </>
            )}
          </button>
          <div className="user-section">
            <div className="user-avatar">{user?.name?.[0]?.toUpperCase() ?? '?'}</div>
            <span className="user-name">{user?.name}</span>
            <button className="user-logout-btn" onClick={handleLogout} title="Sign out">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
                <polyline points="16 17 21 12 16 7" />
                <line x1="21" y1="12" x2="9" y2="12" />
              </svg>
            </button>
          </div>
        </div>
      </aside>

      {/* Main content */}
      <main className={`main${sidebarOpen ? ' main--sidebar-open' : ''}`}>
        {/* Top bar */}
        <div className="topbar">
          <button className="topbar-menu-btn" onClick={() => setSidebarOpen(s => !s)} title="Toggle sidebar">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="18" x2="21" y2="18" />
            </svg>
          </button>
          {!sidebarOpen && <span className="topbar-logo">evo</span>}
          <div className="topbar-spacer" />
          <button className="topbar-new-btn" onClick={handleNewChat}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
            </svg>
            New chat
          </button>
        </div>

        {/* Messages */}
        <div className="messages" ref={messagesContainerRef}>
          {messages.length === 0 ? (
            <div className="welcome">
              <div className="welcome-logo">evo</div>
              <h2 className="welcome-heading">
                Logical AI
              </h2>
              <p className="welcome-sub">Explicit-assumption · Verification · Orchestrator</p>
              <div className="examples">
                {examples.map((example) => (
                  <button key={example.label} className="example-btn" onClick={() => setInput(example.prompt)}>
                    <ReactMarkdown
                      remarkPlugins={[remarkMath]}
                      rehypePlugins={[[rehypeKatex, { throwOnError: false, strict: false }]]}
                      components={{
                        p: ({ children }) => <span>{children}</span>,
                      }}
                    >
                      {example.label}
                    </ReactMarkdown>
                  </button>
                ))}
              </div>
            </div>
          ) : (
            messages.map((message, index) => (
              <MessageItem
                key={message.id}
                message={message}
                userName={user?.name}
                onCopyMarkdown={copyAsMarkdown}
                onCopyEverything={copyEverything}
                onToggleReasoning={handleToggleReasoning}
                onToggleThinking={handleToggleThinking}
                showThinking={isLoading && !responseComplete && message.role === 'assistant' && index === messages.length - 1}
              />
            ))
          )}

          {isLoading && !responseComplete && messages[messages.length - 1]?.role !== 'assistant' && (
            <div className="typing-indicator">
              <div className="avatar avatar--assistant">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>
                </svg>
              </div>
              <div className="typing-dots">
                <span></span><span></span><span></span>
                <em className="status-message">{statusMessage || 'Thinking...'}</em>
              </div>
            </div>
          )}
        </div>

        {/* Input area */}
        <div className="input-wrapper">
          {/* Math symbols popup */}
          {showMathSymbols && (
            <div className="math-symbols-popup">
              <div className="math-symbols-popup-content">
                <div className="math-symbols-popup-header">
                  <span>Math Symbols</span>
                  <button className="math-symbols-close-btn" onClick={() => setShowMathSymbols(false)} aria-label="Close">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                  </button>
                </div>
                <div className="math-symbols">
                  <div className="symbol-tabs">
                    {['greek','operators','relations','sets','logic','arrows','special','calculus','linear','equations','matrices'].map(cat => (
                      <button key={cat} onClick={() => setActiveSymbolCategory(cat)} className={`symbol-tab${activeSymbolCategory === cat ? ' active' : ''}`}>
                        {cat.charAt(0).toUpperCase() + cat.slice(1)}
                      </button>
                    ))}
                  </div>
                  <div className="symbol-content">
                    {activeSymbolCategory === 'greek' && (
                      <div className="symbol-category">
                        <div className="symbol-row">
                          {[['\\alpha ','α'],['\\beta ','β'],['\\gamma ','γ'],['\\delta ','δ'],['\\epsilon ','ε'],['\\theta ','θ'],['\\lambda ','λ'],['\\mu ','μ'],['\\pi ','π'],['\\sigma ','σ'],['\\phi ','φ'],['\\omega ','ω']].map(([s,l]) => (
                            <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                          ))}
                        </div>
                        <div className="symbol-row">
                          {[['\\Gamma ','Γ'],['\\Delta ','Δ'],['\\Theta ','Θ'],['\\Lambda ','Λ'],['\\Pi ','Π'],['\\Sigma ','Σ'],['\\Phi ','Φ'],['\\Omega ','Ω']].map(([s,l]) => (
                            <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                          ))}
                        </div>
                      </div>
                    )}
                    {activeSymbolCategory === 'operators' && (
                      <div className="symbol-category"><div className="symbol-row">
                        {[['\\sum ','∑'],['\\prod ','∏'],['\\int ','∫'],['\\iint ','∬'],['\\oint ','∮'],['\\partial ','∂'],['\\nabla ','∇'],['\\sqrt{} ','√'],['\\pm ','±'],['\\mp ','∓'],['\\times ','×'],['\\div ','÷'],['\\cdot ','·'],['\\ast ','∗']].map(([s,l]) => (
                          <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                        ))}
                      </div></div>
                    )}
                    {activeSymbolCategory === 'relations' && (
                      <div className="symbol-category"><div className="symbol-row">
                        {[['\\leq ','≤'],['\\geq ','≥'],['\\neq ','≠'],['\\approx ','≈'],['\\equiv ','≡'],['\\sim ','∼'],['\\simeq ','≃'],['\\cong ','≅'],['\\propto ','∝'],['\\ll ','≪'],['\\gg ','≫']].map(([s,l]) => (
                          <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                        ))}
                      </div></div>
                    )}
                    {activeSymbolCategory === 'sets' && (
                      <div className="symbol-category"><div className="symbol-row">
                        {[['\\in ','∈'],['\\notin ','∉'],['\\subset ','⊂'],['\\subseteq ','⊆'],['\\supset ','⊃'],['\\supseteq ','⊇'],['\\cup ','∪'],['\\cap ','∩'],['\\emptyset ','∅'],['\\setminus ','\\']].map(([s,l]) => (
                          <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                        ))}
                      </div></div>
                    )}
                    {activeSymbolCategory === 'logic' && (
                      <div className="symbol-category"><div className="symbol-row">
                        {[['\\forall ','∀'],['\\exists ','∃'],['\\nexists ','∄'],['\\land ','∧'],['\\lor ','∨'],['\\neg ','¬'],['\\implies ','⟹'],['\\iff ','⟺'],['\\vdash ','⊢'],['\\models ','⊨']].map(([s,l]) => (
                          <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                        ))}
                      </div></div>
                    )}
                    {activeSymbolCategory === 'arrows' && (
                      <div className="symbol-category"><div className="symbol-row">
                        {[['\\to ','→'],['\\leftarrow ','←'],['\\leftrightarrow ','↔'],['\\Rightarrow ','⇒'],['\\Leftarrow ','⇐'],['\\Leftrightarrow ','⇔'],['\\mapsto ','↦'],['\\uparrow ','↑'],['\\downarrow ','↓']].map(([s,l]) => (
                          <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                        ))}
                      </div></div>
                    )}
                    {activeSymbolCategory === 'special' && (
                      <div className="symbol-category">
                        <div className="symbol-row">
                          {[['\\mathbb{R} ','ℝ'],['\\mathbb{C} ','ℂ'],['\\mathbb{N} ','ℕ'],['\\mathbb{Z} ','ℤ'],['\\mathbb{Q} ','ℚ'],['\\infty ','∞'],['\\aleph ','ℵ'],['\\hbar ','ℏ'],['\\ell ','ℓ']].map(([s,l]) => (
                            <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                          ))}
                        </div>
                        <div className="symbol-row">
                          {[['\\langle \\rangle ','⟨⟩'],['\\lfloor \\rfloor ','⌊⌋'],['\\lceil \\rceil ','⌈⌉'],['\\{ \\} ','{}'],['\\lVert \\rVert ','‖‖']].map(([s,l]) => (
                            <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                          ))}
                        </div>
                      </div>
                    )}
                    {activeSymbolCategory === 'calculus' && (
                      <div className="symbol-category"><div className="symbol-row">
                        {[['\\lim ','lim'],['\\sup ','sup'],['\\inf ','inf'],['\\max ','max'],['\\min ','min'],['\\frac{}{} ','a/b'],['^{} ','xⁿ'],['_{} ','xₙ']].map(([s,l]) => (
                          <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                        ))}
                      </div></div>
                    )}
                    {activeSymbolCategory === 'linear' && (
                      <div className="symbol-category"><div className="symbol-row">
                        {[['\\oplus ','⊕'],['\\otimes ','⊗'],['\\odot ','⊙'],['\\circ ','∘'],['\\perp ','⊥'],['\\parallel ','∥'],['\\det ','det'],['\\dim ','dim']].map(([s,l]) => (
                          <button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
                        ))}
                      </div></div>
                    )}
                    {activeSymbolCategory === 'equations' && (
                      <div className="symbol-category">
                        <div className="symbol-row">
                          <button onClick={() => insertSymbol('$  $')} className="symbol-btn template-btn" title="Inline math">$...$</button>
                          <button onClick={() => insertSymbol('$$\n  \n$$')} className="symbol-btn template-btn" title="Display math">$$...$$</button>
                          <button onClick={() => insertSymbol('\\begin{align}\n  & = \\\\\n  & = \n\\end{align}')} className="symbol-btn template-btn">align</button>
                          <button onClick={() => insertSymbol('\\begin{cases}\n   & \\text{if } \\\\\n   & \\text{if } \n\\end{cases}')} className="symbol-btn template-btn">cases</button>
                          <button onClick={() => insertSymbol('\\begin{equation}\n  \n\\end{equation}')} className="symbol-btn template-btn">equation</button>
                          <button onClick={() => insertSymbol('\\begin{aligned}\n  & \\\\\n  & \n\\end{aligned}')} className="symbol-btn template-btn">aligned</button>
                        </div>
                        <div className="symbol-row">
                          <button onClick={() => insertSymbol('\\begin{cases}\n  a_1x + b_1y = c_1 \\\\\n  a_2x + b_2y = c_2\n\\end{cases}')} className="symbol-btn template-btn">2 eq</button>
                          <button onClick={() => insertSymbol('\\begin{cases}\n  a_1x + b_1y + c_1z = d_1 \\\\\n  a_2x + b_2y + c_2z = d_2 \\\\\n  a_3x + b_3y + c_3z = d_3\n\\end{cases}')} className="symbol-btn template-btn">3 eq</button>
                        </div>
                      </div>
                    )}
                    {activeSymbolCategory === 'matrices' && (
                      <div className="symbol-category">
                        <div className="symbol-row">
                          <button onClick={() => insertSymbol('\\begin{pmatrix}\n  a & b \\\\\n  c & d\n\\end{pmatrix}')} className="symbol-btn template-btn">(2×2)</button>
                          <button onClick={() => insertSymbol('\\begin{bmatrix}\n  a & b \\\\\n  c & d\n\\end{bmatrix}')} className="symbol-btn template-btn">[2×2]</button>
                          <button onClick={() => insertSymbol('\\begin{vmatrix}\n  a & b \\\\\n  c & d\n\\end{vmatrix}')} className="symbol-btn template-btn">|2×2|</button>
                          <button onClick={() => insertSymbol('\\begin{pmatrix}\n  a & b & c \\\\\n  d & e & f \\\\\n  g & h & i\n\\end{pmatrix}')} className="symbol-btn template-btn">(3×3)</button>
                          <button onClick={() => insertSymbol('\\begin{pmatrix}\n  x_1 \\\\\n  x_2 \\\\\n  x_3\n\\end{pmatrix}')} className="symbol-btn template-btn">col vec</button>
                          <button onClick={() => insertSymbol('\\begin{pmatrix} x_1 & x_2 & x_3 \\end{pmatrix}')} className="symbol-btn template-btn">row vec</button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}

          <div className="input-box">
            <textarea
              ref={textareaRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder={chatPlaceholder}
              rows={3}
              disabled={isGenerating}
            />
            <div className="input-actions">
              <button
                onClick={() => setWebSearchEnabled(v => !v)}
                className={`action-icon-btn${webSearchEnabled ? ' action-icon-btn--active' : ''}`}
                title={webSearchEnabled ? 'Web search enabled (click to disable)' : 'Web search disabled (click to enable)'}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="10"/>
                  <line x1="2" y1="12" x2="22" y2="12"/>
                  <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
                </svg>
              </button>
              <button
                onClick={() => setShowMathSymbols(!showMathSymbols)}
                className={`action-icon-btn${showMathSymbols ? ' action-icon-btn--active' : ''}`}
                title="Math Symbols"
              >
                Σ
              </button>
              <button
                onClick={toggleModel}
                className={`model-toggle-btn${selectedModel === 'deepseek-reasoner' ? ' model-toggle-btn--r1' : ''}`}
                title={AVAILABLE_MODELS.find(m => m.id === selectedModel)?.title}
                disabled={isGenerating}
              >
                {selectedModel === 'deepseek-chat' ? 'V3' : 'R1'}
              </button>
              {isGenerating ? (
                <button
                  onClick={handleStopGeneration}
                  className="stop-btn"
                  title="Stop generation"
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                    <rect x="4" y="4" width="16" height="16" rx="2"/>
                  </svg>
                </button>
              ) : (
                <button
                  onClick={handleSendMessage}
                  disabled={!input.trim()}
                  className="send-btn"
                  title="Send (Enter)"
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </button>
              )}
            </div>
          </div>
          <div className="input-footer">Press Enter to send · Shift+Enter for new line</div>
        </div>
      </main>
    </div>
    </CodeThemeContext.Provider>
  );
}

export default App;