File size: 42,975 Bytes
84e1dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b78a45
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
<!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, viewport-fit=cover">
    <title>DOC Q&A - AI PRO SUITE</title>
    
    <!-- πŸ”— CORE STYLES -->
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;800&display=swap" rel="stylesheet">
    
    <!-- FILE PARSING ENGINES -->
    <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js"></script>
    <script>pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>

    <!-- MATHJAX INJECTION -->
    <script>

        MathJax = { 

            options: { ignoreHtmlClass: 'code-box', processHtmlClass: 'markdown-body' },

            tex: { inlineMath: [['$', '$'], ['\\(', '\\)']], displayMath: [['$$', '$$'], ['\\[', '\\]']] },

            svg: { fontCache: 'global' }, chtml: { displayAlign: 'left' }

        };

    </script>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

<style>

    /* πŸ›‘οΈ STRICT DESKTOP SPLIT & MOBILE RESPONSIVE FIXES */

    * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; } 

    html, body { overflow: hidden !important; max-width: 100vw !important; }

    

    .qa-sidebar {

        position: fixed; top: 70px; left: 0; bottom: 0; width: 350px;

        background: var(--bg-surface); border-right: 1px solid var(--border-light);

        padding: 20px; overflow-y: auto; z-index: 10;

        transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);

    }

    

    .qa-main {

        margin-left: 350px; position: relative; height: 100dvh; 

        display: flex; flex-direction: column; width: calc(100vw - 350px);

    }

    

    .qa-input-area {

        position: fixed; bottom: 0; left: 350px; width: calc(100% - 350px);

        background: var(--bg-surface); padding: 15px 20px; border-top: 1px solid var(--border-light);

        z-index: 100; display: flex; flex-direction: column; gap: 10px;

    }



    /* πŸ›‘ SEND & STOP BUTTON STYLING */

    .qa-send-btn {

        background: linear-gradient(135deg, var(--secondary), var(--primary)); 

        color: white; border: none; width: 45px; height: 45px; border-radius: 50%; 

        font-size: 18px; cursor: pointer; display: flex; justify-content: center; align-items: center; 

        flex-shrink: 0; box-shadow: 0 4px 15px rgba(139, 92, 246, 0.4);

        transition: 0.15s ease-out; animation: none !important; transform: none !important;

    }

    .qa-send-btn:active { transform: scale(0.9) !important; }



    .qa-stop-btn {

        background: #ef4444; color: white; border: none; width: 45px; height: 45px; border-radius: 50%; 

        font-size: 18px; cursor: pointer; display: none; justify-content: center; align-items: center; 

        flex-shrink: 0; box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4);

    }

    .qa-stop-btn:active { transform: scale(0.9) !important; }



    .qa-clear-btn {

        background: rgba(239, 68, 68, 0.1) !important; color: #ef4444 !important;

        border: 1px solid rgba(239, 68, 68, 0.4) !important; padding: 8px 16px !important;

        border-radius: 12px !important; font-size: 12px !important; font-weight: 800 !important;

        cursor: pointer; transition: 0.2s;

    }

    .qa-clear-btn:hover { background: #ef4444 !important; color: white !important; box-shadow: 0 5px 15px rgba(239,68,68,0.3); }



    /* UPLOAD ZONE */

    .drop-zone { width: 100%; padding: 30px 20px; border: 2px dashed var(--primary); border-radius: 20px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; background: rgba(139, 92, 246, 0.05); cursor: pointer; transition: 0.3s; margin-bottom: 20px; }

    .drop-zone:hover { background: rgba(139, 92, 246, 0.15); border-color: var(--secondary); transform: translateY(-2px); }

    .kb-item { display: flex; justify-content: space-between; align-items: center; background: var(--input-bg); padding: 12px; border-radius: 12px; border: 1px solid var(--border-light); margin-bottom: 10px; animation: slideInUp 0.3s ease; }

    .answer-highlight { background: rgba(59,130,246,0.20); color: #3b82f6; font-weight: 800; padding: 2px 6px; border-radius: 6px; }



    /* 🌈 RAINBOW THINKING ANIMATION */

    @property --tail { syntax: '<percentage>'; inherits: false; initial-value: 100%; }

    .rainbow-thinking-bubble { position: relative; padding: 16px 20px; min-width: 220px; display: flex; flex-direction: column; gap: 12px; border-radius: 20px; background: transparent; box-shadow: 0 8px 25px rgba(0,0,0,0.05); overflow: hidden; z-index: 1; }

    .rainbow-thinking-bubble::before { content: ''; position: absolute; top: 50%; left: 50%; width: 250%; height: 250%; background: conic-gradient(transparent 0%, transparent var(--tail), currentColor 100%); filter: blur(4px); z-index: -2; animation: spin 2s linear infinite, writeAndHideTail 2s infinite, colorLoop 8s infinite; }

    .rainbow-thinking-bubble::after { content: ''; position: absolute; inset: 2px; background: var(--bg-surface); border-radius: 18px; z-index: -1; }

    @keyframes spin { 0% { transform: translate(-50%, -50%) rotate(0deg); } 100% { transform: translate(-50%, -50%) rotate(360deg); } }

    @keyframes writeAndHideTail { 0% { --tail: 100%; opacity: 0; } 15% { opacity: 1; } 50% { --tail: 40%; } 85% { opacity: 1; } 100% { --tail: 100%; opacity: 0; } }

    @keyframes colorLoop { 0%, 24.99% { color: #4285F4; } 25%, 49.99% { color: #EA4335; } 50%, 74.99% { color: #FBBC05; } 75%, 100% { color: #34A853; } }

    .thinking-status-line { font-size: 14px; font-weight: 800; color: var(--text-main); letter-spacing: 0.5px; text-align: center; }



    /* CHAT BUBBLE ANIMATIONS */

    .chat-msg { animation: bounceInBubble 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; transform-origin: bottom center; width: 100%; }

    .bubble { max-width: 90%; padding: 16px 20px; border-radius: 20px; font-size: 14.5px; line-height: 1.6; word-wrap: break-word; overflow-wrap: break-word; overflow-x: auto; box-shadow: 0 4px 15px rgba(0,0,0,0.05); transition: transform 0.3s ease; }

    .bubble:hover { transform: translateY(-2px); }

    @keyframes bounceInBubble { 0% { opacity: 0; transform: scale(0.8) translateY(30px); } 60% { opacity: 1; transform: scale(1.02) translateY(-5px); } 100% { opacity: 1; transform: scale(1) translateY(0); } }

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



    /* MENU POPUPS */

    .glass-menu { display: none; position: absolute; background: rgba(30, 41, 59, 0.95); backdrop-filter: blur(20px); border: 1px solid var(--border-light); border-radius: 16px; flex-direction: column; z-index: 200; width: 200px; box-shadow: 0 15px 40px rgba(0,0,0,0.5); animation: popIn 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275); overflow: hidden; }

    .menu-btn { background: transparent; border: none; color: white; padding: 15px; text-align: left; font-size: 14px; font-weight: 600; cursor: pointer; border-bottom: 1px solid var(--border-light); transition: 0.2s; }

    .menu-btn:hover { background: var(--primary); padding-left: 20px; }

    @keyframes popIn { 0% { opacity: 0; transform: scale(0.9) translateY(10px); } 100% { opacity: 1; transform: scale(1) translateY(0); } }



    .mobile-kb-fab { display: none; }



    /* πŸ“± MOBILE OVERRIDES */

    @media (max-width: 800px) {

        .qa-sidebar {

            top: 0; left: 0; width: 100vw; height: 100vh; z-index: 9999999;

            background: rgba(15, 23, 42, 0.98); backdrop-filter: blur(15px);

            border: none; padding: 25px 20px; display: none; flex-direction: column;

        }

        .qa-sidebar.active { display: flex; animation: fadeInPage 0.3s ease; }

        

        .qa-main { margin-left: 0; width: 100vw; }

        .qa-input-area { left: 0; width: 100vw; }



        .mobile-kb-fab {

            display: flex; position: fixed; top: 85px; left: 50%; transform: translateX(-50%);

            background: var(--bg-surface); border: 2px solid var(--primary); color: var(--primary);

            padding: 10px 24px; border-radius: 30px; font-weight: 900; font-size: 13px;

            z-index: 900; box-shadow: 0 10px 25px rgba(0,0,0,0.15);

            align-items: center; gap: 8px; cursor: pointer; white-space: nowrap; transition: 0.2s;

        }

        .mobile-kb-fab:active { transform: translateX(-50%) scale(0.95); }

        .chat-scroll-area { padding-top: 140px !important; padding-bottom: 140px !important; }

    }

</style>
</head>
<body>

    <!-- 🌐 TOPBAR -->
    <div class="topbar" id="appTopbar">
        <div style="display:flex; align-items:center; gap:12px; flex:1;">
            <button class="menu-btn" onclick="apsToggleSidebar()" title="All pages" style="background:none; border:none; font-size:24px; color:var(--text-main); cursor:pointer;">☰</button>
            <div class="appTitle" style="font-size:20px; font-weight:bold; color: var(--text-main); letter-spacing: 1px; margin-left:0;">DOC Q&A</div>
        </div>

        <div style="display:flex; gap:10px; align-items:center;">
            <button class="qa-clear-btn" onclick="clearChat()">πŸ—‘οΈ Clear</button>
            
            <button id="modeToggleBtn" style="background: rgba(16, 185, 129, 0.15); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.4); padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 900; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; transition: 0.3s;" onclick="toggleAppMode()">
                <span id="modeDot" style="display:inline-block; width:8px; height:8px; background:#10b981; border-radius:50%; box-shadow: 0 0 10px #10b981;"></span>
                <span id="modeBtnText">πŸ”’ OFFLINE</span>
            </button>
        </div>
    </div>

    <!-- πŸ“± MOBILE FLOATING SOURCES BUTTON -->
    <div class="mobile-kb-fab" id="mobileKbFab" onclick="toggleQaSidebar()">
        πŸ“‚ Manage Sources (0)
    </div>

    <!-- πŸ“‚ KNOWLEDGE BASE (SIDEBAR) -->
    <div class="qa-sidebar" id="qaSidebar">
        <button style="display: none; width: 100%; margin-bottom: 20px; padding: 15px; background: #ef4444; color: white; border: none; border-radius: 12px; font-weight: 900; font-size: 15px; cursor: pointer; box-shadow: 0 5px 15px rgba(239,68,68,0.4);" id="mobileCloseSidebarBtn" onclick="toggleQaSidebar()">βœ– Close & Return to Chat</button>

        <h2 style="margin:0 0 5px 0; font-size:18px; font-weight:900;">Knowledge Base</h2>
        <p style="color:var(--text-muted); font-size:12px; margin-bottom:15px; line-height:1.4;"><span id="modeDescText">AI will ONLY answer based on these files.</span></p>
        
        <input type="file" id="kbUpload" accept=".txt,.pdf,.docx,.csv,.md,.json,image/*" multiple style="display:none" onchange="processKbFiles(event)">
        
        <!-- DROP ZONE MENU TRIGGER -->
        <div class="drop-zone" onclick="toggleMenu('kbAddMenu', event)" id="dropZone">
            <div class="drop-icon">πŸ“₯</div>
            <div style="font-weight: 800; font-size: 15px; color: var(--text-main);">Click to Add Files</div>
            <div style="font-size: 11px; color: var(--text-muted); margin-top: 5px;">PDF, DOCX, TXT, CSV, Images</div>
        </div>

        <!-- KB ADD MENU -->
        <div class="glass-menu" id="kbAddMenu" style="top: 250px; left: 50px;">
            <button class="menu-btn" onclick="openCameraFor('kb')">πŸ“· Take Photo</button>
            <button class="menu-btn" style="border-bottom:none;" onclick="document.getElementById('kbUpload').click(); closeAllMenus();">πŸ“Ž Upload File</button>
        </div>

        <div id="kbList" style="flex:1; overflow-y:auto; overflow-x:hidden;">
            <div style="text-align:center; padding: 30px 10px; opacity: 0.6;">
                <div style="font-size: 40px; margin-bottom: 10px;">πŸ“</div>
                <div style="color:var(--text-main); font-size:14px; font-weight:bold;">No sources loaded</div>
            </div>
        </div>
    </div>

    <!-- πŸ’¬ MAIN CHAT AREA -->
    <div class="qa-main">
        <div class="chat-scroll-area" id="searchScrollArea" style="padding-top: 90px; padding-bottom: 120px; overflow-x: hidden;">
            <div class="chat-history" id="chatBox" style="width: 100%; max-width: 100vw;">
                <div class="chat-msg chat-ai">
                    <div class="bubble">
                        <div style="font-size:12px; font-weight:900; color:var(--primary); margin-bottom:10px; text-transform:uppercase; letter-spacing:1px;">✨ RAG SYSTEM ONLINE</div>
                        Load your documents or images on the left. I am strictly locked to your files and will <b>not</b> hallucinate outside information. <br><br><i>(Want me to use my general knowledge or search the web? Click 'OFFLINE' at the top to toggle to ONLINE MODE).</i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- ⌨️ INPUT AREA -->
        <div class="chat-input-area qa-input-area" id="appInputArea">
            <div class="chat-images-preview" id="chatImgPreview" style="display:none; gap:10px; overflow-x:auto; padding-bottom:5px; width:100%;"></div>
            
            <div class="chat-input-wrapper">
                <button class="chat-action-btn" onclick="toggleMenu('chatAddMenu', event)" style="background:transparent; color:var(--primary); width:40px; height:40px; border:none; font-size:20px;" title="Add Image">πŸ“Ž</button>
                <input type="file" id="chatImgUpload" accept="image/*" multiple style="display:none" onchange="handleChatImages(event)">
                
                <!-- CHAT ADD MENU -->
                <div class="glass-menu" id="chatAddMenu" style="bottom: 80px; left: 20px;">
                    <button class="menu-btn" onclick="openCameraFor('chat')">πŸ“· Take Photo</button>
                    <button class="menu-btn" style="border-bottom:none;" onclick="document.getElementById('chatImgUpload').click(); closeAllMenus();">πŸ“Ž Upload Image</button>
                </div>
                
                <textarea id="userInput" placeholder="Ask about the documents..." rows="1" oninput="resizeInput()" onkeypress="if(event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); askQuestion(); }" style="flex:1; background:transparent; border:none; color:var(--text-main); outline:none; resize:none; font-family:'Poppins'; padding:10px; max-height:120px; overflow-y:auto; font-size:15px;"></textarea>
                
                <button class="qa-send-btn" id="sendBtn" onclick="askQuestion()">⬆️</button>
                <button class="qa-stop-btn" id="stopBtn" onclick="stopGeneration()">πŸ›‘</button>
            </div>
        </div>
    </div>

    <!-- FULL SCREEN IMAGE VIEWER -->
    <div id="fullImageViewer" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.95); z-index:9999999; flex-direction:column; align-items:center; justify-content:center;">
        <div style="position:absolute; top:20px; right:20px; display:flex; gap:10px; z-index:10000000;">
            <button class="qa-clear-btn" style="background: rgba(255,255,255,0.2) !important; color: white !important; border: 1px solid white !important;" onclick="downloadFullImage()">πŸ“₯ Download</button>
            <button class="qa-clear-btn" style="background: #ef4444 !important; color: white !important; border: 1px solid #ef4444 !important;" onclick="closeFullImage()">βœ– Close</button>
        </div>
        <img id="fullImageSrc" style="max-width:95%; max-height:80vh; border-radius:15px; object-fit:contain; animation: popInCard 0.3s ease;">
    </div>

    <!-- CAMERA MODAL (WITH FLASH BUTTON) -->
    <div id="cameraModal" style="display:none; position:fixed; inset:0; background:#000; z-index:9999999; flex-direction:column;">
        <video id="cameraVideo" autoplay playsinline style="width:100%; height:100%; object-fit:cover;"></video>
        <button style="position:absolute; top:20px; right:20px; background:#ef4444; color:white; border:none; width:45px; height:45px; border-radius:50%; font-size:20px; cursor:pointer; font-weight:bold; box-shadow:0 5px 15px rgba(0,0,0,0.5);" onclick="closeCamera()">βœ•</button>
        <div style="position:absolute; bottom:40px; left:0; width:100%; display:flex; justify-content:center; align-items:center; gap:40px;">
            <button id="flashBtn" onclick="toggleFlash()" style="background:rgba(255,255,255,0.25); border:1px solid rgba(255,255,255,0.5); color:white; width:55px; height:55px; border-radius:50%; font-size:22px; cursor:pointer; backdrop-filter:blur(5px); transition:0.2s;">πŸ’‘</button>
            <div onclick="takePhoto()" style="width:75px; height:75px; background:white; border:6px solid #cbd5e1; border-radius:50%; cursor:pointer; box-shadow:0 0 30px rgba(0,0,0,0.6); transition:0.2s;" onmousedown="this.style.transform='scale(0.85)'" onmouseup="this.style.transform='scale(1)'"></div>
            <button onclick="switchCamera()" style="background:rgba(255,255,255,0.25); border:1px solid rgba(255,255,255,0.5); color:white; width:55px; height:55px; border-radius:50%; font-size:22px; cursor:pointer; backdrop-filter:blur(5px); transition:0.2s;">πŸ”„</button>
        </div>
        <canvas id="captureCanvas" style="display:none;"></canvas>
    </div>

    <!-- NAV WARNING TRAP -->
    <div id="navWarningModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.85); z-index:10000000; justify-content:center; align-items:center; backdrop-filter:blur(5px);">
        <div style="text-align:center; max-width:320px; border:2px solid #ef4444; background:var(--bg-surface); padding: 25px; border-radius: 20px;">
            <div style="font-size:45px; margin-bottom:10px;">⚠️</div>
            <h3 style="color:#ef4444; margin:0 0 10px 0; font-weight:900;">Leave Page?</h3>
            <p style="color:var(--text-main); font-size:14px;">You will lose your loaded documents and current chat. Are you sure you want to leave?</p>
            <div style="display:flex; gap:10px; width:100%; margin-top:20px;">
                <button class="qa-clear-btn" style="flex:1; background:var(--input-bg) !important; color:var(--text-main) !important; border-color:var(--border-light) !important;" onclick="cancelNav()">Stay</button>
                <button class="qa-clear-btn" style="flex:1; background:#ef4444 !important; color:white !important; border-color:#ef4444 !important;" onclick="proceedNav()">Leave</button>
            </div>
        </div>
    </div>

    <script>

        // --- MOBILE LAYOUT & MENUS ---

        function toggleQaSidebar() {

            const sidebar = document.getElementById('qaSidebar');

            sidebar.classList.toggle('active');

            if (window.innerWidth <= 800) {

                document.getElementById('mobileCloseSidebarBtn').style.display = sidebar.classList.contains('active') ? 'block' : 'none';

            }

        }



        function toggleMenu(menuId, e) {

            e.stopPropagation();

            const m = document.getElementById(menuId);

            const isShowing = m.style.display === "flex";

            closeAllMenus();

            if (!isShowing) m.style.display = "flex";

        }

        function closeAllMenus() {

            document.querySelectorAll('.glass-menu').forEach(m => m.style.display = 'none');

        }

        window.onclick = closeAllMenus;



        // --- STATE & MEMORY ---

        let kbTextBlocks = [];

        let kbImages = []; 

        let chatImages = []; 

        let kbFilesUI = []; 

        let isProcessing = false;

        let currentFullImg = "";

        let isOnlineMode = false; 

        let appHistory = [];

        let currentSessionId = Date.now();

        

        let currentPhotoTarget = 'chat'; 

        let camStream = null;

        let camFacing = "environment";

        let isFlash = false;



        let fetchAbortController = null;

        let typewriterInterval = null;



        if (typeof localforage !== 'undefined') {

            localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });

            localforage.getItem('aiHistory').then(data => { if (data) appHistory = data; });

        }



        function toggleAppMode() {

            isOnlineMode = !isOnlineMode;

            const btn = document.getElementById("modeToggleBtn");

            const dot = document.getElementById("modeDot");

            const txt = document.getElementById("modeBtnText");

            const desc = document.getElementById("modeDescText");



            if (isOnlineMode) {

                btn.style.color = "#3b82f6"; btn.style.borderColor = "rgba(59, 130, 246, 0.4)"; btn.style.background = "rgba(59, 130, 246, 0.15)";

                dot.style.background = "#3b82f6"; dot.style.boxShadow = "0 0 10px #3b82f6";

                txt.innerText = "🌐 ONLINE"; desc.innerHTML = "AI will use these files AND its internet knowledge.";

            } else {

                btn.style.color = "#10b981"; btn.style.borderColor = "rgba(16, 185, 129, 0.4)"; btn.style.background = "rgba(16, 185, 129, 0.15)";

                dot.style.background = "#10b981"; dot.style.boxShadow = "0 0 10px #10b981";

                txt.innerText = "πŸ”’ OFFLINE"; desc.innerHTML = "AI will ONLY answer based on these files.";

            }

        }



        function resizeInput() {

            const inp = document.getElementById('userInput');

            inp.style.height = 'auto'; inp.style.height = Math.min(inp.scrollHeight, 150) + 'px';

        }



        function openFullImage(src) { currentFullImg = src; document.getElementById('fullImageSrc').src = src; document.getElementById('fullImageViewer').style.display = 'flex'; }

        function closeFullImage() { document.getElementById('fullImageViewer').style.display = 'none'; }

        function downloadFullImage() { const a = document.createElement("a"); a.href = currentFullImg; a.download = "RAG_Image_" + Date.now() + ".jpg"; a.click(); }



        function clearChat() {

            if(!confirm("Wipe the chat history? Knowledge base files will be kept.")) return;

            document.getElementById("chatBox").innerHTML = `

                <div class="chat-msg chat-ai"><div class="bubble"><div style="font-size:12px; font-weight:900; color:var(--primary); margin-bottom:10px;">✨ SYSTEM REFRESHED</div>Chat history wiped. Ready for new questions.</div></div>`;

            currentSessionId = Date.now();

        }



        function appendMessage(sender, htmlContent, id = "") {

            const chatBox = document.getElementById("chatBox");

            const msgDiv = document.createElement("div");

            msgDiv.className = `chat-msg chat-${sender}`;

            if (id) msgDiv.id = "wrap_" + id;

            msgDiv.innerHTML = `<div class="bubble">${htmlContent}</div>`;

            chatBox.appendChild(msgDiv);

            document.getElementById("searchScrollArea").scrollTop = document.getElementById("searchScrollArea").scrollHeight;

        }



        // --- CAMERA ENGINE (WITH FLASH) ---

        function openCameraFor(target) { currentPhotoTarget = target; closeAllMenus(); openCamera(); }

        async function openCamera() {

            document.getElementById('cameraModal').style.display='flex';

            try { 

                if(camStream) camStream.getTracks().forEach(t => t.stop()); 

                camStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: camFacing, width: {ideal: 1280}, height: {ideal: 720} } }); 

                document.getElementById("cameraVideo").srcObject = camStream; 

                

                // πŸ’‘ Auto Flash logic

                setTimeout(async () => {

                    if(!camStream) return;

                    const track = camStream.getVideoTracks()[0];

                    if (track.getCapabilities && track.getCapabilities().torch && camFacing === "environment") {

                        isFlash = true;

                        await track.applyConstraints({ advanced: [{ torch: true }] });

                        document.getElementById('flashBtn').innerText = "πŸ’‘";

                    } else {

                        document.getElementById('flashBtn').innerText = "πŸ”¦";

                    }

                }, 500);

            } catch(e) { alert("Camera access denied."); closeCamera(); }

        }

        function closeCamera() { document.getElementById('cameraModal').style.display='none'; if(camStream) camStream.getTracks().forEach(t=>t.stop()); isFlash = false; }

        async function switchCamera() { camFacing = camFacing === "environment" ? "user" : "environment"; await openCamera(); }

        async function toggleFlash() {

            if(!camStream) return;

            const track = camStream.getVideoTracks()[0];

            if (track.getCapabilities && track.getCapabilities().torch) {

                isFlash = !isFlash;

                await track.applyConstraints({ advanced: [{ torch: isFlash }] });

                document.getElementById('flashBtn').innerText = isFlash ? "πŸ’‘" : "πŸ”¦";

            } else {

                alert("Flash not supported on this device/camera.");

            }

        }

        function takePhoto() { 

            const v = document.getElementById("cameraVideo"), c = document.getElementById("captureCanvas"); 

            c.width = v.videoWidth; c.height = v.videoHeight; 

            c.getContext("2d").drawImage(v, 0, 0, c.width, c.height); 

            const dataUrl = c.toDataURL("image/jpeg", 0.7); 

            

            if (currentPhotoTarget === 'kb') {

                if(kbImages.length >= 15) { alert("Max 15 images!"); closeCamera(); return; }

                kbImages.push(dataUrl);

                kbFilesUI.push({ id: Date.now(), name: "Camera Photo", type: 'img', index: kbImages.length - 1, src: dataUrl });

                renderKbList();

            } else {

                if(chatImages.length >= 5) { alert("Max 5 chat images!"); closeCamera(); return; }

                chatImages.push(dataUrl);

                renderChatImgPreview();

            }

            closeCamera(); 

        }



        // --- BACK BUTTON TRAP ---

        let isBackNav = false;

        history.pushState({ trap: true }, null, window.location.href);

        window.addEventListener('popstate', function(e) { isBackNav = true; document.getElementById('navWarningModal').style.display = 'flex'; history.pushState({ trap: true }, null, window.location.href); });

        window.addEventListener('beforeunload', (e) => { if (kbFilesUI.length > 0 || chatImages.length > 0) { const msg = "Leave site?"; e.returnValue = msg; return msg; } });

        function requestExit() { document.getElementById('navWarningModal').style.display = 'flex'; }

        function cancelNav() { document.getElementById('navWarningModal').style.display = 'none'; isBackNav = false; }

        function proceedNav() { window.removeEventListener('beforeunload', null); if (isBackNav) { history.go(-2); } else { window.location.href = window.__apsPending || 'index.html'; } }



        // --- KNOWLEDGE BASE ENGINE ---

        async function processKbFiles(event) {

            const files = Array.from(event.target.files);

            if (!files.length) return;

            for (let file of files) {

                try {

                    const ext = file.name.split('.').pop().toLowerCase();

                    if (file.type.startsWith("image/")) {

                        if (kbImages.length >= 15) continue;

                        const b64 = await readFileAsBase64(file); kbImages.push(b64);

                        kbFilesUI.push({ id: Date.now(), name: file.name, type: 'img', index: kbImages.length - 1, src: b64 });

                    } else if (file.type === "application/pdf" || ext === "pdf") {

                        const arrayBuffer = await file.arrayBuffer(); const pdf = await pdfjsLib.getDocument(new Uint8Array(arrayBuffer)).promise;

                        let text = ""; for (let i = 1; i <= pdf.numPages; i++) { const page = await pdf.getPage(i); const content = await page.getTextContent(); text += content.items.map(item => item.str).join(" ") + "\n"; }

                        kbTextBlocks.push(`[FILE: ${file.name}]\n${text.replace(/\s+/g, ' ').trim()}`); kbFilesUI.push({ id: Date.now(), name: file.name, type: 'pdf', index: kbTextBlocks.length - 1 });

                    } else if (ext === "docx" || file.type.includes("wordprocessingml")) {

                        const arrayBuffer = await file.arrayBuffer(); const result = await mammoth.extractRawText({arrayBuffer: arrayBuffer});

                        kbTextBlocks.push(`[FILE: ${file.name}]\n${result.value.replace(/\s+/g, ' ').trim()}`); kbFilesUI.push({ id: Date.now(), name: file.name, type: 'docx', index: kbTextBlocks.length - 1 });

                    } else {

                        const text = await file.text(); kbTextBlocks.push(`[FILE: ${file.name}]\n${text.trim()}`); kbFilesUI.push({ id: Date.now(), name: file.name, type: 'txt', index: kbTextBlocks.length - 1 });

                    }

                } catch (e) { console.error("Parse fail:", file.name, e); }

            }

            event.target.value = ""; renderKbList();

        }



        function readFileAsBase64(file) { return new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; r.readAsDataURL(file); }); }



        function renderKbList() {

            const list = document.getElementById("kbList");

            const mobileFab = document.getElementById("mobileKbFab");

            if (mobileFab) mobileFab.innerText = `πŸ“‚ Manage Sources (${kbFilesUI.length})`;



            if (kbFilesUI.length === 0) {

                list.innerHTML = `<div style="text-align:center; padding: 30px 10px; opacity: 0.6;"><div style="font-size: 40px; margin-bottom: 10px;">πŸ“</div><div style="color:var(--text-main); font-size:14px; font-weight:bold;">No sources loaded</div></div>`;

                return;

            }

            list.innerHTML = kbFilesUI.map((f, i) => {

                let iconHtml = f.type === 'img' ? `<img src="${f.src}" onclick="openFullImage('${f.src}')" style="width:35px; height:35px; border-radius:6px; object-fit:cover; cursor:zoom-in; border:1px solid var(--primary);">` : `<span style="font-size:24px;">${f.type === 'pdf' ? 'πŸ“‘' : (f.type === 'docx' ? 'πŸ“' : 'πŸ“„')}</span>`;

                return `<div class="kb-item"><div style="display:flex; align-items:center; gap:10px; overflow:hidden;">${iconHtml}<div style="font-size:13px; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; color:var(--text-main);">${f.name}</div></div><button class="qa-clear-btn" onclick="deleteKbItem(${i})" style="padding: 6px 10px !important;">βœ•</button></div>`;

            }).join('');

        }



        function deleteKbItem(uiIndex) {

            const fUi = kbFilesUI[uiIndex];

            if (fUi.type === 'img') kbImages[fUi.index] = null; else kbTextBlocks[fUi.index] = null;

            kbFilesUI.splice(uiIndex, 1);

            kbImages = kbImages.filter(Boolean); kbTextBlocks = kbTextBlocks.filter(Boolean);

            kbFilesUI.forEach(f => { if (f.type === 'img') f.index = kbImages.indexOf(f.src); });

            let txtIdx = 0; kbFilesUI.forEach(f => { if (f.type !== 'img') f.index = txtIdx++; });

            renderKbList();

        }



        async function handleChatImages(event) {

            const files = Array.from(event.target.files);

            for (let f of files) { if (chatImages.length >= 5) break; const b64 = await readFileAsBase64(f); chatImages.push(b64); }

            event.target.value = ""; renderChatImgPreview(); closeAllMenus();

        }



        function renderChatImgPreview() {

            const c = document.getElementById("chatImgPreview");

            if (!chatImages.length) { c.style.display = "none"; return; }

            c.style.display = "flex";

            c.innerHTML = chatImages.map((img, i) => `<div style="position:relative; width:60px; height:60px; border-radius:10px; border:2px solid var(--primary); flex-shrink:0;"><img src="${img}" style="width:100%; height:100%; object-fit:cover; border-radius:8px;"><button onclick="chatImages.splice(${i},1); renderChatImgPreview();" style="position:absolute; top:-5px; right:-5px; background:#ef4444; color:white; border:none; border-radius:50%; width:20px; height:20px; cursor:pointer;">βœ•</button></div>`).join('');

        }



        function saveInteraction(q, a, provider) {

            if (typeof localforage === 'undefined') return;

            let idx = appHistory.findIndex(s => s.id === currentSessionId);

            let session = idx !== -1 ? appHistory.splice(idx, 1)[0] : { id: currentSessionId, type: 'qa', title: q.length > 30 ? q.substring(0, 30)+"..." : q, interactions: [] };

            session.interactions.push({ id: "msg_" + Date.now(), question: q, answer: a, timestamp: Date.now(), provider: provider });

            appHistory.unshift(session); if (appHistory.length > 30) appHistory = appHistory.slice(0, 30);

            localforage.setItem('aiHistory', appHistory);

        }



        // --- STOP BUTTON ENGINE ---

        function stopGeneration() {

            if (fetchAbortController) fetchAbortController.abort();

            clearInterval(typewriterInterval);

            if (window._twTarget && window._twHtml) {

                window._twTarget.innerHTML = window._twHtml;

                if(window.MathJax) { MathJax.typesetClear([window._twTarget]); MathJax.typesetPromise([window._twTarget]); }

            }

            isProcessing = false;

            document.getElementById('sendBtn').style.display = 'flex';

            document.getElementById('stopBtn').style.display = 'none';

        }



        // --- HYPER FAST TYPEWRITER (WITH CALLBACK FIX) ---

        function runFastTypewriter(targetElement, fullHtml, callback) {

            window._twTarget = targetElement; window._twHtml = fullHtml;

            

            let charIndex = 0;

            const chunkSize = 8; 

            targetElement.innerHTML = "";

            const scrollArea = document.getElementById("searchScrollArea");



            typewriterInterval = setInterval(() => {

                if (charIndex >= fullHtml.length) {

                    clearInterval(typewriterInterval);

                    targetElement.innerHTML = fullHtml;

                    if(window.MathJax) { MathJax.typesetClear([targetElement]); MathJax.typesetPromise([targetElement]); }

                    if (callback) callback(); // πŸš€ Triggers the button unlock!

                    return;

                }

                charIndex += chunkSize;

                targetElement.innerHTML = fullHtml.substring(0, charIndex);

                if(charIndex % 24 === 0) scrollArea.scrollTop = scrollArea.scrollHeight;

            }, 10);

        }



        function buildPrompt() {

            let memoryString = kbTextBlocks.join('\n\n');

            if (memoryString.length > 250000) memoryString = memoryString.substring(0, 250000) + "\n\n...[TRUNCATED]...";



            let chatHistoryMemory = "";

            let currentSession = appHistory.find(s => s.id === currentSessionId);

            if (currentSession && currentSession.interactions.length > 0) {

                chatHistoryMemory = "\n\n=== RECENT CHAT HISTORY ===\n" + currentSession.interactions.slice(-4).map(msg => `USER: ${msg.question}\nAI: ${msg.answer}\n`).join('\n');

            }



            const baseDirectives = `πŸ”΄ CRITICAL INSTRUCTIONS: 

1. Answer in HINDI by default. 

2. Highlight key facts with %%the fact%%. 

3. Use Markdown formatting. 

4. MULTIPLE IMAGES: If multiple images are provided, treat them as a SINGLE continuous document or question. Read across all images to form the complete context before answering. Do not stop at the first image. Solve the FULL question.`;



            return isOnlineMode 

                ? `You are an AI in ONLINE MODE.\n${baseDirectives}\nUse general knowledge. Start exactly with: "⚑ **ONLINE MODE USED TO SOLVE ANSWER**\n\n"\n\n=== CONTEXT ===\n${memoryString}\n${chatHistoryMemory}`

                : `You are a STRICT Extractor.\n${baseDirectives}\nTURN BRAIN OFF. Answer ONLY from sources. If not found, reply exactly: "❌ I cannot find the answer to this question in the provided sources."\n\n=== CONTEXT ===\n${memoryString}\n${chatHistoryMemory}`;

        }



        async function askQuestion() {

            if (isProcessing) return;

            const inputEl = document.getElementById("userInput");

            let question = inputEl.value.trim();

            

            if (!question && chatImages.length === 0) return;

            if (!isOnlineMode && kbFilesUI.length === 0 && chatImages.length === 0) { alert("Upload files on the left to use STRICT MODE, or toggle to 'ONLINE MODE' at the top!"); return; }



            isProcessing = true;

            inputEl.value = ""; resizeInput();

            

            // πŸ›‘ INSTANT BUTTON SWAP

            document.getElementById('sendBtn').style.display = 'none';

            document.getElementById('stopBtn').style.display = 'flex';



            const sidebar = document.getElementById('qaSidebar');

            if (window.innerWidth <= 800 && sidebar.classList.contains('active')) toggleQaSidebar();



            let userImgsHtml = chatImages.map(img => `<img src="${img}" onclick="openFullImage('${img}')" style="max-height:100px; border-radius:10px; margin:5px; border:2px solid white; cursor:zoom-in;">`).join('');

            appendMessage("user", `${userImgsHtml}${userImgsHtml ? '<br>' : ''}${question.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, '<br>')}`);



            const loadId = "load_" + Date.now();

            

            // 🌈 RAINBOW ANIMATION INJECTED

            const thinkingHtml = `

                <div class="rainbow-thinking-bubble">

                    <div class="thinking-status-line">⏳ ${isOnlineMode ? 'Analyzing & Searching...' : 'Scanning Sources...'}</div>

                </div>`;

            appendMessage("ai", thinkingHtml, loadId);



            let allImagesForPayload = [];

            if (kbImages.length > 0) allImagesForPayload.push(...kbImages);

            if (chatImages.length > 0) allImagesForPayload.push(...chatImages);

            chatImages = []; renderChatImgPreview();



            const payload = {

                userPrompt: question || "Describe the contents.", systemPrompt: buildPrompt(),

                imageBase64Array: allImagesForPayload.length > 0 ? allImagesForPayload : null,

                searchStrategy: isOnlineMode ? 'auto' : 'off', webSearchActive: isOnlineMode

            };



            fetchAbortController = new AbortController();



            try {

                const response = await fetch("/api/other", {

                    method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: fetchAbortController.signal

                });



                let data;

                try { data = await response.json(); } catch(e) { throw new Error(`Server crashed (Status: ${response.status}).`); }

                if (!response.ok) throw new Error(data.error || `Server failed with status ${response.status}`);

                if (data.error) throw new Error(data.error);



                let topLabel = data.provider ? `VIA: ${data.provider}` : "AI";

                let rawText = data.text || "No text returned.";

                rawText = rawText.replace(/%%([^%]+?)%%/g, '<span class="answer-highlight">$1</span>');

                const markdownHtml = marked.parse(rawText);

                

                document.getElementById("wrap_" + loadId).innerHTML = `

                    <div class="bubble">

                        <div style="font-size:10px; color:var(--primary); font-weight:900; margin-bottom:10px; text-transform:uppercase;">✨ ${topLabel}</div>

                        <div id="txt_${loadId}" class="markdown-body"></div>

                    </div>`;

                

                // πŸš€ TYPEWRITER CALLBACK RE-ENABLES THE SEND BUTTON

                runFastTypewriter(document.getElementById("txt_" + loadId), markdownHtml, () => {

                    saveInteraction(question, rawText, data.provider || "AI");

                    isProcessing = false;

                    document.getElementById('sendBtn').style.display = 'flex';

                    document.getElementById('stopBtn').style.display = 'none';

                    document.getElementById("userInput").focus();

                });



            } catch (err) {

                if (err.name === 'AbortError') {

                    document.getElementById("wrap_" + loadId).innerHTML = `<div class="bubble" style="border:1px solid #f59e0b; background:rgba(245,158,11,0.1);"><div style="color:#f59e0b; font-weight:bold;">πŸ›‘ Generation Stopped.</div></div>`;

                } else {

                    document.getElementById("wrap_" + loadId).innerHTML = `<div class="bubble" style="border:1px solid #ef4444; background:rgba(239,68,68,0.1);"><div style="color:#ef4444; font-weight:bold; margin-bottom:10px;">❌ Error: ${err.message}</div></div>`;

                }

                // UNLOCK ON ERROR

                isProcessing = false;

                document.getElementById('sendBtn').style.display = 'flex';

                document.getElementById('stopBtn').style.display = 'none';

            }

        }

    </script>
<script>/* keep the existing "leave this page?" warning when using the sidebar */
window.apsBeforeNavigate=function(href){window.__apsPending=href;isBackNav=false;requestExit();return false;};
</script>
<script src="nav-sidebar.js" data-pos="none"></script>
</body>
</html>