File size: 52,662 Bytes
e803935
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>AxonIQ β€” AI Clinical Assistant</title>
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
  :root {
    --navy:#0B1F3A;--teal:#0A7B74;--teal-lt:#E6F5F4;--amber:#C97B2A;--red:#B53535;
    --sand:#F5F1EB;--warm-white:#FDFAF6;--border:#DDD8CF;--text:#1A1510;--muted:#6B6056;
    --bubble-ai:#F0F7F6;--bubble-user:#0B1F3A;--sidebar-w:260px;
  }
  *,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
  body{font-family:'DM Sans',sans-serif;background:var(--warm-white);color:var(--text);height:100vh;display:flex;flex-direction:column;overflow:hidden;}

  /* AUTH */
  #authOverlay{position:fixed;inset:0;background:rgba(11,31,58,0.85);backdrop-filter:blur(6px);display:flex;align-items:center;justify-content:center;z-index:1000;}
  .auth-card{background:#fff;border-radius:20px;padding:40px 44px;width:420px;max-width:95vw;box-shadow:0 24px 64px rgba(0,0,0,0.3);}
  .auth-logo{display:flex;align-items:center;gap:12px;margin-bottom:28px;}
  .auth-logo-mark{width:44px;height:44px;background:var(--teal);border-radius:10px;display:flex;align-items:center;justify-content:center;font-family:'Libre Baskerville',serif;font-size:20px;font-weight:700;color:#fff;}
  .auth-logo h2{font-family:'Libre Baskerville',serif;font-size:20px;color:var(--navy);font-weight:700;}
  .auth-logo p{font-size:12px;color:var(--muted);}
  .auth-tabs{display:flex;margin-bottom:24px;border:1.5px solid var(--border);border-radius:10px;overflow:hidden;}
  .auth-tab{flex:1;padding:10px;text-align:center;font-size:14px;font-weight:500;cursor:pointer;background:none;border:none;color:var(--muted);transition:background 0.15s,color 0.15s;}
  .auth-tab.active{background:var(--navy);color:#fff;}
  .auth-field{margin-bottom:16px;}
  .auth-field label{display:block;font-size:12px;font-weight:600;color:var(--muted);margin-bottom:6px;letter-spacing:0.4px;text-transform:uppercase;}
  .auth-field input{width:100%;padding:11px 14px;border:1.5px solid var(--border);border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--text);outline:none;transition:border-color 0.2s,box-shadow 0.2s;}
  .auth-field input:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(10,123,116,0.1);}
  .auth-btn{width:100%;padding:13px;background:var(--teal);color:#fff;border:none;border-radius:9px;font-family:'DM Sans',sans-serif;font-size:15px;font-weight:600;cursor:pointer;margin-top:6px;transition:background 0.2s;}
  .auth-btn:hover{background:#088078;}
  .auth-btn:disabled{background:#8FA8BF;cursor:not-allowed;}
  .auth-error{background:#FEE2E2;border:1px solid #FECACA;border-radius:8px;padding:10px 14px;font-size:13px;color:#B91C1C;margin-bottom:14px;display:none;}
  .auth-register-only{display:none;}

  /* SHELL */
  #appShell{display:none;flex-direction:column;height:100vh;}
  #appShell.visible{display:flex;}
  header{background:var(--navy);padding:14px 20px;display:flex;align-items:center;gap:14px;border-bottom:3px solid var(--teal);flex-shrink:0;z-index:10;}
  .sidebar-toggle{width:32px;height:32px;border-radius:8px;background:rgba(255,255,255,0.08);border:none;color:#8FA8BF;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;transition:background 0.15s;}
  .sidebar-toggle:hover{background:rgba(255,255,255,0.15);}
  .logo-mark{width:36px;height:36px;background:var(--teal);border-radius:9px;display:flex;align-items:center;justify-content:center;font-family:'Libre Baskerville',serif;font-size:16px;font-weight:700;color:#fff;}
  .header-text h1{font-family:'Libre Baskerville',serif;font-size:18px;color:#fff;font-weight:700;}
  .header-text p{font-size:11px;color:#8FA8BF;margin-top:1px;}
  .header-right{margin-left:auto;display:flex;align-items:center;gap:10px;}
  .model-badge{background:rgba(10,123,116,0.2);border:1px solid rgba(10,123,116,0.4);color:#5ECFC8;font-size:11px;font-weight:500;padding:3px 9px;border-radius:20px;letter-spacing:0.4px;}
  .nav-link{color:#8FA8BF;font-size:12px;text-decoration:none;border:1px solid rgba(255,255,255,0.1);padding:4px 10px;border-radius:6px;}
  .user-pill{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,0.08);border-radius:20px;padding:4px 12px 4px 6px;cursor:pointer;transition:background 0.15s;position:relative;}
  .user-pill:hover{background:rgba(255,255,255,0.15);}
  .user-avatar{width:26px;height:26px;border-radius:50%;background:var(--teal);display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#fff;}
  .user-name{font-size:13px;color:#E0EAF4;font-weight:500;}
  .user-dropdown{position:absolute;top:calc(100% + 8px);right:0;background:#fff;border:1px solid var(--border);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,0.12);min-width:160px;display:none;z-index:50;}
  .user-dropdown.open{display:block;}
  .user-dropdown a{display:block;padding:10px 16px;font-size:13px;color:var(--text);text-decoration:none;cursor:pointer;transition:background 0.1s;}
  .user-dropdown a:hover{background:var(--sand);}
  .user-dropdown a.danger{color:var(--red);}
  .user-dropdown hr{border:none;border-top:1px solid var(--border);}

  /* BODY */
  .main-body{flex:1;display:flex;overflow:hidden;}
  #sidebar{width:var(--sidebar-w);background:#F8F5F0;border-right:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;transition:width 0.22s ease,opacity 0.2s;overflow:hidden;}
  #sidebar.collapsed{width:0;opacity:0;}
  .sidebar-header{padding:14px 16px 10px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
  .sidebar-header span{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;}
  .new-chat-side{background:var(--teal);color:#fff;border:none;border-radius:7px;padding:5px 11px;font-size:12px;font-weight:600;cursor:pointer;transition:background 0.15s;}
  .new-chat-side:hover{background:#088078;}
  .session-list{flex:1;overflow-y:auto;padding:8px;}
  .session-list::-webkit-scrollbar{width:4px;}
  .session-list::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px;}
  .session-item{padding:9px 12px;border-radius:9px;cursor:pointer;transition:background 0.12s;margin-bottom:2px;display:flex;align-items:flex-start;gap:8px;}
  .session-item:hover{background:#EDEBE6;}
  .session-item.active{background:var(--teal-lt);}
  .session-item-icon{font-size:14px;flex-shrink:0;margin-top:1px;}
  .session-item-body{flex:1;min-width:0;}
  .session-title{font-size:13px;font-weight:500;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
  .session-meta{font-size:11px;color:var(--muted);margin-top:2px;}
  .session-delete{opacity:0;flex-shrink:0;background:none;border:none;color:var(--muted);cursor:pointer;font-size:14px;padding:0 2px;transition:opacity 0.15s,color 0.15s;}
  .session-item:hover .session-delete{opacity:1;}
  .session-delete:hover{color:var(--red);}
  .sidebar-empty{padding:24px 16px;text-align:center;font-size:13px;color:var(--muted);line-height:1.6;}

  /* CHAT */
  .chat-wrapper{flex:3;min-width:0;display:flex;flex-direction:column;overflow:hidden;}
  .disclaimer-bar{background:transparent;border-bottom:0.5px solid var(--border);padding:4px 16px;font-size:10px;color:var(--muted);text-align:center;flex-shrink:0;opacity:0.6;}
  .chat-container{flex:1;display:flex;flex-direction:column;width:100%;padding:0 20px;overflow:hidden;}
  .messages{flex:1;overflow-y:auto;padding:24px 0 16px;display:flex;flex-direction:column;gap:16px;scroll-behavior:smooth;}
  .messages::-webkit-scrollbar{width:6px;}
  .messages::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
  .welcome{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:12px;padding:40px 20px;}
  .welcome-icon{width:72px;height:72px;background:var(--teal-lt);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:32px;margin-bottom:4px;}
  .welcome h2{font-family:'Libre Baskerville',serif;font-size:22px;color:var(--navy);}
  .welcome p{font-size:14px;color:var(--muted);max-width:480px;line-height:1.7;}
  .welcome-chips{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;margin-top:8px;}
  .chip{background:var(--sand);border:1px solid var(--border);border-radius:20px;padding:8px 16px;font-size:13px;color:var(--muted);cursor:pointer;transition:background 0.15s,color 0.15s,border-color 0.15s;}
  .chip:hover{background:var(--teal-lt);border-color:var(--teal);color:var(--navy);}
  .msg-row{display:flex;align-items:flex-end;gap:10px;animation:fadeUp 0.3s ease;}
  @keyframes fadeUp{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
  .msg-row.user{flex-direction:row-reverse;}
  .avatar{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;}
  .avatar.ai{background:var(--teal-lt);color:var(--teal);font-weight:700;font-family:'Libre Baskerville',serif;}
  .avatar.user{background:var(--navy);color:#fff;font-size:12px;}
  .bubble{max-width:72%;padding:14px 18px;border-radius:18px;font-size:14px;line-height:1.7;}
  .bubble.ai{background:var(--bubble-ai);border:1px solid var(--border);border-bottom-left-radius:4px;color:var(--text);}
  .bubble.user{background:var(--bubble-user);color:#E8F0F8;border-bottom-right-radius:4px;}
  .msg-ts{font-size:10px;color:#C0B8AF;margin-top:4px;}
  .msg-row.user .msg-ts{text-align:right;}
  .tier-label{font-size:12px;font-weight:600;color:var(--muted);margin-bottom:6px;display:block;}
  .typing-bubble{background:var(--bubble-ai);border:1px solid var(--border);border-bottom-left-radius:4px;padding:14px 18px;border-radius:18px;display:flex;gap:4px;align-items:center;}
  .dot{width:7px;height:7px;border-radius:50%;background:var(--teal);opacity:0.6;animation:bounce 1.2s infinite ease-in-out;}
  .dot:nth-child(2){animation-delay:0.2s;}
  .dot:nth-child(3){animation-delay:0.4s;}
  @keyframes bounce{0%,80%,100%{transform:scale(0.8);opacity:.4;}40%{transform:scale(1.2);opacity:1;}}
  .input-area{border-top:1px solid var(--border);padding:14px 0 18px;flex-shrink:0;}
  .input-row{display:flex;gap:10px;align-items:flex-end;}
  .msg-input{flex:1;min-height:48px;max-height:160px;padding:12px 16px;border:1.5px solid var(--border);border-radius:12px;font-family:'DM Sans',sans-serif;font-size:14px;line-height:1.5;color:var(--text);background:#fff;resize:none;outline:none;transition:border-color 0.2s,box-shadow 0.2s;}
  .msg-input:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(10,123,116,0.1);}
  .msg-input::placeholder{color:#B0A898;}
  .send-btn{width:48px;height:48px;background:var(--navy);color:#fff;border:none;border-radius:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background 0.2s,transform 0.1s;flex-shrink:0;}
  .send-btn:hover:not(:disabled){background:#162F52;}
  .send-btn:active:not(:disabled){transform:scale(0.95);}
  .send-btn:disabled{background:#8FA8BF;cursor:not-allowed;}
  .send-btn svg{width:20px;height:20px;}
  .input-hint{font-size:11px;color:var(--muted);margin-top:6px;}
  .input-controls{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;}
  .session-id{font-size:11px;color:#C0B8AF;font-family:monospace;}
  .new-chat-btn{background:none;border:1px solid var(--border);border-radius:8px;padding:6px 14px;font-size:12px;color:var(--muted);cursor:pointer;transition:border-color 0.15s,color 0.15s;}
  .new-chat-btn:hover{border-color:var(--teal);color:var(--teal);}
  .session-loading{display:none;align-items:center;justify-content:center;gap:10px;padding:32px;font-size:14px;color:var(--muted);}
  .session-loading.visible{display:flex;}
  .spin{width:18px;height:18px;border:2px solid var(--border);border-top-color:var(--teal);border-radius:50%;animation:spin 0.7s linear infinite;}
  @keyframes spin{to{transform:rotate(360deg);}}
  /* ── RISK PANEL ─────────────────────────────────────────────── */
  #riskPanel{flex:2;min-width:0;background:#F8F5F0;border-left:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;transition:flex 0.22s ease,opacity 0.22s;overflow:hidden;}
  #riskPanel.hidden{flex:0;min-width:0;max-width:0;opacity:0;pointer-events:none;overflow:hidden;}
  .rp-header{padding:14px 18px 12px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
  .rp-header span{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;}
  .rp-close{background:none;border:none;color:var(--muted);cursor:pointer;font-size:17px;padding:0 2px;line-height:1;}
  .rp-body{flex:1;overflow-y:auto;padding:18px 16px;}
  .rp-body::-webkit-scrollbar{width:5px;}
  .rp-body::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
  .rp-idle{text-align:center;padding:40px 16px;font-size:13px;color:var(--muted);line-height:1.8;}
  .rp-idle .idle-icon{font-size:36px;margin-bottom:12px;}

  /* tier badge */
  .rp-tier{text-align:center;padding:14px 0 10px;}
  .rp-tier-label{font-size:20px;font-weight:700;margin-bottom:5px;font-family:'Libre Baskerville',serif;}
  .rp-tier-sub{font-size:12px;color:var(--muted);}
  .tier-color-LOW{color:#065F46;}
  .tier-color-WATCH{color:#5B21B6;}
  .tier-color-MODERATE{color:#1E40AF;}
  .tier-color-HIGH{color:#92400E;}
  .tier-color-CRITICAL_EMERGENCY{color:#B91C1C;}

  /* sections */
  .rp-section-title{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;margin:16px 0 8px;}
  .feature-list{display:flex;flex-direction:column;gap:6px;}
  .feature-chip{font-size:13px;padding:7px 12px;border-radius:8px;background:#fff;border:0.5px solid var(--border);color:var(--text);line-height:1.5;border-left:3px solid var(--teal);}
  .workup-list{display:flex;flex-direction:column;gap:6px;}
  .workup-item{font-size:12px;color:var(--text);padding:5px 0 5px 12px;border-left:2px solid var(--border);line-height:1.6;}
  .action-box{background:#fff;border:1px solid var(--border);border-radius:10px;padding:14px 16px;font-size:13px;color:var(--text);line-height:1.7;margin-top:14px;}

  /* CHANGE PASSWORD MODAL */
  #changePwOverlay{position:fixed;inset:0;background:rgba(11,31,58,0.7);backdrop-filter:blur(4px);display:none;align-items:center;justify-content:center;z-index:200;}
  #changePwOverlay.open{display:flex;}
  .changepw-card{background:#fff;border-radius:16px;padding:32px 36px;width:380px;max-width:95vw;box-shadow:0 16px 48px rgba(0,0,0,0.25);}
  .changepw-card h3{font-family:'Libre Baskerville',serif;font-size:18px;color:var(--navy);margin-bottom:20px;}
  .changepw-error{background:#FEE2E2;border:1px solid #FECACA;border-radius:8px;padding:9px 14px;font-size:13px;color:#B91C1C;margin-bottom:14px;display:none;}
  .changepw-success{background:#D1FAE5;border:1px solid #6EE7B7;border-radius:8px;padding:9px 14px;font-size:13px;color:#065F46;margin-bottom:14px;display:none;}
  .changepw-cancel{width:100%;padding:10px;background:none;border:1.5px solid var(--border);border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--muted);cursor:pointer;margin-top:8px;transition:background 0.15s;}
  .changepw-cancel:hover{background:var(--sand);}
  @media(max-width:768px){
    header{padding:10px 12px;gap:8px;}
    .header-text h1{font-size:15px;}
    .header-text p{display:none;}
    .model-badge{display:none;}
    .nav-link{display:none;}
    .user-name{display:none;}
    .bubble{max-width:88%;font-size:13px;}
    .chat-container{padding:0 8px;}
    #sidebar{position:absolute;height:calc(100% - 59px);z-index:20;box-shadow:4px 0 16px rgba(0,0,0,.15);}
    .input-area{padding:10px 0 14px;}
    .msg-input{font-size:14px;padding:10px 14px;}
    .send-btn{width:44px;height:44px;}
    .input-hint{display:none;}
    .disclaimer-bar{font-size:10px;padding:3px 10px;}
  }
  @media(max-width:420px){
    .bubble{max-width:95%;}
    .avatar{width:28px;height:28px;font-size:12px;}
    header{padding:8px 10px;}
  }
  /* Mobile input fixes β€” prevent iOS zoom on focus */
  /* ── RISK PANEL ─────────────────────────────────────────────── */
  #riskPanel{flex:2;min-width:0;background:#F8F5F0;border-left:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;transition:flex 0.22s ease,opacity 0.22s;overflow:hidden;}
  #riskPanel.hidden{flex:0;min-width:0;max-width:0;opacity:0;pointer-events:none;overflow:hidden;}
  .rp-header{padding:14px 18px 12px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
  .rp-header span{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;}
  .rp-close{background:none;border:none;color:var(--muted);cursor:pointer;font-size:17px;padding:0 2px;line-height:1;}
  .rp-body{flex:1;overflow-y:auto;padding:18px 16px;}
  .rp-body::-webkit-scrollbar{width:5px;}
  .rp-body::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
  .rp-idle{text-align:center;padding:40px 16px;font-size:13px;color:var(--muted);line-height:1.8;}
  .rp-idle .idle-icon{font-size:36px;margin-bottom:12px;}

  /* tier badge */
  .rp-tier{text-align:center;padding:14px 0 10px;}
  .rp-tier-label{font-size:20px;font-weight:700;margin-bottom:5px;font-family:'Libre Baskerville',serif;}
  .rp-tier-sub{font-size:12px;color:var(--muted);}
  .tier-color-LOW{color:#065F46;}
  .tier-color-WATCH{color:#5B21B6;}
  .tier-color-MODERATE{color:#1E40AF;}
  .tier-color-HIGH{color:#92400E;}
  .tier-color-CRITICAL_EMERGENCY{color:#B91C1C;}

  /* sections */
  .rp-section-title{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;margin:16px 0 8px;}
  .feature-list{display:flex;flex-direction:column;gap:6px;}
  .feature-chip{font-size:13px;padding:7px 12px;border-radius:8px;background:#fff;border:0.5px solid var(--border);color:var(--text);line-height:1.5;border-left:3px solid var(--teal);}
  .workup-list{display:flex;flex-direction:column;gap:6px;}
  .workup-item{font-size:12px;color:var(--text);padding:5px 0 5px 12px;border-left:2px solid var(--border);line-height:1.6;}
  .action-box{background:#fff;border:1px solid var(--border);border-radius:10px;padding:14px 16px;font-size:13px;color:var(--text);line-height:1.7;margin-top:14px;}

  @media(max-width:768px){
    .msg-input{font-size:16px !important;}
    .send-btn{width:44px;height:44px;}
    .header-text p{display:none;}
    .model-badge{display:none;}
    .nav-link{display:none;}
    body{-webkit-text-size-adjust:100%;}
  }
  .tier-color-LOW{color:#065F46;}
  .tier-color-WATCH{color:#5B21B6;}
  .tier-color-MODERATE{color:#1E40AF;}
  .tier-color-HIGH{color:#92400E;}
  .tier-color-CRITICAL_EMERGENCY{color:#B91C1C;}


</style>
</head>
<body>

<!-- AUTH OVERLAY -->
<div id="authOverlay">
  <div class="auth-card">
    <div class="auth-logo">
      <div class="auth-logo-mark">AQ</div>
      <div><h2>AxonIQ</h2><p>AI-Powered MS Diagnostic Assistant β€” Sign in to continue</p></div>
    </div>
    <div class="auth-tabs">
      <button class="auth-tab active" id="tabLogin" onclick="switchTab('login')">Sign In</button>
      <button class="auth-tab" id="tabRegister" onclick="switchTab('register')">Register</button>
    </div>
    <div id="authError" class="auth-error"></div>
    <div class="auth-field auth-register-only" id="fieldUsername">
      <label>Username</label>
      <input type="text" id="authUsername" placeholder="e.g. dr_smith" autocomplete="username">
    </div>
    <div class="auth-field">
      <label id="emailLabel">Email or Username</label>
      <input type="text" id="authEmail" placeholder="your@email.com" autocomplete="email">
    </div>
    <div class="auth-field">
      <label>Password</label>
      <input type="password" id="authPassword" placeholder="β€’β€’β€’β€’β€’β€’β€’β€’" autocomplete="current-password">
    </div>
    <button class="auth-btn" id="authSubmitBtn" onclick="submitAuth()">Sign In</button>
    <p id="forgotLink" style="text-align:center;margin-top:12px;font-size:13px;color:var(--muted);">
      Forgot your password?
      <a onclick="showForgotPassword()" style="color:var(--teal);cursor:pointer;font-weight:500;">Reset it here</a>
    </p>
  </div>
</div>

<!-- APP SHELL -->
<div id="appShell">
  <header>
    <button class="sidebar-toggle" onclick="toggleSidebar()">☰</button>
    <div class="logo-mark">AQ</div>
    <div class="header-text">
      <h1>AxonIQ</h1>
      <p>AI-Powered MS Diagnostic Assistant Β· Powered by Llama 3.1 Β· RAG + NegEx</p>
    </div>
    <div class="header-right">
      <span class="model-badge">πŸ€– Agentic AI</span>
      <div class="user-pill" onclick="toggleUserMenu()">
        <div class="user-avatar" id="headerAvatar">?</div>
        <span class="user-name" id="headerUsername">…</span>
        <div class="user-dropdown" id="userDropdown">
          <a onclick="newChat()">οΌ‹ New Chat</a>
          <hr>
          <a onclick="showChangePassword()">πŸ”‘ Change Password</a>
          <a onclick="signOut()" class="danger">Sign Out</a>
        </div>
      </div>
    </div>
  </header>

  <div class="main-body">
    <div id="sidebar">
      <div class="sidebar-header">
        <span>Chat History</span>
        <button class="new-chat-side" onclick="newChat()">+ New</button>
      </div>
      <div class="session-list" id="sessionList">
        <div class="sidebar-empty" id="sidebarEmpty">No conversations yet.<br>Start a new chat!</div>
      </div>
    </div>

    <!-- RISK PANEL -->
    <div id="riskPanel" class="hidden">
      <div class="rp-header">
        <span>MS Risk Analysis</span>
        <button class="rp-close" onclick="closeRiskPanel()" title="Close">βœ•</button>
      </div>
      <div class="rp-body" id="riskBody">
        <div class="rp-idle" id="riskIdle">
          <div class="idle-icon">🧠</div>
          Describe your symptoms and the risk analysis will appear here automatically.
        </div>
        <div id="riskContent" style="display:none;">
          <div class="rp-tier" id="rpTier">
            <div class="rp-tier-label" id="rpTierLabel"></div>
            <div class="rp-tier-sub" id="rpTierSub"></div>
          </div>
          <div id="rpFeaturesSection" style="display:none;">
            <div class="rp-section-title">Detected Symptoms</div>
            <div class="feature-list" id="rpFeatureList"></div>
          </div>
          <div id="rpWorkupSection" style="display:none;">
            <div class="rp-section-title">Recommended Workup</div>
            <div class="workup-list" id="rpWorkupList"></div>
          </div>
          <div class="action-box" id="rpActionBox" style="display:none;"></div>
        </div>
      </div>
    </div>

    <div class="chat-wrapper">
      <div class="disclaimer-bar">Clinical decision support only β€” not a diagnosis</div>
      <div class="chat-container">
        <div class="messages" id="messages">
          <div class="session-loading" id="sessionLoading">
            <div class="spin"></div> Loading conversation…
          </div>
          <div class="welcome" id="welcome">
            <div class="welcome-icon">🧠</div>
            <h2>MS Clinical AI Assistant</h2>
            <p>Describe your neurological symptoms in plain language. I will conduct a structured clinical interview, identify MS-specific patterns, and recommend the appropriate workup.</p>
            <div class="welcome-chips">
              <div class="chip" onclick="sendChip('I have been having blurry vision in my left eye for 3 days and pain when I move my eye.')">πŸ‘οΈ Vision symptoms</div>
              <div class="chip" onclick="sendChip('Every time I bend my neck forward I get an electric shock running down my spine.')">⚑ Lhermitte sign</div>
              <div class="chip" onclick="sendChip('I woke up seeing double and my eyes feel jiggly. I also feel like I am on a boat when walking.')">πŸ‘€ Double vision + balance</div>
              <div class="chip" onclick="sendChip('I have numbness and tingling in my right arm and leg that started 2 days ago.')">🦾 Numbness / tingling</div>
              <div class="chip" onclick="sendChip('I feel a tight squeezing band around my chest like a corset being pulled tight.')">πŸŽ—οΈ MS Hug</div>
            </div>
          </div>
        </div>
        <div class="input-area">
          <div class="input-controls">
            <span class="session-id" id="sessionLabel"></span>
            <button class="new-chat-btn" onclick="newChat()">+ New Chat</button>
          </div>
          <div class="input-row">
            <textarea class="msg-input" id="msgInput" placeholder="Describe your symptoms… (Enter to send, Shift+Enter for new line)" rows="1"></textarea>
            <button class="send-btn" id="sendBtn" onclick="sendMessage()">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"></line>
                <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
const API = window.location.origin;
let authToken   = localStorage.getItem('nc_token') || null;
let currentUser = JSON.parse(localStorage.getItem('nc_user') || 'null');
let sessionId   = null;
let isWaiting   = false;
let currentTab  = 'login';

// Bootstrap
window.addEventListener('DOMContentLoaded', () => {
  document.getElementById('authPassword').addEventListener('keydown', e => { if(e.key==='Enter') submitAuth(); });
  if (authToken && currentUser) showApp();
});

// ── Auth ──
function switchTab(tab) {
  currentTab = tab;
  document.getElementById('tabLogin').classList.toggle('active', tab==='login');
  document.getElementById('tabRegister').classList.toggle('active', tab==='register');
  document.getElementById('authSubmitBtn').textContent = tab==='login' ? 'Sign In' : 'Create Account';
  document.querySelectorAll('.auth-register-only').forEach(el => el.style.display = tab==='register' ? 'block' : 'none');
  document.getElementById('emailLabel').textContent = tab==='login' ? 'Email or Username' : 'Email';
  clearAuthError();
  const fl = document.getElementById('forgotLink');
  if (fl) fl.style.display = tab==='login' ? 'block' : 'none';
}

function showAuthError(msg) { const e=document.getElementById('authError'); e.textContent=msg; e.style.display='block'; }
function clearAuthError()   { document.getElementById('authError').style.display='none'; }

async function submitAuth() {
  clearAuthError();
  const btn = document.getElementById('authSubmitBtn');
  btn.disabled = true;
  const email    = document.getElementById('authEmail').value.trim();
  const password = document.getElementById('authPassword').value;
  const username = document.getElementById('authUsername').value.trim();
  if (!email || !password) { showAuthError('Please fill in all fields.'); btn.disabled=false; return; }
  if (currentTab==='register' && !username) { showAuthError('Please enter a username.'); btn.disabled=false; return; }
  try {
    let res;
    if (currentTab==='register') {
      res = await fetch(`${API}/auth/register`, {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ username, email, password }),
      });
    } else {
      const form = new URLSearchParams();
      form.append('username', email);
      form.append('password', password);
      res = await fetch(`${API}/auth/login`, {
        method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: form,
      });
    }
    let data;
    try { data = await res.json(); } catch { throw new Error(`Server error ${res.status}`); }
    if (!res.ok) {
      // data.detail can be a string OR a list of validation error objects
      let errMsg = 'Authentication failed';
      if (data.detail) {
        if (typeof data.detail === 'string') {
          errMsg = data.detail;
        } else if (Array.isArray(data.detail)) {
          errMsg = data.detail.map(e => e.msg || JSON.stringify(e)).join(', ');
        } else {
          errMsg = JSON.stringify(data.detail);
        }
      }
      throw new Error(errMsg);
    }
    authToken   = data.access_token;
    currentUser = { id: data.user_id, username: data.username };
    localStorage.setItem('nc_token', authToken);
    localStorage.setItem('nc_user', JSON.stringify(currentUser));
    showApp();
  } catch(err) { showAuthError(err.message); }
  finally { btn.disabled = false; }
}

function signOut() {
  localStorage.removeItem('nc_token'); localStorage.removeItem('nc_user');
  authToken=null; currentUser=null; sessionId=null;
  document.getElementById('appShell').classList.remove('visible');
  document.getElementById('authOverlay').style.display='flex';
  clearMessages();
}

// ── Shell ──
function showApp() {
  document.getElementById('authOverlay').style.display='none';
  document.getElementById('appShell').classList.add('visible');
  document.getElementById('headerUsername').textContent = currentUser.username;
  document.getElementById('headerAvatar').textContent   = currentUser.username[0].toUpperCase();
  loadSessionList();
}

function toggleUserMenu() { document.getElementById('userDropdown').classList.toggle('open'); }
document.addEventListener('click', e => { if (!e.target.closest('.user-pill')) document.getElementById('userDropdown').classList.remove('open'); });
function toggleSidebar() { document.getElementById('sidebar').classList.toggle('collapsed'); }

// ── Session list ──
async function loadSessionList() {
  try {
    const res = await authFetch('/user/sessions');
    const data = await res.json();
    renderSessionList(data.sessions || []);
  } catch(e) { console.error(e); }
}

function renderSessionList(sessions) {
  const list  = document.getElementById('sessionList');
  const empty = document.getElementById('sidebarEmpty');
  list.querySelectorAll('.session-item').forEach(el => el.remove());
  if (!sessions.length) { empty.style.display='block'; return; }
  empty.style.display='none';
  sessions.forEach(s => {
    const item = document.createElement('div');
    item.className = 'session-item' + (s.session_uuid===sessionId ? ' active' : '');
    item.dataset.uuid = s.session_uuid;
    const ts = new Date(s.updated_at).toLocaleDateString(undefined,{month:'short',day:'numeric'});
    item.innerHTML = `
      <div class="session-item-icon">πŸ’¬</div>
      <div class="session-item-body">
        <div class="session-title">${escapeHtml(s.title||'Chat')}</div>
        <div class="session-meta">${ts}</div>
      </div>
      <button class="session-delete" onclick="deleteSession(event,'${s.session_uuid}')">βœ•</button>`;
    item.addEventListener('click', () => loadSession(s.session_uuid));
    list.appendChild(item);
  });
}

async function loadSession(uuid) {
  if (uuid===sessionId) return;
  sessionId = uuid;
  document.querySelectorAll('.session-item').forEach(el => el.classList.toggle('active', el.dataset.uuid===uuid));
  clearMessages();
  const loading = document.getElementById('sessionLoading');
  loading.classList.add('visible');
  try {
    const res  = await authFetch(`/session/${uuid}/history`);
    const data = await res.json();
    loading.classList.remove('visible');
    if (data.messages && data.messages.length) {
      document.getElementById('welcome').style.display='none';
      data.messages.forEach(m => addBubble(m.role==='human'?'user':'ai', m.content, m.created_at));
      resetRiskPanel();
      const humanText = data.messages.filter(m=>m.role==='human').map(m=>m.content).join(' ');
      if (humanText.trim().length > 8) scheduleRiskUpdate(humanText);
    }
  } catch(e) { loading.classList.remove('visible'); }
  document.getElementById('sessionLabel').textContent = `Session: ${uuid.slice(0,8)}…`;
}

async function deleteSession(e, uuid) {
  e.stopPropagation();
  if (!confirm('Delete this conversation?')) return;
  await authFetch(`/session/${uuid}`, {method:'DELETE'}).catch(()=>{});
  if (sessionId===uuid) { sessionId=null; clearMessages(); }
  loadSessionList();
}

// ── Chat ──
const input = document.getElementById('msgInput');
input.addEventListener('input', () => { input.style.height='auto'; input.style.height=Math.min(input.scrollHeight,160)+'px'; });
input.addEventListener('keydown', e => { if (e.key==='Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });

function sendChip(text) { input.value=text; sendMessage(); }

async function sendMessage() {
  const text = input.value.trim();
  if (!text || isWaiting || !authToken) return;
  isWaiting = true;
  input.value = ''; input.style.height='auto';
  document.getElementById('sendBtn').disabled = true;
  document.getElementById('welcome').style.display='none';
  addBubble('user', text, new Date().toISOString());
  scheduleRiskUpdate(text);
  const typing = addTyping();
  try {
    const res = await authFetch('/chat', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ message: text, session_id: sessionId }),
    });
    if (res.status===401) { signOut(); return; }
    if (!res.ok) { const err=await res.json().catch(()=>{}); throw new Error(err.detail||`Error ${res.status}`); }
    const data = await res.json();
    sessionId = data.session_id;
    document.getElementById('sessionLabel').textContent = `Session: ${sessionId.slice(0,8)}…`;
    typing.remove();
    addBubble('ai', data.response, new Date().toISOString());
    loadSessionList();
    // Re-analyze with full accumulated text after every AI response
    rebuildRiskFromHistory();
  } catch(err) {
    typing.remove();
    addBubble('ai', `⚠️ Error: ${err.message}`, new Date().toISOString());
  } finally {
    isWaiting=false;
    document.getElementById('sendBtn').disabled=false;
    input.focus();
  }
}

function newChat() {
  sessionId=null;
  clearMessages();
  resetRiskPanel();
  document.getElementById('sessionLabel').textContent='';
  document.querySelectorAll('.session-item').forEach(el => el.classList.remove('active'));
  loadSessionList();
  input.focus();
}

function clearMessages() {
  document.getElementById('messages').querySelectorAll('.msg-row').forEach(el => el.remove());
  document.getElementById('welcome').style.display='flex';
}

function addBubble(role, text, timestamp) {
  const msgs = document.getElementById('messages');
  const row = document.createElement('div');
  row.className = `msg-row ${role}`;
  const avatar = document.createElement('div');
  avatar.className = `avatar ${role}`;
  avatar.textContent = role==='ai' ? 'AQ' : (currentUser ? currentUser.username[0].toUpperCase() : 'U');
  const inner = document.createElement('div');
  const bubble = document.createElement('div');
  bubble.className = `bubble ${role}`;
  bubble.innerHTML = formatMessage(text);
  const ts = document.createElement('div');
  ts.className = 'msg-ts';
  ts.textContent = formatTimestamp(timestamp);
  inner.appendChild(bubble); inner.appendChild(ts);
  row.appendChild(avatar); row.appendChild(inner);
  msgs.appendChild(row); msgs.scrollTop=msgs.scrollHeight;
  return row;
}

function addTyping() {
  const msgs = document.getElementById('messages');
  const row=document.createElement('div'); row.className='msg-row ai';
  const av=document.createElement('div'); av.className='avatar ai'; av.textContent='AQ';
  const b=document.createElement('div'); b.className='typing-bubble';
  b.innerHTML='<div class="dot"></div><div class="dot"></div><div class="dot"></div>';
  row.appendChild(av); row.appendChild(b); msgs.appendChild(row); msgs.scrollTop=msgs.scrollHeight;
  return row;
}

function formatTimestamp(iso) {
  if (!iso) return '';
  try {
    const d=new Date(iso), now=new Date();
    const sameDay = d.toDateString()===now.toDateString();
    return sameDay
      ? d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})
      : d.toLocaleDateString([],{month:'short',day:'numeric'})+' '+d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
  } catch { return ''; }
}

function formatMessage(text) {
  let html = escapeHtml(text);
  // Bold markdown **text**
  html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  // Paragraphs and line breaks
  html = html.replace(/\n\n/g, '</p><p>');
  html = html.replace(/\n/g, '<br>');
  // Bold key clinical terms β€” word boundaries only, no mid-word replacement
  ['MRI','lumbar puncture','oligoclonal bands','optic neuritis',
   'Lhermitte','Uhthoff','neurology referral'
  ].forEach(kw => {
    const re = new RegExp('(?<![\\w>])' + kw.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + '(?![\\w<])', 'gi');
    html = html.replace(re, '<strong>$&</strong>');
  });
  return `<p>${html}</p>`;
}

function escapeHtml(t) { return t.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

function authFetch(path, opts={}) {
  return fetch(`${API}${path}`, { ...opts, headers:{ ...(opts.headers||{}), 'Authorization':`Bearer ${authToken}` } });
}
// ── Live Risk Panel ────────────────────────────────────────────────────────
let _riskDebounce = null;
let _riskText     = '';

const TIER_COLORS = {
  LOW:                '#065F46',
  WATCH:              '#5B21B6',
  MODERATE:           '#1E40AF',
  HIGH:               '#92400E',
  CRITICAL_EMERGENCY: '#B91C1C',
};

function closeRiskPanel() {
  document.getElementById('riskPanel').classList.add('hidden');
}

function resetRiskPanel() {
  _riskText = '';
  document.getElementById('riskPanel').classList.add('hidden');
  document.getElementById('riskIdle').style.display    = 'block';
  document.getElementById('riskContent').style.display = 'none';
}

function scheduleRiskUpdate(text) {
  if (!text || text.trim().length < 3) return;
  // Always append new text to accumulate full conversation context
  _riskText = (_riskText + ' ' + text).trim();
  clearTimeout(_riskDebounce);
  _riskDebounce = setTimeout(() => _fetchRisk(_riskText), 700);
}

function rebuildRiskFromHistory() {
  // Re-run analysis using ALL human messages in current conversation
  const msgs = document.getElementById('messages').querySelectorAll('.msg-row.user .bubble');
  const allText = Array.from(msgs).map(b => b.innerText || b.textContent).join(' ').trim();
  if (allText.length > 5) {
    _riskText = allText;
    _fetchRisk(_riskText);
  }
}

async function _fetchRisk(text) {
  try {
    const res = await fetch(`${API}/analyze`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text }),
    });
    if (!res.ok) return;
    renderRiskPanel(await res.json());
  } catch(e) { /* silent */ }
}

function renderRiskPanel(data) {
  const tier  = data.tier  || 'LOW';
  const color = TIER_COLORS[tier] || TIER_COLORS.LOW;
  document.getElementById('riskPanel').classList.remove('hidden');
  document.getElementById('riskIdle').style.display    = 'none';
  document.getElementById('riskContent').style.display = 'block';
  const lbl = document.getElementById('rpTierLabel');
  lbl.textContent = data.tier_label || tier;
  lbl.className   = 'rp-tier-label tier-color-' + tier;
  document.getElementById('rpTierSub').textContent = data.tier_subtitle || '';
  const feats = data.features || [];
  const fSec  = document.getElementById('rpFeaturesSection');
  if (feats.length) {
    fSec.style.display = 'block';
    document.getElementById('rpFeatureList').innerHTML =
      feats.map(f => `<div class="feature-chip">${escapeHtml(f.label)}</div>`).join('');
  } else { fSec.style.display = 'none'; }
  const workup = data.workup || [];
  const wSec   = document.getElementById('rpWorkupSection');
  if (workup.length) {
    wSec.style.display = 'block';
    document.getElementById('rpWorkupList').innerHTML =
      workup.map(w => `<div class="workup-item">${escapeHtml(w)}</div>`).join('');
  } else { wSec.style.display = 'none'; }
  const aBox = document.getElementById('rpActionBox');
  if (data.action && tier !== 'LOW') {
    aBox.style.display     = 'block';
    aBox.style.borderColor = color;
    aBox.innerHTML = `<strong>Recommended action:</strong><br>${escapeHtml(data.action)}`;
  } else { aBox.style.display = 'none'; }
}

// ── Change Password ───────────────────────────────────────────────────────
function showChangePassword() {
  document.getElementById('userDropdown').classList.remove('open');
  document.getElementById('changePwOverlay').classList.add('open');
  document.getElementById('pwOld').value='';
  document.getElementById('pwNew').value='';
  document.getElementById('pwConfirm').value='';
  document.getElementById('changePwError').style.display='none';
  document.getElementById('changePwSuccess').style.display='none';
  document.getElementById('pwOld').focus();
}
function hideChangePassword(){document.getElementById('changePwOverlay').classList.remove('open');}
async function submitChangePassword(){
  const oldPw=document.getElementById('pwOld').value;
  const newPw=document.getElementById('pwNew').value;
  const confPw=document.getElementById('pwConfirm').value;
  const errEl=document.getElementById('changePwError');
  const okEl=document.getElementById('changePwSuccess');
  errEl.style.display='none'; okEl.style.display='none';
  if(!oldPw||!newPw||!confPw){errEl.textContent='Please fill in all fields.';errEl.style.display='block';return;}
  if(newPw.length<6){errEl.textContent='New password must be at least 6 characters.';errEl.style.display='block';return;}
  if(newPw!==confPw){errEl.textContent='Passwords do not match.';errEl.style.display='block';return;}
  try{
    const res=await authFetch('/auth/change-password',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({old_password:oldPw,new_password:newPw})});
    const data=await res.json();
    if(!res.ok) throw new Error(data.detail||'Failed');
    okEl.textContent='βœ… Password changed successfully!';
    okEl.style.display='block';
    setTimeout(hideChangePassword,2000);
  }catch(e){errEl.textContent=e.message;errEl.style.display='block';}
}
document.addEventListener('DOMContentLoaded',()=>{
  const ov=document.getElementById('changePwOverlay');
  if(ov) ov.addEventListener('click',function(e){if(e.target===this)hideChangePassword();});
  const pc=document.getElementById('pwConfirm');
  if(pc) pc.addEventListener('keydown',e=>{if(e.key==='Enter')submitChangePassword();});
});

// ── Forgot Password ───────────────────────────────────────────────────────
let _fpResetToken = '';

function showForgotPassword() {
  document.getElementById('forgotOverlay').style.display = 'flex';
  document.getElementById('fpStep1').style.display = 'block';
  document.getElementById('fpStep2').style.display = 'none';
  document.getElementById('fpStep3').style.display = 'none';
  document.getElementById('fpError').style.display = 'none';
  document.getElementById('fpSuccess').style.display = 'none';
  document.getElementById('fpTitle').textContent = 'Reset Password';
  document.getElementById('fpSubtitle').textContent = 'Enter your registered email';
  document.getElementById('fpEmail').value = '';
  document.getElementById('fpOTP').value = '';
  document.getElementById('fpNewPw').value = '';
  document.getElementById('fpConfirmPw').value = '';
}

function hideForgotPassword() {
  document.getElementById('forgotOverlay').style.display = 'none';
}

function fpErr(msg) {
  const e = document.getElementById('fpError');
  e.textContent = msg; e.style.display = 'block';
  document.getElementById('fpSuccess').style.display = 'none';
}

function fpOk(msg) {
  const s = document.getElementById('fpSuccess');
  s.textContent = msg; s.style.display = 'block';
  document.getElementById('fpError').style.display = 'none';
}

async function fpSendOTP() {
  const email = document.getElementById('fpEmail').value.trim();
  if (!email) { fpErr('Please enter your email address.'); return; }
  document.getElementById('fpError').style.display = 'none';

  // Show loading state
  const btn = document.querySelector('#fpStep1 .auth-btn');
  const originalText = btn.textContent;
  btn.textContent = 'Sending...';
  btn.disabled = true;

  try {
    const res  = await fetch(`${API}/auth/forgot-password`, {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ email }),
    });

    if (!res.ok) {
      const err = await res.json().catch(() => ({}));
      fpErr(err.detail || 'Server error. Please try again.');
      return;
    }

    const data = await res.json();

    // Move to step 2
    document.getElementById('fpEmailShow').textContent = email;
    document.getElementById('fpStep1').style.display = 'none';
    document.getElementById('fpStep2').style.display = 'block';
    document.getElementById('fpTitle').textContent = 'Enter Reset Code';

    if (data.dev_mode && data.dev_error) {
      // Email not found in DB
      document.getElementById('fpStep2').style.display = 'none';
      document.getElementById('fpStep1').style.display = 'block';
      document.getElementById('fpTitle').textContent = 'Reset Password';
      fpErr(data.dev_error);
      return;
    } else if (data.dev_mode && data.dev_otp) {
      // Dev mode β€” auto fill OTP and show it prominently
      document.getElementById('fpSubtitle').textContent = 'Code shown below (email not configured)';
      document.getElementById('fpOTP').value = data.dev_otp;
      fpOk('Your reset code is: ' + data.dev_otp);
    } else {
      document.getElementById('fpSubtitle').textContent = 'Check your email inbox';
      fpOk('Code sent! Check your inbox and spam folder.');
    }
    document.getElementById('fpOTP').focus();

  } catch(e) {
    fpErr('Network error. Please check your connection and try again.');
  } finally {
    btn.textContent = originalText;
    btn.disabled = false;
  }
}

async function fpVerifyOTP() {
  const email = document.getElementById('fpEmail').value.trim();
  const otp   = document.getElementById('fpOTP').value.trim();
  if (!otp || otp.length < 6) { fpErr('Please enter the 6-digit code.'); return; }
  try {
    const res  = await fetch(`${API}/auth/verify-otp`, {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ email, otp }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.detail || 'Invalid or expired code');
    _fpResetToken = data.reset_token;
    document.getElementById('fpStep2').style.display = 'none';
    document.getElementById('fpStep3').style.display = 'block';
    document.getElementById('fpTitle').textContent = 'Set New Password';
    document.getElementById('fpSubtitle').textContent = 'Choose a new password';
    document.getElementById('fpSuccess').style.display = 'none';
    document.getElementById('fpNewPw').focus();
  } catch(e) { fpErr(e.message); }
}

async function fpSetPassword() {
  const newPw  = document.getElementById('fpNewPw').value;
  const confPw = document.getElementById('fpConfirmPw').value;
  if (!newPw || newPw.length < 6) { fpErr('Password must be at least 6 characters.'); return; }
  if (newPw !== confPw) { fpErr('Passwords do not match.'); return; }
  try {
    const res  = await fetch(`${API}/auth/reset-password`, {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ reset_token: _fpResetToken, new_password: newPw }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.detail || 'Reset failed');
    fpOk('Password reset successfully! Redirecting to login...');
    setTimeout(() => { hideForgotPassword(); switchTab('login'); }, 2000);
  } catch(e) { fpErr(e.message); }
}

document.addEventListener('DOMContentLoaded', () => {
  const ov = document.getElementById('forgotOverlay');
  if (ov) ov.addEventListener('click', e => { if (e.target === ov) hideForgotPassword(); });
  const otp = document.getElementById('fpOTP');
  if (otp) otp.addEventListener('keydown', e => { if (e.key === 'Enter') fpVerifyOTP(); });
  const cp = document.getElementById('fpConfirmPw');
  if (cp) cp.addEventListener('keydown', e => { if (e.key === 'Enter') fpSetPassword(); });
});

</script>
<!-- CHANGE PASSWORD MODAL -->
<div id="changePwOverlay">
  <div class="changepw-card">
    <h3>πŸ”‘ Change Password</h3>
    <div id="changePwError" class="changepw-error"></div>
    <div id="changePwSuccess" class="changepw-success"></div>
    <div class="auth-field"><label>Current Password</label><input type="password" id="pwOld" placeholder="Your current password"></div>
    <div class="auth-field"><label>New Password</label><input type="password" id="pwNew" placeholder="Min 6 characters"></div>
    <div class="auth-field"><label>Confirm New Password</label><input type="password" id="pwConfirm" placeholder="Repeat new password"></div>
    <button class="auth-btn" onclick="submitChangePassword()">Update Password</button>
    <button class="changepw-cancel" onclick="hideChangePassword()">Cancel</button>
  </div>
</div>

<!-- FORGOT PASSWORD MODAL -->
<div id="forgotOverlay" style="position:fixed;inset:0;background:rgba(11,31,58,0.85);backdrop-filter:blur(6px);display:none;align-items:center;justify-content:center;z-index:2000;">
  <div class="auth-card" style="max-height:90vh;overflow-y:auto;">
    <div class="auth-logo">
      <div class="auth-logo-mark">AQ</div>
      <div><h2 id="fpTitle">Reset Password</h2><p id="fpSubtitle">Enter your registered email</p></div>
    </div>
    <div id="fpError" class="auth-error"></div>
    <div id="fpSuccess" style="background:#D1FAE5;border:1px solid #6EE7B7;border-radius:8px;padding:10px 14px;font-size:13px;color:#065F46;margin-bottom:14px;display:none;"></div>

    <!-- Step 1: Email -->
    <div id="fpStep1">
      <div class="auth-field">
        <label>Email Address</label>
        <input type="email" id="fpEmail" placeholder="your@email.com">
      </div>
      <button class="auth-btn" onclick="fpSendOTP()">Send Reset Code</button>
      <button onclick="hideForgotPassword()" style="width:100%;padding:10px;background:none;border:1.5px solid var(--border);border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--muted);cursor:pointer;margin-top:8px;">Cancel</button>
    </div>

    <!-- Step 2: OTP -->
    <div id="fpStep2" style="display:none;">
      <p style="font-size:13px;color:var(--muted);margin-bottom:16px;line-height:1.7;">A 6-digit code was sent to <strong id="fpEmailShow"></strong>. Check your inbox and spam folder.</p>
      <div class="auth-field">
        <label>6-Digit Reset Code</label>
        <input type="text" id="fpOTP" placeholder="000000" maxlength="6" style="letter-spacing:8px;font-size:24px;text-align:center;font-family:monospace;">
      </div>
      <button class="auth-btn" onclick="fpVerifyOTP()">Verify Code</button>
      <p style="text-align:center;margin-top:10px;font-size:12px;color:var(--muted);">
        Didn't receive it? <a onclick="fpSendOTP()" style="color:var(--teal);cursor:pointer;">Resend</a>
        &nbsp;Β·&nbsp; <a onclick="hideForgotPassword()" style="color:var(--muted);cursor:pointer;">Cancel</a>
      </p>
    </div>

    <!-- Step 3: New Password -->
    <div id="fpStep3" style="display:none;">
      <div class="auth-field">
        <label>New Password</label>
        <input type="password" id="fpNewPw" placeholder="Min 6 characters">
      </div>
      <div class="auth-field">
        <label>Confirm New Password</label>
        <input type="password" id="fpConfirmPw" placeholder="Repeat new password">
      </div>
      <button class="auth-btn" onclick="fpSetPassword()">Set New Password</button>
    </div>
  </div>
</div>

</body>
</html>