Spaces:
Sleeping

File size: 60,075 Bytes
7937092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8417984
 
 
 
 
 
 
 
 
 
 
 
 
7937092
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Placebo AI | Medical Intelligence</title>
    <link rel="stylesheet" href="/static/style.css">
    <!-- Favicons -->
    <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png">
    <link rel="shortcut icon" href="/static/favicon.ico">
    <link rel="manifest" href="/static/site.webmanifest">
    <style>
        #loader-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: #0a0a0a;
            z-index: 9999;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: opacity 1s ease;
        }
        #main-content {
            opacity: 0;
            pointer-events: none;
            transition: opacity 1.5s ease;
        }

        /* Skeleton Loader Styles */
        .skeleton {
            background: linear-gradient(90deg, rgba(255,255,255,0.03) 25%, rgba(255,255,255,0.08) 50%, rgba(255,255,255,0.03) 75%);
            background-size: 200% 100%;
            animation: shimmer 1.5s infinite;
            border-radius: 8px;
            margin-bottom: 12px;
        }

        .skeleton-text { height: 18px; width: 100%; }
        .skeleton-title { height: 28px; width: 60%; margin-bottom: 20px; }
        .skeleton-short { height: 18px; width: 40%; }

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

        /* Side Drawer Styles */
        #side-drawer {
            position: fixed;
            top: 0;
            right: -400px;
            width: 350px;
            height: 100%;
            background: rgba(15, 23, 42, 0.95);
            backdrop-filter: blur(40px);
            border-left: 1px solid rgba(255, 255, 255, 0.1);
            z-index: 2000;
            transition: right 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            padding: 30px;
            box-shadow: -10px 0 30px rgba(0,0,0,0.5);
            display: flex;
            flex-direction: column;
        }

        #side-drawer.open { right: 0; }

        .drawer-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            padding-bottom: 15px;
        }

        .drawer-header h2 {
            font-family: 'Montserrat', sans-serif;
            font-size: 1.2rem;
            color: #10b981;
            letter-spacing: 2px;
            text-transform: uppercase;
        }

        #close-drawer {
            background: none;
            border: none;
            color: white;
            font-size: 2rem;
            cursor: pointer;
            opacity: 0.5;
            transition: opacity 0.2s;
        }

        #close-drawer:hover { opacity: 1; }

        .drawer-item {
            padding: 15px;
            background: rgba(255,255,255,0.05);
            border-radius: 12px;
            margin-bottom: 12px;
            cursor: pointer;
            transition: all 0.2s;
            border: 1px solid transparent;
            font-size: 0.9rem;
            line-height: 1.4;
        }

        .drawer-item:hover {
            background: rgba(16, 185, 129, 0.1);
            border-color: rgba(16, 185, 129, 0.3);
            transform: translateX(-5px);
        }

        .drawer-item .time {
            font-size: 0.7rem;
            opacity: 0.5;
            display: block;
            margin-top: 5px;
        }

        .drawer-content {
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow: hidden;
        }

        #drawer-items {
            flex: 1;
            overflow-y: auto;
            padding-right: 10px;
        }
        
        /* Custom Scrollbar for drawer */
        #drawer-items::-webkit-scrollbar {
            width: 6px;
        }
        #drawer-items::-webkit-scrollbar-track {
            background: rgba(255,255,255,0.02);
        }
        #drawer-items::-webkit-scrollbar-thumb {
            background: rgba(16, 185, 129, 0.3);
            border-radius: 3px;
        }
    </style>
</head>

<body>
    <!-- Spider Cursor Loader -->
    <div id="loader-container">
        <div style="position: absolute; text-align: center; pointer-events: none; z-index: 10;">
            <img src="/static/logo.png" width="80" height="80" style="filter: brightness(0) invert(1); margin-bottom: 20px; opacity: 0.8;">
            <div style="color: #10b981; font-family: 'Montserrat', sans-serif; letter-spacing: 4px; font-weight: 300; font-size: 14px;">INITIALIZING MEDICAL INTELLIGENCE...</div>
        </div>
    </div>

    <div id="main-content">
        <!-- Video Background Layer -->
        <div id="video-container">
            <video id="hero-video" autoplay loop muted playsinline>
                <source src="/static/bg_video.mp4" type="video/mp4">
            </video>
        </div>

        <!-- UI Content Layer -->
        <div class="content-layer">
            <nav>
                <div class="logo-area" style="display: flex; align-items: center; gap: 12px;">
                    <img src="/static/logo.png" width="32" height="32" alt="Logo" style="filter: brightness(0) invert(1);">
                    <a href="#" class="logo">Placebo AI</a>
                </div>
                <div class="menu-items">
                    <a href="/" class="menu-item">Home</a>
                    <a href="/architecture" class="menu-item">Architecture</a>
                    <a href="/capabilities" class="menu-item">Capabilities</a>
                    <a href="/docs" class="menu-item">Docs</a>
                    <a href="/about" class="menu-item">About</a>
                </div>
                <div class="nav-buttons" id="nav-auth-buttons">
                    <button class="btn-signup" id="signup-btn">Sign Up</button>
                    <button class="btn-login" id="login-btn">Log In</button>
                </div>
                <div class="nav-buttons" id="nav-user-buttons" style="display: none; align-items: center; gap: 16px;">
                    <span id="user-display-email" style="font-size: 13px; font-weight: 500; opacity: 0.85; color: var(--primary);">doctor@placebo.ai</span>
                    <button class="btn-login" id="logout-btn" style="width: auto; padding: 0 16px;">Log Out</button>
                </div>
            </nav>

            <main class="hero-content">
                <div class="badge-container">
                    <div class="badge-dark">
                        <svg class="icon" viewBox="0 0 24 24" fill="currentColor">
                            <path
                                d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                        </svg>
                        <span>Placebo AI</span>
                    </div>
                    <span class="badge-text">AI Medical Intelligence</span>
                </div>

                <h1>Next-Gen Medical AI</h1>
                <p class="subtitle">Transforms complex medical textbooks into accurate, citation-backed insights</p>

                <!-- Search / Chat Input Box -->
                <div class="search-container">
                    <div class="search-top">
                        <div class="credit-info">
                            <span>500/500 credits</span>
                            <button class="btn-upgrade">Upgrade</button>
                        </div>
                        <div class="ai-powered">
                            <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
                                <path
                                    d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z" />
                                <path d="M5 3v4" />
                                <path d="M19 17v4" />
                                <path d="M3 5h4" />
                                <path d="M17 19h4" />
                            </svg>
                            <span>Powered by Trinetra Labs</span>
                        </div>
                    </div>

                    <!-- Model Selector Toggle -->
                    <div class="model-selector">
                        <button class="model-btn active" data-mode="unified">
                            <span class="indicator-dot"></span>
                            Unified Library
                        </button>
                        <button class="model-btn" data-mode="mbbs">
                            <span class="indicator-dot"></span>
                            Dx(MBBS)
                        </button>
                        <button class="model-btn" data-mode="pharmacy">
                            <span class="indicator-dot"></span>
                            Rx(Pharmacy)
                        </button>
                    </div>

                    <div class="input-wrapper">
                        <input type="text" id="chat-input" placeholder="Type question..." autocomplete="off">
                        <button class="btn-submit" id="send-btn" aria-label="Send clinical query">
                            <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
                                <path d="m5 12 7-7 7 7" />
                                <path d="M12 19V5" />
                            </svg>
                        </button>
                    </div>

                    <div class="search-bottom">
                        <div class="action-buttons">
                            <button class="action-btn" id="history-btn">
                                <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <circle cx="12" cy="12" r="10" />
                                    <path d="M12 6v6l4 2" />
                                </svg>
                                History
                            </button>
                            <button class="action-btn" id="clear-btn">
                                <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <path d="M3 6h18" />
                                    <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
                                    <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
                                </svg>
                                Clear
                            </button>
                            <button class="action-btn" id="prompts-btn">
                                <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <circle cx="11" cy="11" r="8" />
                                    <path d="m21 21-4.3-4.3" />
                                </svg>
                                Prompts
                            </button>
                        </div>
                        <span class="char-counter" id="char-count">0/3,000</span>
                    </div>
                </div>

                <div class="app-disclaimer" style="text-align: center; font-size: 11px; color: rgba(255, 255, 255, 0.5); margin-top: 16px; font-family: 'Montserrat', sans-serif; max-width: 800px; margin-left: auto; margin-right: auto; line-height: 1.4;">
                    Disclaimer: All books used in this application belong to their respective authors and publishers. The author, publisher, and copyright owner reserve all rights. No ownership of book content is claimed by this application.
                </div>

                <!-- Response Panel -->
                <div id="response-panel">
                    <div class="response-content" id="response-text"></div>
                    <div class="source-container" id="source-list"></div>
                    
                    <!-- Feedback Loop -->
                    <div class="response-feedback" id="response-feedback" style="display: none;">
                        <span class="feedback-label">Was this helpful?</span>
                        <button class="feedback-btn" id="thumbs-up-btn" aria-label="Thumbs up: Helpful answer">
                            <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3" />
                            </svg>
                        </button>
                        <button class="feedback-btn" id="thumbs-down-btn" aria-label="Thumbs down: Unhelpful answer">
                            <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm12-3h3a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-3" />
                            </svg>
                        </button>
                    </div>

                    <!-- Disclaimer -->
                    <div class="response-disclaimer">
                        <svg class="icon disclaimer-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10" />
                            <line x1="12" y1="8" x2="12" y2="12" />
                            <line x1="12" y1="16" x2="12.01" y2="16" />
                        </svg>
                        <span>Placebo AI is a clinical retrieval system. Synthesized knowledge should be clinically verified.</span>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- Page Viewer Modal -->
    <div id="page-modal">
        <div class="modal-container">
            <div class="modal-header">
                <div class="modal-title" id="modal-title">Page Preview</div>
                <button class="close-modal" id="close-modal" aria-label="Close page preview modal">&times;</button>
            </div>
            <div class="modal-body">
                <img id="page-preview-img" src="" alt="Page Preview">
            </div>
        </div>
    </div>

    <!-- Authentication Modal Overlay -->
    <div id="auth-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); backdrop-filter: blur(20px); z-index: 3000; display: none; align-items: center; justify-content: center; padding: 20px;">
        <div class="modal-container" style="max-width: 400px; border: 1px solid rgba(16, 185, 129, 0.2); box-shadow: 0 0 30px rgba(16, 185, 129, 0.1);">
            <div class="modal-header">
                <div class="modal-title" id="auth-modal-title" style="font-family: 'Surgena', serif; font-size: 24px; color: var(--white);">Authentication</div>
                <button class="close-modal" id="close-auth-modal" aria-label="Close authentication modal" style="font-size: 28px;">&times;</button>
            </div>
            <div class="modal-body" style="background: transparent; display: flex; flex-direction: column; gap: 16px; padding: 24px;">
                <!-- Google OAuth Sign In Button -->
                <button id="google-auth-btn" style="width: 100%; height: 48px; background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.15); border-radius: 8px; display: flex; align-items: center; justify-content: center; gap: 12px; color: var(--white); font-family: 'Montserrat', sans-serif; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.1);" onmouseover="this.style.background='rgba(255,255,255,0.12)'; this.style.borderColor='rgba(16, 185, 129, 0.5)'" onmouseout="this.style.background='rgba(255,255,255,0.06)'; this.style.borderColor='rgba(255,255,255,0.15)'">
                    <svg width="20" height="20" viewBox="0 0 24 24" style="flex-shrink: 0;">
                        <path fill="#EA4335" d="M12 5.04c1.66 0 3.2.57 4.38 1.69l3.27-3.27C17.67 1.48 14.97 1 12 1 7.35 1 3.4 3.65 1.56 7.5l3.86 3C6.34 7.55 8.94 5.04 12 5.04z"/>
                        <path fill="#4285F4" d="M23.49 12.27c0-.81-.07-1.59-.2-2.34H12v4.43h6.44c-.28 1.47-1.11 2.71-2.36 3.55l3.65 2.84c2.13-1.97 3.36-4.87 3.36-8.48z"/>
                        <path fill="#FBBC05" d="M5.42 14.5c-.25-.74-.39-1.53-.39-2.35s.14-1.61.39-2.35L1.56 6.8C.56 8.79 0 11.01 0 12.35s.56 3.56 1.56 5.55l3.86-3z"/>
                        <path fill="#34A853" d="M12 23c3.24 0 5.97-1.07 7.96-2.91l-3.65-2.84c-1.01.68-2.31 1.09-3.96 1.09-3.06 0-5.66-2.51-6.58-5.46l-3.86 3C3.4 20.35 7.35 23 12 23z"/>
                    </svg>
                    Continue with Google
                </button>

                <div style="display: flex; align-items: center; justify-content: center; width: 100%; margin: 4px 0;">
                    <div style="flex: 1; height: 1px; background: rgba(255,255,255,0.08);"></div>
                    <span style="font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px; opacity: 0.5; color: var(--white); padding: 0 12px;">or email verification</span>
                    <div style="flex: 1; height: 1px; background: rgba(255,255,255,0.08);"></div>
                </div>

                <!-- OTP Step 1: Send Verification Code -->
                <div id="otp-step-1" style="display: flex; flex-direction: column; gap: 16px; width: 100%;">
                    <div style="display: flex; flex-direction: column; gap: 6px; width: 100%;">
                        <label style="font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; opacity: 0.8; color: var(--white); text-align: left;">Email Address</label>
                        <input type="email" id="auth-email" placeholder="doctor@placebo.ai" style="width: 100%; padding: 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; color: white; font-family: 'Montserrat', sans-serif; outline: none; transition: border-color 0.3s;" onfocus="this.style.borderColor='#10b981'" onblur="this.style.borderColor='rgba(255,255,255,0.1)'">
                    </div>
                    <button class="btn-signup" id="auth-send-otp-btn" style="width: 100%; height: 46px; font-size: 14px; margin-top: 4px;">Send Verification Code</button>
                </div>

                <!-- OTP Step 2: Verify 8-digit Code (Initially Hidden) -->
                <div id="otp-step-2" style="display: none; flex-direction: column; gap: 16px; width: 100%;">
                    <div style="display: flex; flex-direction: column; gap: 6px; width: 100%;">
                        <label style="font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; opacity: 0.8; color: var(--white); text-align: left;">8-Digit OTP Code</label>
                        <input type="text" id="auth-otp-code" placeholder="••••••••" maxlength="8" style="width: 100%; padding: 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; color: white; font-family: 'Montserrat', sans-serif; font-size: 20px; font-weight: 700; letter-spacing: 8px; text-align: center; outline: none; transition: border-color 0.3s;" onfocus="this.style.borderColor='#10b981'" onblur="this.style.borderColor='rgba(255,255,255,0.1)'">
                    </div>
                    <button class="btn-signup" id="auth-verify-otp-btn" style="width: 100%; height: 46px; font-size: 14px; margin-top: 4px;">Verify & Log In</button>
                    <div style="text-align: center; font-size: 12px; opacity: 0.7;">
                        <a href="#" id="auth-back-to-step1" style="color: var(--primary); text-decoration: none; font-weight: 600;">Go back to enter email</a>
                    </div>
                </div>

                <!-- Unified Authentication Message Output -->
                <div id="auth-message" style="text-align: center; font-size: 13px; font-weight: 500; margin-top: 4px; min-height: 18px; color: var(--primary); width: 100%;"></div>
            </div>
        </div>
    </div>

    <!-- Profession Selection Modal Overlay -->
    <div id="profession-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); backdrop-filter: blur(20px); z-index: 4000; display: none; align-items: center; justify-content: center; padding: 20px;">
        <div class="modal-container" style="max-width: 400px; border: 1px solid rgba(16, 185, 129, 0.2); box-shadow: 0 0 30px rgba(16, 185, 129, 0.1);">
            <div class="modal-header">
                <div class="modal-title" style="font-family: 'Surgena', serif; font-size: 24px; color: var(--white);">Welcome!</div>
            </div>
            <div class="modal-body" style="background: transparent; display: flex; flex-direction: column; gap: 16px; padding: 24px; text-align: center;">
                <p style="color: var(--white); opacity: 0.8; font-family: 'Montserrat', sans-serif; font-size: 14px; margin-bottom: 8px;">What best describes you?</p>
                <button class="profession-btn" data-mode="mbbs" style="width: 100%; padding: 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; color: white; font-family: 'Montserrat', sans-serif; font-weight: 600; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='rgba(16, 185, 129, 0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.05)'">MBBS Student / Doctor</button>
                <button class="profession-btn" data-mode="pharmacy" style="width: 100%; padding: 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; color: white; font-family: 'Montserrat', sans-serif; font-weight: 600; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='rgba(16, 185, 129, 0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.05)'">Pharmacy Student / Pharmacist</button>
                <button class="profession-btn" data-mode="unified" style="width: 100%; padding: 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; color: white; font-family: 'Montserrat', sans-serif; font-weight: 600; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='rgba(16, 185, 129, 0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.05)'">Unified (Both Domains)</button>
            </div>
        </div>
    </div>

    <!-- Side Drawer for History/Prompts -->
    <div id="side-drawer">
        <div class="drawer-content">
            <div class="drawer-header">
                <h2 id="drawer-title">History</h2>
                <button id="close-drawer">&times;</button>
            </div>
            <div id="drawer-items"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
    <script src="/static/spider-loader.js"></script>
    <script>
        // --- SUPABASE CLIENT INITIALIZATION ---
        let supabaseClient = null;
        let activeUser = null;
        let activeToken = null;

        async function initializeSupabase() {
            try {
                const response = await fetch("/config");
                const config = await response.json();
                const SUPABASE_URL = config.supabase_url;
                const SUPABASE_ANON_KEY = config.supabase_anon_key;

                if (window.supabase && typeof window.supabase.createClient === 'function' && SUPABASE_URL && SUPABASE_URL !== "https://your-project-id.supabase.co") {
                    // Wipe any old local storage sessions lingering from before this feature
                    for (let key in localStorage) {
                        if (key.startsWith('sb-') && key.endsWith('-auth-token')) {
                            localStorage.removeItem(key);
                        }
                    }
                    
                    supabaseClient = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
                        auth: {
                            persistSession: false // Forces logout on every page refresh
                        }
                    });
                    console.log("Supabase Client initialized with ephemeral sessions. Testing connectivity...");
                    
                    // Connection ping test with 2-second timeout
                    const pingPromise = supabaseClient.auth.getSession();
                    const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("Supabase connection timeout")), 2000));
                    
                    await Promise.race([pingPromise, timeoutPromise]);
                    console.log("Supabase connectivity verified successfully.");
                    
                    supabaseClient.auth.onAuthStateChange((event, session) => {
                        console.log("Auth State Changed Event:", event);
                        updateAuthState();
                    });
                } else {
                    console.warn("Supabase configuration is using placeholder credentials or offline.");
                }
            } catch (e) {
                console.warn("Failed to verify Supabase connectivity or load config.", e);
                supabaseClient = null;
            }
            // Sync current authentication state on load
            await updateAuthState();
        }

        async function updateAuthState() {
            const authButtons = document.getElementById('nav-auth-buttons');
            const userButtons = document.getElementById('nav-user-buttons');
            const displayEmail = document.getElementById('user-display-email');
            
            if (supabaseClient) {
                try {
                    const { data: { session } } = await supabaseClient.auth.getSession();
                    if (session) {
                        activeUser = session.user;
                        activeToken = session.access_token;
                    } else {
                        activeUser = null;
                        activeToken = null;
                    }
                } catch (err) {
                    console.error("Error fetching Supabase session:", err);
                }
            }
            
            if (activeUser) {
                authButtons.style.display = 'none';
                userButtons.style.display = 'flex';
                displayEmail.innerText = activeUser.email;
                
                let userDefaultMode = activeUser.user_metadata?.defaultMode;
                if (!userDefaultMode) {
                    document.getElementById('profession-modal').style.display = 'flex';
                } else {
                    activeMode = userDefaultMode;
                    updateModeButtons(activeMode);
                }
                
                // Dynamically update user limits
                const creditText = document.querySelector('.credit-info span');
                if (creditText) {
                    let userCredits = activeUser.user_metadata?.credits_remaining !== undefined ? activeUser.user_metadata.credits_remaining : 500;
                    if (userCredits > 500) userCredits = 500; // Cap grandfathered users at 500
                    creditText.innerText = `${userCredits}/500 credits`;
                }
            } else {
                authButtons.style.display = 'flex';
                userButtons.style.display = 'none';
                activeToken = null;
                const creditText = document.querySelector('.credit-info span');
                if (creditText) {
                    creditText.innerText = "Log in to check credits";
                }
            }
        }

        // Initialize state check
        window.addEventListener('DOMContentLoaded', () => {
            initializeSupabase();
        });

        const chatForm = document.getElementById('chat-form');
        const video = document.getElementById('hero-video');
        let opacity = 1;

        function setOpacity(val) {
            opacity = val;
            video.style.opacity = opacity;
        }

        if (video.readyState >= 1) {
            video.play();
            setOpacity(1);
        } else {
            video.addEventListener('loadedmetadata', () => {
                video.play();
                setOpacity(1);
            });
        }

        setTimeout(() => setOpacity(1), 2000);

        const chatInput = document.getElementById('chat-input');
        const sendBtn = document.getElementById('send-btn');
        const charCount = document.getElementById('char-count');
        const responsePanel = document.getElementById('response-panel');
        const responseText = document.getElementById('response-text');
        const sourceList = document.getElementById('source-list');
        const pageModal = document.getElementById('page-modal');
        const modalImg = document.getElementById('page-preview-img');
        const modalTitle = document.getElementById('modal-title');
        const closeModal = document.getElementById('close-modal');
        const clearBtn = document.getElementById('clear-btn');

        let activeMode = 'unified';
        
        function updateModeButtons(mode) {
            const buttons = document.querySelectorAll('.model-btn');
            buttons.forEach(b => {
                b.classList.remove('active');
                if (b.getAttribute('data-mode') === mode || (mode === 'unified' && b.getAttribute('data-mode') === 'all')) {
                    b.classList.add('active');
                }
            });
        }

        document.querySelectorAll('.profession-btn').forEach(btn => {
            btn.onclick = async () => {
                const mode = btn.getAttribute('data-mode');
                if (supabaseClient && activeUser) {
                    btn.innerText = "Saving...";
                    const { data, error } = await supabaseClient.auth.updateUser({
                        data: { defaultMode: mode }
                    });
                    if (!error) {
                        activeUser = data.user;
                        activeMode = mode;
                        updateModeButtons(mode);
                        document.getElementById('profession-modal').style.display = 'none';
                        
                        // Reset button text in case they log out and it re-shows
                        btn.innerText = mode === "mbbs" ? "MBBS Student / Doctor" : 
                                      (mode === "pharmacy" ? "Pharmacy Student / Pharmacist" : "Unified (Both Domains)");
                    }
                }
            };
        });

        const modelButtons = document.querySelectorAll('.model-btn');
        modelButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                modelButtons.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                activeMode = btn.getAttribute('data-mode');
            });
        });

        if (clearBtn) {
            clearBtn.addEventListener('click', (e) => {
                e.preventDefault();
                responseText.innerHTML = '';
                sourceList.innerHTML = '';
                responsePanel.style.display = 'none';
                chatInput.value = '';
                charCount.innerText = '0/3,000';
            });
        }

        chatInput.addEventListener('input', () => {
            charCount.innerText = `${chatInput.value.length}/3,000`;
        });

        const historyBtn = document.getElementById('history-btn');
        const promptsBtn = document.getElementById('prompts-btn');
        const sideDrawer = document.getElementById('side-drawer');
        const closeDrawer = document.getElementById('close-drawer');
        const drawerTitle = document.getElementById('drawer-title');
        const drawerItems = document.getElementById('drawer-items');

        const PREDEFINED_PROMPTS = [
            "Explain the clinical presentation, diagnosis, and surgical management of acute appendicitis.",
            "What are the histological features of a myocardial infarction across different time frames?",
            "Explain the mechanism of action, pharmacokinetics, and adverse effects of Aspirin.",
            "What is the principle behind Non-aqueous Titrations and which indicators are used?",
            "Explain Type II Diabetes Mellitus, including its pathophysiology and the pharmacological management using Metformin.",
            "Describe the physiological pathway of the Renin-Angiotensin-Aldosterone System (RAAS)."
        ];

        function saveToHistory(query, answer = '', sources = []) {
            const historyKey = activeUser ? `chat_history_${activeUser.id}` : 'chat_history_guest';
            let history = JSON.parse(localStorage.getItem(historyKey) || '[]');
            // Find if query exists, remove it (to bring to top)
            history = history.filter(h => h.query !== query);
            history.unshift({ 
                query, 
                answer, 
                sources,
                time: new Date().toLocaleString() 
            });
            history = history.slice(0, 20); // Keep last 20
            localStorage.setItem(historyKey, JSON.stringify(history));
        }

        function displayStoredResult(item) {
            const queryHTML = `<div style="font-size: 16px; font-weight: 500; color: white; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid rgba(255,255,255,0.1);"><span style="opacity: 0.5; font-size: 12px; display: block; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 1px;">You Asked:</span>${item.query}</div>`;
            
            let galleryHTML = '<div class="source-images-gallery" style="display: flex; gap: 10px; margin-top: 15px; overflow-x: auto; padding-bottom: 10px;">';
            sourceList.innerHTML = '';
            item.sources.forEach(src => {
                const tag = document.createElement('span');
                tag.className = 'source-tag';
                tag.innerText = `${src.book_name} (Pg ${src.page_number})`;
                tag.onclick = () => {
                    modalTitle.innerText = `${src.book_name} - Page ${src.page_number}`;
                    modalImg.src = `/page_image?path=${encodeURIComponent(src.image_path)}`;
                    pageModal.style.display = 'flex';
                };
                sourceList.appendChild(tag);
                
                galleryHTML += `
                    <div style="flex: 0 0 auto; width: 250px; border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 8px; overflow: hidden; background: rgba(0,0,0,0.2); cursor: pointer;" onclick="document.getElementById('modal-title').innerText='${src.book_name} - Page ${src.page_number}'; document.getElementById('modal-img').src='/page_image?path=${encodeURIComponent(src.image_path)}'; document.getElementById('page-modal').style.display='flex';">
                        <div style="font-size: 10px; color: var(--primary); padding: 5px 8px; border-bottom: 1px solid rgba(16, 185, 129, 0.2); font-weight: 600; text-transform: uppercase;">Exact Page Reference</div>
                        <img src="/page_image?path=${encodeURIComponent(src.image_path)}" style="width: 100%; height: auto; object-fit: contain; display: block;" alt="Reference Page">
                    </div>
                `;
            });
            galleryHTML += '</div>';
            
            responseText.innerHTML = queryHTML + DOMPurify.sanitize(marked.parse(item.answer)) + (item.sources.length > 0 ? galleryHTML : "");
            
            responsePanel.style.display = 'flex';
            chatInput.value = item.query;
            sideDrawer.classList.remove('open');
            window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
        }

        function openDrawer(type) {
            drawerItems.innerHTML = '';
            if (type === 'history') {
                drawerTitle.innerText = 'History';
                const historyKey = activeUser ? `chat_history_${activeUser.id}` : 'chat_history_guest';
                const history = JSON.parse(localStorage.getItem(historyKey) || '[]');
                if (history.length === 0) {
                    drawerItems.innerHTML = '<div style="opacity: 0.5; text-align: center; margin-top: 20px;">No history yet.</div>';
                }
                history.forEach(item => {
                    const el = document.createElement('div');
                    el.className = 'drawer-item';
                    el.innerHTML = `${item.query} <span class="time">${item.time}</span>`;
                    el.onclick = () => displayStoredResult(item);
                    drawerItems.appendChild(el);
                });
            } else {
                drawerTitle.innerText = 'Prompts';
                PREDEFINED_PROMPTS.forEach(prompt => {
                    const el = document.createElement('div');
                    el.className = 'drawer-item';
                    el.innerText = prompt;
                    el.onclick = () => {
                        chatInput.value = prompt;
                        sideDrawer.classList.remove('open');
                        handleSend();
                    };
                    drawerItems.appendChild(el);
                });
            }
            sideDrawer.classList.add('open');
        }

        historyBtn.onclick = () => openDrawer('history');
        promptsBtn.onclick = () => openDrawer('prompts');
        closeDrawer.onclick = () => sideDrawer.classList.remove('open');

        // --- AUTH OVERLAY CONTROLLERS ---
        const authModal = document.getElementById('auth-modal');
        const loginBtn = document.getElementById('login-btn');
        const signupBtn = document.getElementById('signup-btn');
        const closeAuthModal = document.getElementById('close-auth-modal');
        const authModalTitle = document.getElementById('auth-modal-title');
        
        const googleAuthBtn = document.getElementById('google-auth-btn');
        
        const otpStep1 = document.getElementById('otp-step-1');
        const authEmail = document.getElementById('auth-email');
        const authSendOtpBtn = document.getElementById('auth-send-otp-btn');
        
        const otpStep2 = document.getElementById('otp-step-2');
        const authOtpCode = document.getElementById('auth-otp-code');
        const authVerifyOtpBtn = document.getElementById('auth-verify-otp-btn');
        const authBackToStep1 = document.getElementById('auth-back-to-step1');
        
        const authMessage = document.getElementById('auth-message');
        const logoutBtn = document.getElementById('logout-btn');

        function resetAuthModal() {
            authMessage.innerText = '';
            authEmail.value = '';
            authOtpCode.value = '';
            otpStep1.style.display = 'flex';
            otpStep2.style.display = 'none';
        }

        function showAuthModal() {
            resetAuthModal();
            authModal.style.display = 'flex';
            if (!supabaseClient) {
                authMessage.style.color = '#eab308'; // Warning gold/yellow
                authMessage.innerText = 'Supabase server is offline (Error 521). Sandbox simulation mode active.';
            }
        }

        loginBtn.onclick = () => showAuthModal();
        signupBtn.onclick = () => showAuthModal();
        closeAuthModal.onclick = () => authModal.style.display = 'none';
        
        // Close auth modal when clicking outside content box
        authModal.onclick = (e) => {
            if (e.target === authModal) {
                authModal.style.display = 'none';
            }
        };

        // Go back to Step 1
        authBackToStep1.onclick = (e) => {
            e.preventDefault();
            authMessage.innerText = '';
            authOtpCode.value = '';
            otpStep1.style.display = 'flex';
            otpStep2.style.display = 'none';
        };

        // --- DISPOSABLE EMAIL CHECK ---
        function isDisposableEmail(email) {
            const disposableDomains = [
                'mailinator.com', 'tempmail.com', 'temp-mail.org', '10minutemail.com', 
                'yopmail.com', 'guerrillamail.com', 'dispostable.com', 'trashmail.com', 
                'getairmail.com', 'sharklasers.com', 'guerrillamailblock.com', 
                'guerrillamail.net', 'guerrillamail.org', 'guerrillamail.biz', 
                'tempmailo.com', 'generator.email', 'maildrop.cc', 'tempmail.dev',
                'tempmail.net', 'disposable.com', 'fakeinbox.com', 'disposablemail.com'
            ];
            const parts = email.split('@');
            if (parts.length < 2) return true;
            const domain = parts[1].toLowerCase().trim();
            return disposableDomains.includes(domain);
        }

        // --- GOOGLE OAUTH LOGIN TRIGGER ---
        googleAuthBtn.onclick = async () => {
            if (!supabaseClient) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = 'Authentication service is offline. Mock login is disabled.';
                return;
            }

            authMessage.style.color = '#10b981';
            authMessage.innerText = 'Redirecting to Google...';
            
            try {
                const { error } = await supabaseClient.auth.signInWithOAuth({
                    provider: 'google',
                    options: {
                        redirectTo: window.location.origin
                    }
                });
                if (error) throw error;
            } catch (err) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = err.message || 'OAuth redirection failed.';
            }
        };

        // --- PASSWORDLESS SEND EMAIL OTP TRIGGER ---
        authSendOtpBtn.onclick = async () => {
            const email = authEmail.value.trim();
            if (!email) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = 'Please enter a valid email address.';
                return;
            }

            if (isDisposableEmail(email)) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = 'Please use a valid personal, academic, or professional email address. Temporary email addresses are not supported.';
                return;
            }

            if (!supabaseClient) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = 'Authentication service is offline. Mock login is disabled.';
                return;
            }

            authSendOtpBtn.disabled = true;
            authMessage.style.color = '#10b981';
            authMessage.innerText = 'Sending verification code...';

            try {
                const { error } = await supabaseClient.auth.signInWithOtp({
                    email: email,
                    options: {
                        shouldCreateUser: true // Automatically sign up new users
                    }
                });
                if (error) throw error;
                
                authMessage.innerText = 'Verification code sent to your email!';
                setTimeout(() => {
                    authMessage.innerText = '';
                    otpStep1.style.display = 'none';
                    otpStep2.style.display = 'flex';
                    authOtpCode.focus();
                }, 1000);
            } catch (err) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = err.message || 'Failed to send OTP code.';
            } finally {
                authSendOtpBtn.disabled = false;
            }
        };

        // --- PASSWORDLESS VERIFY EMAIL OTP TRIGGER ---
        authVerifyOtpBtn.onclick = async () => {
            const email = authEmail.value.trim();
            const otpCode = authOtpCode.value.trim();
            if (!otpCode || otpCode.length !== 8) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = 'Please enter the 8-digit verification code.';
                return;
            }

            if (!supabaseClient) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = 'Authentication service is offline. Mock login is disabled.';
                return;
            }

            authVerifyOtpBtn.disabled = true;
            authMessage.style.color = '#10b981';
            authMessage.innerText = 'Verifying security code...';

            try {
                const { data, error } = await supabaseClient.auth.verifyOtp({
                    email: email,
                    token: otpCode,
                    type: 'email'
                });
                if (error) throw error;
                
                authMessage.innerText = 'Authentication successful!';
                setTimeout(() => {
                    authModal.style.display = 'none';
                    updateAuthState();
                }, 1000);
            } catch (err) {
                authMessage.style.color = '#ef4444';
                authMessage.innerText = err.message || 'Invalid or expired verification code.';
            } finally {
                authVerifyOtpBtn.disabled = false;
            }
        };

        logoutBtn.onclick = async () => {
            if (supabaseClient) {
                await supabaseClient.auth.signOut();
            } else {
                activeUser = null;
                activeToken = null;
                updateAuthState();
            }
        };

        async function handleSend() {
            if (!activeUser) {
                showAuthModal();
                return;
            }

            const message = chatInput.value.trim();
            if (!message) return;

            // Disable inputs while processing
            chatInput.disabled = true;
            sendBtn.disabled = true;
            document.querySelector('.input-wrapper').classList.add('disabled');

            // Hide feedback widget and reset its state
            const feedbackContainer = document.getElementById('response-feedback');
            const thumbsUpBtn = document.getElementById('thumbs-up-btn');
            const thumbsDownBtn = document.getElementById('thumbs-down-btn');
            if (feedbackContainer) feedbackContainer.style.display = 'none';
            if (thumbsUpBtn) thumbsUpBtn.classList.remove('active-up');
            if (thumbsDownBtn) thumbsDownBtn.classList.remove('active-down');

            saveToHistory(message);
            chatInput.value = '';
            charCount.innerText = '0/3,000';

            // --- CREDIT DEDUCTION LOGIC ---
            if (activeUser && supabaseClient) {
                let currentCredits = activeUser.user_metadata?.credits_remaining !== undefined ? activeUser.user_metadata.credits_remaining : 500;
                if (currentCredits > 500) currentCredits = 500; // Instantly scale legacy users down to new 500 limit
                
                if (currentCredits < 10) {
                    responsePanel.style.display = 'flex';
                    responseText.innerHTML = '<span style="color: #ef4444; padding: 20px; display: block; text-align: center;">Insufficient credits. You need at least 10 credits to perform a clinical search. Please upgrade your account.</span>';
                    chatInput.disabled = false;
                    sendBtn.disabled = false;
                    document.querySelector('.input-wrapper').classList.remove('disabled');
                    return;
                }
                
                let newCredits = Math.max(0, currentCredits - 10);
                
                // Optimistic UI update
                const creditText = document.querySelector('.credit-info span');
                if (creditText) creditText.innerText = `${newCredits}/500 credits`;
                
                // Background sync with Supabase User Metadata
                supabaseClient.auth.updateUser({
                    data: { credits_remaining: newCredits }
                }).then(({ data, error }) => {
                    if (!error && data.user) {
                        activeUser = data.user;
                    }
                });
            }

            responsePanel.style.display = 'flex';
            
            let modeDisplay = "Unified Library";
            if (activeMode === "mbbs") modeDisplay = "Dx(MBBS) Knowledge Base";
            if (activeMode === "pharmacy") modeDisplay = "Rx(Pharmacy) Knowledge Base";
            
            const queryHTML = `<div style="font-size: 16px; font-weight: 500; color: white; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid rgba(255,255,255,0.1);"><span style="opacity: 0.5; font-size: 12px; display: block; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 1px;">You Asked:</span>${message}</div>`;
            const badgeHTML = `<div style="font-size: 11px; color: var(--primary); font-weight: 600; letter-spacing: 1px; text-transform: uppercase; margin-bottom: 12px; border-left: 2px solid var(--primary); padding-left: 8px;">Response from ${modeDisplay}</div>`;
            
            responseText.innerHTML = queryHTML + badgeHTML + `
                <div class="skeleton skeleton-title"></div>
                <div class="skeleton skeleton-text"></div>
                <div class="skeleton skeleton-text"></div>
                <div class="skeleton skeleton-short"></div>
            `;
            sourceList.innerHTML = '';

            try {
                const headers = { 'Content-Type': 'application/json' };
                if (activeToken) {
                    headers['Authorization'] = `Bearer ${activeToken}`;
                }

                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify({ message: message, mode: activeMode })
                });

                if (!response.ok) {
                    if (response.status === 401) {
                        responseText.innerHTML = '<span style="color: #ef4444;">Session expired or unauthorized. Please log out and log back in.</span>';
                        return;
                    }
                    throw new Error(`HTTP Error: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullAnswer = "";
                let sources = [];
                let sourceGalleryHTML = "";

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

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

                    for (const line of lines) {
                        if (!line.trim()) continue;
                        try {
                            const json = JSON.parse(line);
                            if (json.type === 'sources') {
                                sources = json.data;
                                // Create a visual gallery for the images inline
                                sourceGalleryHTML = '<div class="source-images-gallery" style="display: flex; gap: 10px; margin-top: 15px; overflow-x: auto; padding-bottom: 10px;">';
                                sources.forEach(src => {
                                    // Keep the clickable tags for history
                                    const tag = document.createElement('span');
                                    tag.className = 'source-tag';
                                    tag.innerText = `${src.book_name} (Pg ${src.page_number})`;
                                    tag.onclick = () => {
                                        modalTitle.innerText = `${src.book_name} - Page ${src.page_number}`;
                                        modalImg.src = `/page_image?path=${encodeURIComponent(src.image_path)}`;
                                        pageModal.style.display = 'flex';
                                    };
                                    sourceList.appendChild(tag);
                                    
                                    // Auto-embed the exact image directly in the chat
                                    sourceGalleryHTML += `
                                        <div style="flex: 0 0 auto; width: 250px; border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 8px; overflow: hidden; background: rgba(0,0,0,0.2); cursor: pointer;" onclick="document.getElementById('modal-title').innerText='${src.book_name} - Page ${src.page_number}'; document.getElementById('modal-img').src='/page_image?path=${encodeURIComponent(src.image_path)}'; document.getElementById('page-modal').style.display='flex';">
                                            <div style="font-size: 10px; color: var(--primary); padding: 5px 8px; border-bottom: 1px solid rgba(16, 185, 129, 0.2); font-weight: 600; text-transform: uppercase;">Exact Page Reference</div>
                                            <img src="/page_image?path=${encodeURIComponent(src.image_path)}" style="width: 100%; height: auto; object-fit: contain; display: block;" alt="Reference Page">
                                        </div>
                                    `;
                                });
                                sourceGalleryHTML += '</div>';
                                
                                // Manually update the view since sources arrive last in the stream now
                                responseText.innerHTML = queryHTML + badgeHTML + DOMPurify.sanitize(marked.parse(fullAnswer)) + sourceGalleryHTML;
                                window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
                                
                            } else if (json.type === 'start_answer') {
                                responseText.innerHTML = queryHTML + badgeHTML + sourceGalleryHTML;
                                fullAnswer = ""; // Reset buffer
                            } else if (json.type === 'content') {
                                fullAnswer += json.data;
                                responseText.innerHTML = queryHTML + badgeHTML + DOMPurify.sanitize(marked.parse(fullAnswer)) + sourceGalleryHTML;
                                window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
                            }
                        } catch (e) { }
                    }
                }
                // Save complete result to history
                saveToHistory(message, fullAnswer, sources);

                // Revert to user's default mode if they did a temporary override
                if (activeUser?.user_metadata?.defaultMode) {
                    activeMode = activeUser.user_metadata.defaultMode;
                    updateModeButtons(activeMode);
                }

                // Show feedback widget when streaming completes successfully
                if (feedbackContainer) feedbackContainer.style.display = 'flex';
            } catch (error) {
                responseText.innerHTML = '<span style="color: #ef4444;">Connection error.</span>';
            } finally {
                // Re-enable inputs
                chatInput.disabled = false;
                sendBtn.disabled = false;
                document.querySelector('.input-wrapper').classList.remove('disabled');
                chatInput.focus();
            }
        }

        const resetModal = () => { 
            pageModal.style.display = 'none'; 
            modalImg.dataset.scale = 1;
            modalImg.style.transform = 'scale(1)';
        };
        closeModal.onclick = resetModal;
        window.onclick = (event) => { if (event.target == pageModal) resetModal(); };

        modalImg.addEventListener('wheel', (e) => {
            e.preventDefault();
            const delta = e.deltaY > 0 ? 0.9 : 1.1;
            const newScale = (modalImg.dataset.scale || 1) * delta;
            if (newScale >= 1 && newScale <= 5) {
                modalImg.dataset.scale = newScale;
                modalImg.style.transform = `scale(${newScale})`;
            }
        });

        let isDragging = false;
        let startX, startY, scrollLeft, scrollTop;

        const modalBody = document.querySelector('.modal-body');
        modalBody.addEventListener('mousedown', (e) => {
            isDragging = true;
            startX = e.pageX - modalBody.offsetLeft;
            startY = e.pageY - modalBody.offsetTop;
            scrollLeft = modalBody.scrollLeft;
            scrollTop = modalBody.scrollTop;
        });

        modalBody.addEventListener('mouseleave', () => { isDragging = false; });
        modalBody.addEventListener('mouseup', () => { isDragging = false; });

        modalBody.addEventListener('mousemove', (e) => {
            if (!isDragging) return;
            e.preventDefault();
            const x = e.pageX - modalBody.offsetLeft;
            const y = e.pageY - modalBody.offsetTop;
            const walkX = (x - startX) * 2;
            const walkY = (y - startY) * 2;
            modalBody.scrollLeft = scrollLeft - walkX;
            modalBody.scrollTop = scrollTop - walkY;
        });

        // Feedback loop logic
        const thumbsUpBtn = document.getElementById('thumbs-up-btn');
        const thumbsDownBtn = document.getElementById('thumbs-down-btn');
        const feedbackLabel = document.querySelector('.feedback-label');

        if (thumbsUpBtn && thumbsDownBtn) {
            thumbsUpBtn.addEventListener('click', () => {
                thumbsUpBtn.classList.toggle('active-up');
                thumbsDownBtn.classList.remove('active-down');
                if (thumbsUpBtn.classList.contains('active-up')) {
                    feedbackLabel.innerText = "Thank you!";
                    setTimeout(() => { feedbackLabel.innerText = "Was this helpful?"; }, 3000);
                }
            });

            thumbsDownBtn.addEventListener('click', () => {
                thumbsDownBtn.classList.toggle('active-down');
                thumbsUpBtn.classList.remove('active-up');
                if (thumbsDownBtn.classList.contains('active-down')) {
                    feedbackLabel.innerText = "Thank you!";
                    setTimeout(() => { feedbackLabel.innerText = "Was this helpful?"; }, 3000);
                }
            });
        }

        sendBtn.addEventListener('click', handleSend);
        chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') handleSend(); });
    </script>
</body>

</html>