Aichatbot12321 commited on
Commit
15e7e4c
·
verified ·
1 Parent(s): 0860f8a

Update qa.html

Browse files
Files changed (1) hide show
  1. qa.html +166 -439
qa.html CHANGED
@@ -5,18 +5,18 @@
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
6
  <title>DOC Q&A - AI PRO SUITE</title>
7
 
 
 
8
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;800&display=swap" rel="stylesheet">
9
 
10
  <!-- FILE PARSING ENGINES -->
11
  <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js"></script>
12
  <script>pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';</script>
13
- <!-- MAMMOTH.JS FOR WORD DOCX SUPPORT -->
14
  <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
15
-
16
  <script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>
17
  <script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
18
 
19
- <!-- MATHJAX INJECTION FOR EQUATION FORMATTING -->
20
  <script>
21
  MathJax = {
22
  options: { ignoreHtmlClass: 'code-box', processHtmlClass: 'markdown-body' },
@@ -27,278 +27,143 @@
27
  <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
28
 
29
  <style>
30
- /* 🛡️ ULTIMATE OVERFLOW KILLER FOR MOBILE */
31
- * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
32
- html, body { margin: 0; padding: 0; max-width: 100vw !important; overflow-x: hidden !important; }
33
-
34
- :root {
35
- --primary: #8b5cf6;
36
- --primary-glow: rgba(139, 92, 246, 0.4);
37
- --secondary: #3b82f6;
38
- --bg-base: #0b0f19;
39
- --bg-surface: #1e293b;
40
- --text-main: #f8fafc;
41
- --text-muted: #94a3b8;
42
- --border-light: #334155;
43
  }
44
-
45
- body { font-family: 'Poppins', sans-serif; background: var(--bg-base); color: var(--text-main); height: 100vh; display: flex; flex-direction: column; }
46
-
47
- ::-webkit-scrollbar { width: 6px; height: 6px; }
48
- ::-webkit-scrollbar-track { background: transparent; }
49
- ::-webkit-scrollbar-thumb { background: var(--border-light); border-radius: 10px; transition: 0.3s; }
50
- ::-webkit-scrollbar-thumb:hover { background: var(--primary); }
51
-
52
- .topbar { padding: 15px 20px; width: 100%; background: rgba(30, 41, 59, 0.85); backdrop-filter: blur(20px); border-bottom: 1px solid var(--border-light); display: flex; justify-content: space-between; align-items: center; z-index: 100; box-shadow: 0 4px 30px rgba(0,0,0,0.3); }
53
- .title { font-size: 20px; font-weight: 900; letter-spacing: 1px; display: flex; align-items: center; gap: 12px; background: linear-gradient(90deg, #a855f7, #3b82f6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
54
 
55
- .main-container { display: flex; flex: 1; overflow: hidden; position: relative; width: 100%; max-width: 100vw; }
56
-
57
- /* LEFT SIDE: KNOWLEDGE BASE */
58
- .upload-pane { width: 35%; background: var(--bg-surface); border-right: 1px solid var(--border-light); padding: 25px; display: flex; flex-direction: column; position: relative; z-index: 10; box-shadow: 5px 0 20px rgba(0,0,0,0.2); transition: 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); }
59
- .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: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); position: relative; overflow: hidden; }
60
- .drop-zone:hover { background: rgba(139, 92, 246, 0.15); transform: translateY(-2px); border-color: #a855f7; box-shadow: 0 10px 25px var(--primary-glow); }
61
- .drop-icon { font-size: 45px; margin-bottom: 10px; animation: float 3s infinite ease-in-out; }
62
- .kb-list { flex: 1; overflow-y: auto; overflow-x: hidden; margin-top: 20px; display: flex; flex-direction: column; gap: 10px; padding-right: 5px; }
63
-
64
- .kb-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 12px 15px; border-radius: 12px; border: 1px solid var(--border-light); animation: popIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); transition: 0.2s; max-width: 100%; }
65
- .kb-item:hover { border-color: var(--primary); transform: translateX(5px); }
66
- .kb-item-info { display: flex; align-items: center; gap: 10px; overflow: hidden; }
67
- .kb-item-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-main); }
68
- .kb-item-del { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: none; border-radius: 50%; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: 0.2s; font-weight: bold; flex-shrink: 0; }
69
- .kb-item-del:hover { background: #ef4444; color: white; transform: scale(1.15) rotate(90deg); }
70
-
71
- /* RIGHT SIDE: CHAT ZONE */
72
- .chat-pane { flex: 1; display: flex; flex-direction: column; background: var(--bg-base); position: relative; width: 100%; max-width: 100vw; overflow: hidden; }
73
- .chat-history { flex: 1; overflow-y: auto; overflow-x: hidden; padding: 30px 20px; display: flex; flex-direction: column; gap: 20px; scroll-behavior: smooth; width: 100%; max-width: 100vw; }
74
-
75
- /* 🛡️ AGGRESSIVE TEXT OVERFLOW HANDLING */
76
- .chat-msg { display: flex; flex-direction: column; width: 100%; max-width: 100%; animation: slideUpPop 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; transform-origin: bottom center; }
77
- .bubble { max-width: 95%; padding: 16px 20px; border-radius: 20px; font-size: 14.5px; line-height: 1.6; position: relative; box-shadow: 0 4px 15px rgba(0,0,0,0.1); word-break: break-word; overflow-wrap: break-word; overflow-x: auto; }
78
- .chat-user { align-items: flex-end; }
79
- .chat-user .bubble { background: linear-gradient(135deg, var(--primary), var(--secondary)); color: white; border-bottom-right-radius: 4px; box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3); }
80
- .chat-ai { align-items: flex-start; }
81
- .chat-ai .bubble { background: var(--bg-surface); border: 1px solid var(--border-light); border-bottom-left-radius: 4px; width: 100%; }
82
 
83
- .markdown-body { max-width: 100%; overflow-x: hidden; word-wrap: break-word; }
84
- .markdown-body p { margin-top: 0; margin-bottom: 10px; max-width: 100%; }
85
- .markdown-body pre { background: #0d1117; padding: 15px; border-radius: 12px; overflow-x: auto; border: 1px solid #30363d; font-family: monospace; font-size: 13px; box-shadow: inset 0 2px 10px rgba(0,0,0,0.5); max-width: 100%; white-space: pre-wrap; word-break: break-word; }
86
- .markdown-body code { font-family: monospace; background: rgba(0,0,0,0.3); padding: 2px 5px; border-radius: 6px; color: #a855f7; word-break: break-word; white-space: pre-wrap; }
87
- .answer-highlight { background: rgba(59,130,246,0.20); color: #3b82f6; font-weight: 800; padding: 2px 6px; border-radius: 6px; }
88
- body html mjx-container[jax="CHTML"][display="true"] { max-width: 100% !important; overflow-x: auto !important; overflow-y: hidden !important; }
89
 
90
- /* INPUT AREA */
91
- .input-area { padding: 15px 20px; width: 100%; max-width: 100vw; background: var(--bg-surface); border-top: 1px solid var(--border-light); position: relative; z-index: 100; box-shadow: 0 -10px 30px rgba(0,0,0,0.2); display: flex; flex-direction: column; gap: 10px; }
92
-
93
- .chat-images-preview { display: flex; gap: 10px; overflow-x: auto; padding-bottom: 5px; width: 100%; }
94
- .chat-img-thumb { position: relative; width: 65px; height: 65px; border-radius: 12px; border: 2px solid var(--primary); flex-shrink: 0; animation: popIn 0.3s ease; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
95
- .chat-img-thumb img { width: 100%; height: 100%; object-fit: cover; border-radius: 10px; cursor: zoom-in; }
96
- .chat-img-thumb button { position: absolute; top: -8px; right: -8px; background: #ef4444; color: white; border: none; border-radius: 50%; width: 22px; height: 22px; font-size: 12px; font-weight: bold; cursor: pointer; box-shadow: 0 4px 10px rgba(0,0,0,0.5); transition: 0.2s; }
97
- .chat-img-thumb button:hover { transform: scale(1.2); }
98
-
99
- .input-wrapper { display: flex; align-items: flex-end; gap: 8px; width: 100%; max-width: 100%; background: #0b0f19; border: 1px solid var(--border-light); border-radius: 25px; padding: 8px 12px; transition: 0.3s; }
100
- .input-wrapper:focus-within { border-color: var(--primary); box-shadow: 0 0 20px rgba(139, 92, 246, 0.2); }
101
-
102
- .plus-btn { background: none; border: none; font-size: 24px; color: var(--primary); cursor: pointer; padding: 5px; transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); flex-shrink: 0; }
103
- .plus-btn:hover { transform: scale(1.2) rotate(90deg); color: var(--secondary); }
104
-
105
- textarea { flex: 1; min-width: 0; background: transparent; border: none; color: white; font-size: 15px; outline: none; resize: none; padding: 10px 5px; font-family: 'Poppins', sans-serif; max-height: 150px; overflow-y: auto; }
106
 
107
- .send-btn { background: linear-gradient(135deg, var(--primary), var(--secondary)); color: white; border: none; width: 45px; height: 45px; border-radius: 50%; font-size: 18px; cursor: pointer; display: flex; justify-content: center; align-items: center; transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); font-weight: bold; flex-shrink: 0; box-shadow: 0 4px 15px rgba(139, 92, 246, 0.4); }
108
- .send-btn:hover { transform: scale(1.15); box-shadow: 0 8px 25px rgba(139, 92, 246, 0.6); }
109
- .send-btn:active { transform: scale(0.9); }
110
- .send-btn:disabled { background: var(--border-light); cursor: not-allowed; transform: none; box-shadow: none; color: var(--text-muted); }
111
-
112
- .action-btn { background: var(--input-bg); border: 1px solid var(--border-light); color: var(--text-main); padding: 8px 15px; border-radius: 10px; font-size: 12px; font-weight: bold; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 6px; }
113
- .action-btn:hover { background: rgba(139, 92, 246, 0.2); border-color: var(--primary); color: white; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.2); }
114
-
115
- .glass-menu { display: none; position: absolute; bottom: 85px; left: 20px; 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; }
116
- .menu-btn { background: transparent; border: none; color: var(--text-main); padding: 15px; text-align: left; font-size: 14px; font-weight: 600; cursor: pointer; border-bottom: 1px solid var(--border-light); display: flex; align-items: center; gap: 12px; transition: 0.2s; }
117
- .menu-btn:hover { background: rgba(139, 92, 246, 0.2); padding-left: 20px; color: #fff; }
118
 
119
- .modal-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.85); z-index: 9999999; justify-content: center; align-items: center; backdrop-filter: blur(10px); animation: fadeIn 0.3s ease; }
120
-
121
- #fullImageViewer { flex-direction: column; }
122
- .img-gui-topbar { position: absolute; top: 0; left: 0; width: 100%; display: flex; justify-content: flex-end; gap: 15px; padding: 20px 30px; box-sizing: border-box; background: linear-gradient(to bottom, rgba(0,0,0,0.9), transparent); z-index: 10; }
123
- .img-gui-btn { background: rgba(255,255,255,0.15); border: 1px solid rgba(255,255,255,0.4); color: white; padding: 10px 20px; border-radius: 30px; font-size: 14px; font-weight: bold; cursor: pointer; transition: 0.2s; backdrop-filter: blur(5px); }
124
- .img-gui-btn:hover { background: rgba(255,255,255,0.3); transform: scale(1.05); }
125
- .img-gui-btn.close-btn { background: rgba(239, 68, 68, 0.6); border-color: #ef4444; }
126
- .img-gui-btn.close-btn:hover { background: #ef4444; }
127
- #fullImageSrc { max-width: 95%; max-height: 80vh; border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,0.8); object-fit: contain; animation: popIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
128
-
129
- .ai-thinking-box { display: inline-flex; align-items: center; gap: 15px; }
130
- .spinner-ring { width: 20px; height: 20px; border: 3px solid rgba(139, 92, 246, 0.2); border-top-color: var(--primary); border-radius: 50%; animation: spin 1s infinite linear; }
131
-
132
- .mobile-kb-toggle { display: none; background: var(--bg-surface); border: 1px solid var(--border-light); color: var(--text-main); padding: 12px 15px; text-align: center; font-weight: bold; cursor: pointer; z-index: 20; position: relative; width: 100%; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
133
-
134
- /* 📱 FLAWLESS MOBILE OVERLAY DESIGN */
135
  @media (max-width: 800px) {
136
- .topbar { padding: 12px 15px; }
137
- .title { font-size: 16px; }
138
- .mobile-kb-toggle { display: block; border-bottom: 2px solid var(--primary); }
139
-
140
- .upload-pane {
141
- position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
142
- z-index: 999999; display: none; padding: 25px 20px; box-shadow: none;
143
- background: rgba(15, 23, 42, 0.98); backdrop-filter: blur(25px);
144
- border: none; overflow-y: auto;
145
- }
146
- .upload-pane.expanded { display: flex; }
147
-
148
- /* 🔥 THE UNMISSABLE MOBILE CLOSE BUTTON */
149
- .mobile-close-kb-btn {
150
- display: flex !important;
151
- position: absolute; top: 20px; right: 20px;
152
- background: #ef4444; color: white; border: none;
153
- width: 45px; height: 45px; border-radius: 50%;
154
- font-size: 20px; cursor: pointer; z-index: 1000;
155
- justify-content: center; align-items: center;
156
- box-shadow: 0 5px 20px rgba(239, 68, 68, 0.5);
157
- font-weight: 900;
158
  }
159
-
160
- .drop-zone { padding: 20px 15px; margin-top: 50px; }
161
- .drop-icon { font-size: 35px; margin-bottom: 5px; }
162
- .chat-history { padding: 20px 15px; }
163
- .input-area { padding: 12px 15px; }
164
  }
165
-
166
- @keyframes popIn { 0% { opacity: 0; transform: scale(0.9) translateY(10px); } 100% { opacity: 1; transform: scale(1) translateY(0); } }
167
- @keyframes slideUpPop { 0% { opacity: 0; transform: translateY(30px); } 100% { opacity: 1; transform: translateY(0); } }
168
- @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-10px); } }
169
- @keyframes pulse-border { 0% { border-color: rgba(139,92,246,0.2); } 50% { border-color: rgba(139,92,246,1); box-shadow: 0 0 25px rgba(139,92,246,0.5); } 100% { border-color: rgba(139,92,246,0.2); } }
170
- @keyframes spin { 100% { transform: rotate(360deg); } }
171
- @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
172
  </style>
173
  </head>
174
  <body>
175
 
176
- <div class="topbar">
177
- <div class="title">
178
- <button onclick="requestExit()" style="background:none; border:none; font-size:22px; cursor:pointer; transition:0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);" onmouseover="this.style.transform='scale(1.2)'" onmouseout="this.style.transform='scale(1)'">🏠</button>
179
- DOC Q&A
 
180
  </div>
181
-
182
- <!-- STATUS INDICATORS -->
183
- <div style="display:flex; gap:12px; align-items:center;">
184
- <div style="display:flex; flex-direction:column; align-items:flex-end; font-size:10px; font-weight:800; color:var(--text-muted); letter-spacing:0.5px;">
185
- <span id="topOnlineStatus" style="color:#10b981;">🔒 OFFLINE</span>
186
- <span id="topProviderStatus">VIA: STANDBY</span>
187
- </div>
188
 
189
- <!-- ONLINE / OFFLINE TOGGLE BUTTON -->
190
- <button id="modeToggleBtn" style="background: rgba(16, 185, 129, 0.15); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.4); padding: 8px 12px; border-radius: 20px; font-size: 11px; font-weight: 900; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 0 15px rgba(16,185,129,0.2); cursor: pointer; transition: 0.3s;" onclick="toggleAppMode()">
191
- <span id="modeDot" style="display:inline-block; width:8px; height:8px; background:#10b981; border-radius:50%; animation: pulse-border 1.5s infinite;"></span>
192
- <span class="desktop-only" id="modeBtnText">MODE</span>
 
 
193
  </button>
194
  </div>
195
  </div>
196
 
197
- <div class="main-container">
198
- <!-- MOBILE KB TOGGLE -->
199
- <div class="mobile-kb-toggle" onclick="toggleMobileKB()" id="mobileKbBtn">
200
- 📂 Show Knowledge Base (0 files) ▼
201
- </div>
202
-
203
- <!-- UPLOAD PANE (KNOWLEDGE BASE) -->
204
- <div class="upload-pane" id="uploadPane">
205
- <!-- MASSIVE MOBILE CLOSE BUTTON -->
206
- <button class="mobile-close-kb-btn" style="display:none;" onclick="toggleMobileKB()">✖</button>
207
 
208
- <h2 style="margin:0 0 5px 0; font-size:18px; font-weight:900;">Knowledge Base</h2>
209
- <p style="color:var(--text-muted); font-size:12px; margin-bottom:15px; line-height:1.4;">Drop PDFs, DOCX, TXT, CSV or up to 15 Images. <br><span id="modeDescText">AI will ONLY answer based on these files.</span></p>
210
-
211
- <input type="file" id="kbUpload" accept=".txt,.pdf,.docx,.doc,.csv,.md,.json,image/*" multiple style="display:none" onchange="processKbFiles(event)">
212
-
213
- <div class="drop-zone" onclick="document.getElementById('kbUpload').click()" id="dropZone">
214
- <div class="drop-icon">📥</div>
215
- <div style="font-weight: 800; font-size: 15px; color: var(--text-main); letter-spacing: 0.5px;">Click or Drop Files</div>
216
- <div style="font-size: 11px; color: var(--text-muted); margin-top: 5px;">PDF, DOCX, TXT, CSV, Images (Max 15)</div>
217
- </div>
218
 
219
- <div class="kb-list" id="kbList">
220
- <div style="text-align:center; padding: 30px 10px; opacity: 0.6;">
221
- <div style="font-size: 40px; margin-bottom: 10px;">📁</div>
222
- <div style="color:var(--text-main); font-size:14px; font-weight:bold;">No sources loaded</div>
223
- <div style="color:var(--text-muted); font-size:12px; margin-top:5px;">Your files will appear here.</div>
224
- </div>
225
  </div>
226
  </div>
 
227
 
228
- <!-- CHAT PANE -->
229
- <div class="chat-pane">
 
230
  <div class="chat-history" id="chatBox">
231
  <div class="chat-msg chat-ai">
232
- <div class="bubble" style="border: 2px solid var(--primary); background: rgba(139, 92, 246, 0.05); box-shadow: inset 0 0 20px rgba(139, 92, 246, 0.05);">
233
  <div style="font-size:12px; font-weight:900; color:var(--primary); margin-bottom:10px; text-transform:uppercase; letter-spacing:1px;">✨ RAG SYSTEM ONLINE</div>
234
- 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 'MODE' at the top to toggle to ONLINE MODE).</i>
235
  </div>
236
  </div>
237
  </div>
 
 
 
 
 
238
 
239
- <div class="input-area">
240
- <div class="chat-images-preview" id="chatImgPreview"></div>
241
-
242
- <div class="glass-menu" id="plusMenu">
243
- <button class="menu-btn" onclick="openCamera()">📷 Take Photo</button>
244
- <button class="menu-btn" onclick="document.getElementById('chatImgUpload').click()" style="border-bottom:none;">📎 Upload Image</button>
245
- </div>
246
  <input type="file" id="chatImgUpload" accept="image/*" multiple style="display:none" onchange="handleChatImages(event)">
247
-
248
- <div class="input-wrapper">
249
- <button class="plus-btn" onclick="togglePlusMenu(event)">➕</button>
250
- <textarea id="userInput" placeholder="Ask about the documents..." rows="1" oninput="resizeInput()" onkeypress="if(event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); askQuestion(); }"></textarea>
251
- <button class="send-btn" id="sendBtn" onclick="askQuestion()">⬆️</button>
252
- </div>
253
  </div>
254
  </div>
255
  </div>
256
 
257
- <!-- MODALS -->
258
  <!-- FULL SCREEN IMAGE VIEWER -->
259
- <div id="fullImageViewer" class="modal-overlay">
260
- <div class="img-gui-topbar">
261
- <button class="img-gui-btn" onclick="downloadFullImage()">📥 Download</button>
262
- <button class="img-gui-btn close-btn" onclick="closeFullImage()">✖ Close</button>
263
- </div>
264
- <img id="fullImageSrc">
265
- </div>
266
-
267
- <!-- CAMERA MODAL -->
268
- <div id="cameraModal" class="modal-overlay" style="z-index: 9999999;">
269
- <div style="background:#000; width:100%; height:100%; position:relative; display:flex; flex-direction:column;">
270
- <video id="cameraVideo" autoplay playsinline style="width:100%; height:100%; object-fit:cover;"></video>
271
- <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>
272
- <div style="position:absolute; bottom:40px; left:0; width:100%; display:flex; justify-content:center; align-items:center; gap:40px;">
273
- <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 cubic-bezier(0.175, 0.885, 0.32, 1.275);" onmousedown="this.style.transform='scale(0.85)'" onmouseup="this.style.transform='scale(1)'"></div>
274
- <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;" onmouseover="this.style.transform='rotate(180deg)'">🔄</button>
275
- </div>
276
- </div>
277
- <canvas id="captureCanvas" style="display:none;"></canvas>
278
- </div>
279
-
280
- <!-- NAV WARNING TRAP -->
281
- <div id="navWarningModal" class="modal-overlay" style="z-index:10000000;">
282
- <div class="modal-box" style="text-align:center; max-width:320px; border:2px solid #ef4444; background:var(--bg-surface); padding: 25px; border-radius: 20px;">
283
- <div style="font-size:45px; margin-bottom:10px;">⚠️</div>
284
- <h3 style="color:#ef4444; margin:0 0 10px 0; font-weight:900;">Leave Page?</h3>
285
- <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>
286
- <div style="display:flex; gap:10px; width:100%; margin-top:20px;">
287
- <button class="action-btn" style="flex:1; justify-content:center; margin-top:0;" onclick="cancelNav()">Stay</button>
288
- <button class="action-btn" style="flex:1; background:#ef4444; color:white; border:none; justify-content:center; margin-top:0;" onclick="proceedNav()">Leave</button>
289
- </div>
290
  </div>
 
291
  </div>
292
 
293
  <script>
 
 
 
 
 
 
 
 
 
 
 
 
294
  // --- STATE & MEMORY ENGINE ---
295
  let kbTextBlocks = [];
296
  let kbImages = [];
297
  let chatImages = [];
298
  let kbFilesUI = [];
299
  let isProcessing = false;
300
- let camStream = null;
301
- let camFacing = "environment";
302
  let currentFullImg = "";
303
  let isOnlineMode = false;
304
 
@@ -316,65 +181,34 @@
316
  isOnlineMode = !isOnlineMode;
317
  const btn = document.getElementById("modeToggleBtn");
318
  const dot = document.getElementById("modeDot");
319
- const topStatus = document.getElementById("topOnlineStatus");
320
  const desc = document.getElementById("modeDescText");
321
 
322
  if (isOnlineMode) {
323
  btn.style.color = "#3b82f6";
324
  btn.style.borderColor = "rgba(59, 130, 246, 0.4)";
325
  btn.style.background = "rgba(59, 130, 246, 0.15)";
326
- btn.style.boxShadow = "0 0 15px rgba(59, 130, 246, 0.2)";
327
  dot.style.background = "#3b82f6";
328
- topStatus.style.color = "#3b82f6";
329
- topStatus.innerText = "🌐 ONLINE";
330
- desc.innerHTML = "AI will use these files AND its general internet knowledge.";
331
  } else {
332
  btn.style.color = "#10b981";
333
  btn.style.borderColor = "rgba(16, 185, 129, 0.4)";
334
  btn.style.background = "rgba(16, 185, 129, 0.15)";
335
- btn.style.boxShadow = "0 0 15px rgba(16, 185, 129, 0.2)";
336
  dot.style.background = "#10b981";
337
- topStatus.style.color = "#10b981";
338
- topStatus.innerText = "🔒 OFFLINE";
339
  desc.innerHTML = "AI will ONLY answer based on these files.";
340
  }
341
  }
342
 
343
- // --- BACK BUTTON TRAP ENGINE ---
344
- let isBackNav = false;
345
- history.pushState({ trap: true }, null, window.location.href);
346
- window.addEventListener('popstate', function(e) {
347
- isBackNav = true;
348
- document.getElementById('navWarningModal').style.display = 'flex';
349
- history.pushState({ trap: true }, null, window.location.href);
350
- });
351
- window.addEventListener('beforeunload', (e) => {
352
- if (kbFilesUI.length > 0 || chatImages.length > 0) { const msg = "Leave site?"; e.returnValue = msg; return msg; }
353
- });
354
- function requestExit() { document.getElementById('navWarningModal').style.display = 'flex'; }
355
- function cancelNav() { document.getElementById('navWarningModal').style.display = 'none'; isBackNav = false; }
356
- function proceedNav() { window.removeEventListener('beforeunload', null); if (isBackNav) { history.go(-2); } else { window.location.href = 'index.html'; } }
357
-
358
- // --- MOBILE KB TOGGLE ---
359
- function toggleMobileKB() {
360
- const pane = document.getElementById('uploadPane');
361
- const btn = document.getElementById('mobileKbBtn');
362
-
363
- if (pane.classList.contains('expanded')) {
364
- pane.classList.remove('expanded');
365
- btn.innerHTML = `📂 Show Knowledge Base (${kbFilesUI.length} files) ▼`;
366
- } else {
367
- pane.classList.add('expanded');
368
- btn.innerHTML = `📂 Hide Knowledge Base (${kbFilesUI.length} files) ▲`;
369
- }
370
- }
371
- function updateMobileBtnText() {
372
- const btn = document.getElementById('mobileKbBtn');
373
- const isExpanded = document.getElementById('uploadPane').classList.contains('expanded');
374
- btn.innerHTML = `📂 ${isExpanded ? 'Hide' : 'Show'} Knowledge Base (${kbFilesUI.length} files) ${isExpanded ? '▲' : '▼'}`;
375
  }
376
 
377
- // --- FULL IMAGE VIEWER ---
378
  function openFullImage(src) {
379
  currentFullImg = src;
380
  document.getElementById('fullImageSrc').src = src;
@@ -388,75 +222,42 @@
388
  a.click();
389
  }
390
 
391
- // --- UI UTILS ---
392
- function resizeInput() {
393
- const inp = document.getElementById('userInput');
394
- inp.style.height = 'auto';
395
- inp.style.height = Math.min(inp.scrollHeight, 150) + 'px';
396
- }
397
-
398
- function togglePlusMenu(e) {
399
- e.stopPropagation();
400
- const m = document.getElementById("plusMenu");
401
- m.style.display = m.style.display === "flex" ? "none" : "flex";
402
- }
403
- window.onclick = () => { document.getElementById("plusMenu").style.display = "none"; };
404
-
405
  function clearChat() {
406
  if(!confirm("Wipe the chat history? Knowledge base files will be kept.")) return;
407
  document.getElementById("chatBox").innerHTML = `
408
  <div class="chat-msg chat-ai">
409
- <div class="bubble" style="border: 2px solid var(--primary); background: rgba(139, 92, 246, 0.05);">
410
- <div style="font-size:12px; font-weight:900; color:var(--primary); margin-bottom:10px; text-transform:uppercase;">✨ SYSTEM REFRESHED</div>
411
- Chat history wiped. I am still locked to your loaded Knowledge Base.
412
  </div>
413
  </div>`;
414
  currentSessionId = Date.now();
415
  }
416
 
417
- function copyAIResponse(btn, textId) {
418
- const el = document.getElementById(textId);
419
- if (!el) return;
420
- navigator.clipboard.writeText(el.innerText);
421
- const orig = btn.innerHTML;
422
- btn.innerHTML = "✅ Copied";
423
- btn.style.background = "#10b981";
424
- btn.style.color = "white";
425
- setTimeout(() => { btn.innerHTML = orig; btn.style.background = "var(--input-bg)"; btn.style.color = "var(--text-main)"; }, 2000);
426
- }
427
-
428
  function appendMessage(sender, htmlContent, id = "") {
429
  const chatBox = document.getElementById("chatBox");
430
  const msgDiv = document.createElement("div");
431
  msgDiv.className = `chat-msg chat-${sender}`;
432
  if (id) msgDiv.id = "wrap_" + id;
433
 
434
- let innerHtml = `<div class="bubble" ${id ? `id="${id}"` : ''}>${htmlContent}</div>`;
435
- msgDiv.innerHTML = innerHtml;
436
-
437
  chatBox.appendChild(msgDiv);
438
- chatBox.scrollTop = chatBox.scrollHeight;
 
 
439
  }
440
 
441
- window.parseAIFormatting = function(text) {
442
- if (!text) return "";
443
- return text.replace(/%%([^%]+?)%%/g, '<span class="answer-highlight">$1</span>');
444
- };
445
-
446
- // --- 🚀 UNIVERSAL KNOWLEDGE BASE ENGINE (PDF, DOCX, CSV, MD, JSON) ---
447
  async function processKbFiles(event) {
448
  const files = Array.from(event.target.files);
449
  if (!files.length) return;
450
 
451
- const dropZone = document.getElementById("dropZone");
452
- dropZone.style.animation = "pulse-border 1s infinite";
453
-
454
  for (let file of files) {
455
  try {
456
  const ext = file.name.split('.').pop().toLowerCase();
457
 
458
  if (file.type.startsWith("image/")) {
459
- if (kbImages.length >= 15) { alert("Max 15 images allowed in Knowledge Base!"); continue; }
460
  const b64 = await readFileAsBase64(file);
461
  kbImages.push(b64);
462
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'img', index: kbImages.length - 1, src: b64 });
@@ -475,7 +276,7 @@
475
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'pdf', index: kbTextBlocks.length - 1, wordCount: cleanText.split(/\s+/).length });
476
  }
477
  else if (ext === "docx" || file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
478
- // 🌟 MAMMOTH.JS WORD DOCX SUPPORT
479
  const arrayBuffer = await file.arrayBuffer();
480
  const result = await mammoth.extractRawText({arrayBuffer: arrayBuffer});
481
  const cleanText = result.value.replace(/\s+/g, ' ').trim();
@@ -483,7 +284,6 @@
483
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'docx', index: kbTextBlocks.length - 1, wordCount: cleanText.split(/\s+/).length });
484
  }
485
  else {
486
- // FALLBACK FOR TXT, CSV, JSON, MD
487
  const text = await file.text();
488
  kbTextBlocks.push(`[FILE: ${file.name}]\n${text.trim()}`);
489
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'txt', index: kbTextBlocks.length - 1, wordCount: text.split(/\s+/).length });
@@ -493,10 +293,8 @@
493
  }
494
  }
495
 
496
- dropZone.style.animation = "none";
497
  event.target.value = "";
498
  renderKbList();
499
- updateMobileBtnText();
500
  }
501
 
502
  function readFileAsBase64(file) {
@@ -515,7 +313,6 @@
515
  <div style="text-align:center; padding: 30px 10px; opacity: 0.6;">
516
  <div style="font-size: 40px; margin-bottom: 10px;">📁</div>
517
  <div style="color:var(--text-main); font-size:14px; font-weight:bold;">No sources loaded</div>
518
- <div style="color:var(--text-muted); font-size:12px; margin-top:5px;">Your files will appear here.</div>
519
  </div>`;
520
  return;
521
  }
@@ -529,14 +326,14 @@
529
 
530
  return `
531
  <div class="kb-item">
532
- <div class="kb-item-info">
533
  ${iconHtml}
534
  <div style="display:flex; flex-direction:column; min-width:0;">
535
- <div class="kb-item-name" title="${f.name}">${f.name}</div>
536
  ${statsHtml}
537
  </div>
538
  </div>
539
- <button class="kb-item-del" onclick="deleteKbItem(${i})" title="Remove file">✕</button>
540
  </div>`;
541
  }).join('');
542
  }
@@ -557,10 +354,8 @@
557
  kbFilesUI.forEach(f => { if (f.type !== 'img') { f.index = txtIdx++; } });
558
 
559
  renderKbList();
560
- updateMobileBtnText();
561
  }
562
 
563
- // --- CHAT IMAGES & CAMERA ---
564
  async function handleChatImages(event) {
565
  const files = Array.from(event.target.files);
566
  for (let f of files) {
@@ -572,40 +367,19 @@
572
  renderChatImgPreview();
573
  }
574
 
575
- async function openCamera() {
576
- document.getElementById('cameraModal').style.display='flex';
577
- try {
578
- if(camStream) camStream.getTracks().forEach(t => t.stop());
579
- camStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: camFacing, width: {ideal: 1280}, height: {ideal: 720} } });
580
- document.getElementById("cameraVideo").srcObject = camStream;
581
- } catch(e) { alert("Camera access denied."); closeCamera(); }
582
- }
583
- function closeCamera() { document.getElementById('cameraModal').style.display='none'; if(camStream) camStream.getTracks().forEach(t=>t.stop()); }
584
- async function switchCamera() { camFacing = camFacing === "environment" ? "user" : "environment"; await openCamera(); }
585
- function takePhoto() {
586
- if(chatImages.length >= 5) { alert("Max 5 images per question!"); closeCamera(); return; }
587
- const v = document.getElementById("cameraVideo"), c = document.getElementById("captureCanvas");
588
- c.width = v.videoWidth; c.height = v.videoHeight;
589
- c.getContext("2d").drawImage(v, 0, 0, c.width, c.height);
590
- chatImages.push(c.toDataURL("image/jpeg", 0.7));
591
- renderChatImgPreview();
592
- closeCamera();
593
- }
594
-
595
  function renderChatImgPreview() {
596
  const container = document.getElementById("chatImgPreview");
597
  if (!chatImages.length) { container.style.display = "none"; return; }
598
  container.style.display = "flex";
599
  container.innerHTML = chatImages.map((img, i) => `
600
- <div class="chat-img-thumb">
601
- <img src="${img}" onclick="openFullImage('${img}')">
602
- <button onclick="chatImages.splice(${i},1); renderChatImgPreview();">✕</button>
603
  </div>
604
  `).join('');
605
  }
606
 
607
- // --- MEMORY SAVER (LocalForage) ---
608
- function saveInteraction(q, a, imgs, provider) {
609
  if (typeof localforage === 'undefined') return;
610
 
611
  let sessionIndex = appHistory.findIndex(s => s.id === currentSessionId);
@@ -622,7 +396,6 @@
622
  id: "msg_" + Date.now(),
623
  question: q,
624
  answer: a,
625
- images: imgs || [],
626
  timestamp: Date.now(),
627
  provider: provider
628
  });
@@ -633,14 +406,19 @@
633
  localforage.setItem('aiHistory', appHistory);
634
  }
635
 
636
- // --- TYPEWRITER ENGINE ---
637
- function runInsaneTypewriter(targetElement, fullHtml, callback) {
638
  let tempDiv = document.createElement('div'); tempDiv.innerHTML = fullHtml;
639
  let nodes = Array.from(tempDiv.childNodes); targetElement.innerHTML = ""; let nodeIndex = 0;
640
- const chatBox = document.getElementById("chatBox");
641
 
642
  function typeNextNode() {
643
- if (nodeIndex >= nodes.length) { if(callback) callback(); return; }
 
 
 
 
 
 
644
  let currentNode = nodes[nodeIndex].cloneNode(true);
645
  if (currentNode.nodeType === Node.TEXT_NODE) {
646
  let text = currentNode.textContent; let span = document.createElement('span'); targetElement.appendChild(span); let charIndex = 0;
@@ -650,14 +428,13 @@
650
  } else {
651
  span.textContent += text.substring(charIndex, charIndex + 2);
652
  charIndex += 2;
653
- if(charIndex % 10 === 0) chatBox.scrollTop = chatBox.scrollHeight;
654
  }
655
  }, 5);
656
  } else { targetElement.appendChild(currentNode); nodeIndex++; typeNextNode(); }
657
  } typeNextNode();
658
  }
659
 
660
- // --- CORE FETCH ENGINE ---
661
  function buildPrompt() {
662
  let memoryString = kbTextBlocks.join('\n\n');
663
  if (memoryString.length > 250000) {
@@ -667,7 +444,7 @@
667
  let chatHistoryMemory = "";
668
  let currentSession = appHistory.find(s => s.id === currentSessionId);
669
  if (currentSession && currentSession.interactions.length > 0) {
670
- chatHistoryMemory = "\n\n=== RECENT CHAT HISTORY (MEMORY) ===\n";
671
  currentSession.interactions.slice(-4).forEach(msg => {
672
  chatHistoryMemory += `USER: ${msg.question}\nAI: ${msg.answer}\n\n`;
673
  });
@@ -675,19 +452,18 @@
675
 
676
  const baseDirectives = `
677
  🔴 CRITICAL INSTRUCTIONS:
678
- 1. LANGUAGE: You MUST answer in HINDI by default, unless the user specifically asks to reply in another language.
679
- 2. USER INSTRUCTIONS: You MUST strictly respect and follow any specific instructions given by the user in the prompt.
680
- 3. Highlight key factual words, specific numbers, or core answers by wrapping them in double percent signs like this: %%the fact%%.
681
- 4. Use Markdown formatting. Use bolding and lists to make it readable.
682
  `;
683
 
684
  if (!isOnlineMode) {
685
  return `You are a STRICT Document Intelligence Extractor.
686
- YOUR ONLY JOB is to read the attached documents/images and answer the user's question based STRICTLY and EXCLUSIVELY on them.
687
 
688
  ${baseDirectives}
689
- 5. DO NOT use your general world knowledge. Turn your brain OFF.
690
- 6. If the answer is NOT explicitly stated in the provided text or images, you MUST reply exactly with: "❌ I cannot find the answer to this question in the provided sources." Do not guess or assume.
691
 
692
  === SOURCE DOCUMENT CONTEXT ===
693
  ${memoryString}
@@ -697,9 +473,8 @@ ${chatHistoryMemory}`;
697
  return `You are an intelligent AI Assistant operating in ONLINE MODE.
698
 
699
  ${baseDirectives}
700
- 5. You MUST use your general knowledge and logic to answer the user's query perfectly.
701
- 6. If the user provided any source text below, you can refer to it, but you are not restricted by it.
702
- 7. You MUST start your response exactly with this phrase: "⚡ **ONLINE MODE USED TO SOLVE ANSWER**\n\n"
703
 
704
  === SOURCE DOCUMENT CONTEXT (IF ANY) ===
705
  ${memoryString}
@@ -708,28 +483,6 @@ ${chatHistoryMemory}`;
708
  }
709
  }
710
 
711
- // RETRY CACHE
712
- window.__retryCache = window.__retryCache || {};
713
-
714
- window.triggerRetry = function(loadId) {
715
- const cache = window.__retryCache[loadId];
716
- if (!cache) return;
717
-
718
- chatImages = cache.images || [];
719
- renderChatImgPreview();
720
- document.getElementById("userInput").value = cache.prompt;
721
- resizeInput();
722
-
723
- const wrap = document.getElementById("wrap_" + loadId);
724
- if (wrap) {
725
- if (wrap.previousElementSibling && wrap.previousElementSibling.classList.contains('chat-user')) {
726
- wrap.previousElementSibling.remove();
727
- }
728
- wrap.remove();
729
- }
730
- askQuestion();
731
- };
732
-
733
  async function askQuestion() {
734
  if (isProcessing) return;
735
  const inputEl = document.getElementById("userInput");
@@ -737,9 +490,8 @@ ${chatHistoryMemory}`;
737
  let question = inputEl.value.trim();
738
 
739
  if (!question && chatImages.length === 0) return;
740
-
741
  if (!isOnlineMode && kbFilesUI.length === 0 && chatImages.length === 0) {
742
- alert("Upload files on the left to use STRICT MODE, or toggle to 'ONLINE MODE' at the top to ask general questions!");
743
  return;
744
  }
745
 
@@ -749,30 +501,27 @@ ${chatHistoryMemory}`;
749
  btnEl.disabled = true;
750
  btnEl.innerHTML = "⏳";
751
 
 
 
 
 
 
 
752
  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('');
753
  appendMessage("user", `${userImgsHtml}${userImgsHtml ? '<br>' : ''}${question.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, '<br>')}`);
754
 
755
  const loadId = "load_" + Date.now();
756
-
757
- const thinkingHtml = `
758
- <div class="ai-thinking-box" style="padding:10px 0; background:transparent; border:none; box-shadow:none;">
759
- <div class="spinner-ring"></div>
760
- <div style="font-weight:900; color:var(--primary); font-size:13px; letter-spacing:1px; text-transform:uppercase;">${isOnlineMode ? 'Analyzing & Searching...' : 'Scanning Sources...'}</div>
761
- </div>`;
762
- appendMessage("ai", thinkingHtml, loadId);
763
 
764
  let allImagesForPayload = [];
765
  if (kbImages.length > 0) allImagesForPayload.push(...kbImages);
766
  if (chatImages.length > 0) allImagesForPayload.push(...chatImages);
767
 
768
- const savedImagesForRetry = [...chatImages];
769
- const savedPromptForRetry = question;
770
-
771
  chatImages = [];
772
  renderChatImgPreview();
773
 
774
  const payload = {
775
- userPrompt: question || "Describe the contents of the attached images/documents.",
776
  systemPrompt: buildPrompt(),
777
  imageBase64Array: allImagesForPayload.length > 0 ? allImagesForPayload : null,
778
  searchStrategy: isOnlineMode ? 'auto' : 'off',
@@ -781,58 +530,36 @@ ${chatHistoryMemory}`;
781
 
782
  try {
783
  const response = await fetch("/api/other", {
784
- method: "POST",
785
- headers: { "Content-Type": "application/json" },
786
- body: JSON.stringify(payload)
787
  });
788
 
789
  let data;
790
- try {
791
- data = await response.json();
792
- } catch(e) {
793
- throw new Error(`Server crashed or returned invalid JSON (Status: ${response.status}).`);
794
- }
795
 
796
- if (!response.ok) {
797
- throw new Error(data.error || `Server failed with status ${response.status}`);
798
- }
799
-
800
  if (data.error) throw new Error(data.error);
801
 
802
- if (data.provider) {
803
- document.getElementById("topProviderStatus").innerText = "VIA: " + data.provider;
804
- }
805
-
806
- let finalCleanText = window.parseAIFormatting(data.text || "No text returned.");
807
- const markdownHtml = marked.parse(finalCleanText);
808
 
809
- document.getElementById(loadId).innerHTML = `<div id="txt_${loadId}" class="markdown-body"></div>`;
 
810
 
811
- runInsaneTypewriter(document.getElementById("txt_" + loadId), markdownHtml, () => {
812
-
813
- if(window.MathJax) {
814
- MathJax.typesetClear([document.getElementById("txt_" + loadId)]);
815
- MathJax.typesetPromise([document.getElementById("txt_" + loadId)]);
816
- }
817
-
818
- saveInteraction(question, finalCleanText, savedImagesForRetry, data.provider || "AI");
819
-
820
- const wrap = document.getElementById("wrap_" + loadId);
821
- if (wrap) {
822
- const btnHtml = `<button class="action-btn" style="margin-top:15px;" onclick="copyAIResponse(this, 'txt_${loadId}')">📋 Copy Text</button>`;
823
- document.getElementById(loadId).insertAdjacentHTML('afterend', btnHtml);
824
- }
825
- const chatBox = document.getElementById("chatBox");
826
- chatBox.scrollTop = chatBox.scrollHeight;
827
- });
828
 
829
  } catch (err) {
830
- window.__retryCache[loadId] = { prompt: savedPromptForRetry, images: savedImagesForRetry };
831
-
832
  document.getElementById(loadId).innerHTML = `
833
- <div style="border:1px solid #ef4444; background:rgba(239,68,68,0.1); padding:15px; border-radius:12px;">
834
  <div style="color:#ef4444; font-weight:bold; margin-bottom:10px;">❌ Error: ${err.message}</div>
835
- <button class="action-btn" style="background:#ef4444; color:white; border:none; margin:0;" onclick="triggerRetry('${loadId}')">🔄 Retry</button>
836
  </div>`;
837
  }
838
 
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
6
  <title>DOC Q&A - AI PRO SUITE</title>
7
 
8
+ <!-- 🔗 LINKED DIRECTLY TO YOUR MASTER CSS ENGINE -->
9
+ <link rel="stylesheet" href="style.css">
10
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;800&display=swap" rel="stylesheet">
11
 
12
  <!-- FILE PARSING ENGINES -->
13
  <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js"></script>
14
  <script>pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';</script>
 
15
  <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
 
16
  <script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>
17
  <script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
18
 
19
+ <!-- MATHJAX INJECTION -->
20
  <script>
21
  MathJax = {
22
  options: { ignoreHtmlClass: 'code-box', processHtmlClass: 'markdown-body' },
 
27
  <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
28
 
29
  <style>
30
+ /* 🛡️ STRICT DESKTOP SPLIT & MOBILE RESPONSIVE FIXES */
31
+ .qa-sidebar {
32
+ position: fixed; top: 70px; left: 0; bottom: 0; width: 350px;
33
+ background: var(--bg-surface); border-right: 1px solid var(--border-light);
34
+ padding: 20px; overflow-y: auto; z-index: 10;
35
+ transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
 
 
 
 
 
 
 
36
  }
 
 
 
 
 
 
 
 
 
 
37
 
38
+ .qa-main {
39
+ margin-left: 350px; position: relative; height: 100dvh;
40
+ display: flex; flex-direction: column;
41
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ .qa-input-area {
44
+ left: 350px !important; width: calc(100% - 350px) !important;
45
+ }
 
 
 
46
 
47
+ .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; }
48
+ .drop-zone:hover { background: rgba(139, 92, 246, 0.15); border-color: var(--secondary); }
49
+ .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; }
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ .answer-highlight { background: rgba(59,130,246,0.20); color: #3b82f6; font-weight: 800; padding: 2px 6px; border-radius: 6px; }
 
 
 
 
 
 
 
 
 
 
52
 
53
+ /* 📱 MOBILE OVERRIDES */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  @media (max-width: 800px) {
55
+ .qa-sidebar {
56
+ top: 0; width: 100vw; z-index: 9999999;
57
+ background: var(--bg-base); border: none;
58
+ transform: translateY(100%); /* Hidden strictly off-screen by default */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  }
60
+ .qa-sidebar.active { transform: translateY(0); }
61
+ .qa-main { margin-left: 0; }
62
+ .qa-input-area { left: 0 !important; width: 100% !important; }
 
 
63
  }
 
 
 
 
 
 
 
64
  </style>
65
  </head>
66
  <body>
67
 
68
+ <!-- 🌐 TOPBAR (Using your style.css classes) -->
69
+ <div class="topbar" id="appTopbar">
70
+ <div style="display:flex; align-items:center; gap:12px; flex:1;">
71
+ <button class="menu-btn" onclick="window.location.href='index.html'" style="background:none; border:none; font-size:24px; color:var(--text-main); cursor:pointer;">🏠</button>
72
+ <div class="appTitle" style="font-size:20px; font-weight:bold; color: var(--text-main); letter-spacing: 1px; margin-left:0;">DOC Q&A</div>
73
  </div>
 
 
 
 
 
 
 
74
 
75
+ <div style="display:flex; gap:10px; align-items:center;">
76
+ <button class="action-btn red" style="padding: 6px 12px; font-size:11px;" onclick="clearChat()">🗑️ Clear</button>
77
+
78
+ <button id="modeToggleBtn" style="background: rgba(16, 185, 129, 0.15); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.4); padding: 8px 12px; border-radius: 20px; font-size: 11px; font-weight: 900; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; transition: 0.3s;" onclick="toggleAppMode()">
79
+ <span id="modeDot" style="display:inline-block; width:8px; height:8px; background:#10b981; border-radius:50%; box-shadow: 0 0 10px #10b981;"></span>
80
+ <span id="modeBtnText">🔒 OFFLINE</span>
81
  </button>
82
  </div>
83
  </div>
84
 
85
+ <!-- 📂 KNOWLEDGE BASE (SIDEBAR ON DESKTOP, OVERLAY ON MOBILE) -->
86
+ <div class="qa-sidebar" id="qaSidebar">
87
+ <!-- 🚨 MOBILE ONLY CLOSE BUTTON -->
88
+ <button class="btn red" style="display: none; width: 100%; margin-bottom: 20px;" id="mobileCloseSidebarBtn" onclick="toggleQaSidebar()">✖ Close Sources & Return to Chat</button>
 
 
 
 
 
 
89
 
90
+ <h2 style="margin:0 0 5px 0; font-size:18px; font-weight:900;">Knowledge Base</h2>
91
+ <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>
92
+
93
+ <input type="file" id="kbUpload" accept=".txt,.pdf,.docx,.csv,.md,.json,image/*" multiple style="display:none" onchange="processKbFiles(event)">
94
+
95
+ <div class="drop-zone" onclick="document.getElementById('kbUpload').click()" id="dropZone">
96
+ <div class="drop-icon">📥</div>
97
+ <div style="font-weight: 800; font-size: 15px; color: var(--text-main);">Click to Add Files</div>
98
+ <div style="font-size: 11px; color: var(--text-muted); margin-top: 5px;">PDF, DOCX, TXT, CSV, Images</div>
99
+ </div>
100
 
101
+ <div id="kbList">
102
+ <div style="text-align:center; padding: 30px 10px; opacity: 0.6;">
103
+ <div style="font-size: 40px; margin-bottom: 10px;">📁</div>
104
+ <div style="color:var(--text-main); font-size:14px; font-weight:bold;">No sources loaded</div>
 
 
105
  </div>
106
  </div>
107
+ </div>
108
 
109
+ <!-- 💬 MAIN CHAT AREA -->
110
+ <div class="qa-main">
111
+ <div class="chat-scroll-area" id="searchScrollArea" style="padding-top: 90px; padding-bottom: 120px;">
112
  <div class="chat-history" id="chatBox">
113
  <div class="chat-msg chat-ai">
114
+ <div class="bubble">
115
  <div style="font-size:12px; font-weight:900; color:var(--primary); margin-bottom:10px; text-transform:uppercase; letter-spacing:1px;">✨ RAG SYSTEM ONLINE</div>
116
+ 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>
117
  </div>
118
  </div>
119
  </div>
120
+ </div>
121
+
122
+ <!-- ⌨️ INPUT AREA (LOCKED TO BOTTOM) -->
123
+ <div class="chat-input-area qa-input-area" id="appInputArea">
124
+ <div class="chat-images-preview" id="chatImgPreview" style="display:none; gap:10px; overflow-x:auto; padding-bottom:5px; width:100%;"></div>
125
 
126
+ <div class="chat-input-wrapper">
127
+ <!-- 📂 MOBILE TOGGLE BUTTON -->
128
+ <button class="chat-action-btn" onclick="toggleQaSidebar()" style="background:transparent; color:var(--primary);" title="Manage Sources">📂</button>
129
+ <button class="chat-action-btn" onclick="document.getElementById('chatImgUpload').click()" style="background:transparent; color:var(--primary);" title="Upload Chat Image">📎</button>
 
 
 
130
  <input type="file" id="chatImgUpload" accept="image/*" multiple style="display:none" onchange="handleChatImages(event)">
131
+
132
+ <textarea id="userInput" placeholder="Ask about the documents..." rows="1" oninput="resizeInput()" onkeypress="if(event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); askQuestion(); }"></textarea>
133
+
134
+ <button class="chat-action-btn send" id="sendBtn" onclick="askQuestion()">⬆️</button>
 
 
135
  </div>
136
  </div>
137
  </div>
138
 
 
139
  <!-- FULL SCREEN IMAGE VIEWER -->
140
+ <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;">
141
+ <div style="position:absolute; top:20px; right:20px; display:flex; gap:10px; z-index:10000000;">
142
+ <button class="btn" onclick="downloadFullImage()">📥</button>
143
+ <button class="btn red" onclick="closeFullImage()">✖</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  </div>
145
+ <img id="fullImageSrc" style="max-width:95%; max-height:80vh; border-radius:15px; object-fit:contain;">
146
  </div>
147
 
148
  <script>
149
+ // --- MOBILE LAYOUT ENGINE ---
150
+ function toggleQaSidebar() {
151
+ const sidebar = document.getElementById('qaSidebar');
152
+ sidebar.classList.toggle('active');
153
+
154
+ // Show close button only on mobile
155
+ const closeBtn = document.getElementById('mobileCloseSidebarBtn');
156
+ if (window.innerWidth <= 800) {
157
+ closeBtn.style.display = sidebar.classList.contains('active') ? 'flex' : 'none';
158
+ }
159
+ }
160
+
161
  // --- STATE & MEMORY ENGINE ---
162
  let kbTextBlocks = [];
163
  let kbImages = [];
164
  let chatImages = [];
165
  let kbFilesUI = [];
166
  let isProcessing = false;
 
 
167
  let currentFullImg = "";
168
  let isOnlineMode = false;
169
 
 
181
  isOnlineMode = !isOnlineMode;
182
  const btn = document.getElementById("modeToggleBtn");
183
  const dot = document.getElementById("modeDot");
184
+ const txt = document.getElementById("modeBtnText");
185
  const desc = document.getElementById("modeDescText");
186
 
187
  if (isOnlineMode) {
188
  btn.style.color = "#3b82f6";
189
  btn.style.borderColor = "rgba(59, 130, 246, 0.4)";
190
  btn.style.background = "rgba(59, 130, 246, 0.15)";
 
191
  dot.style.background = "#3b82f6";
192
+ dot.style.boxShadow = "0 0 10px #3b82f6";
193
+ txt.innerText = "🌐 ONLINE";
194
+ desc.innerHTML = "AI will use these files AND its internet knowledge.";
195
  } else {
196
  btn.style.color = "#10b981";
197
  btn.style.borderColor = "rgba(16, 185, 129, 0.4)";
198
  btn.style.background = "rgba(16, 185, 129, 0.15)";
 
199
  dot.style.background = "#10b981";
200
+ dot.style.boxShadow = "0 0 10px #10b981";
201
+ txt.innerText = "🔒 OFFLINE";
202
  desc.innerHTML = "AI will ONLY answer based on these files.";
203
  }
204
  }
205
 
206
+ function resizeInput() {
207
+ const inp = document.getElementById('userInput');
208
+ inp.style.height = 'auto';
209
+ inp.style.height = Math.min(inp.scrollHeight, 150) + 'px';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  }
211
 
 
212
  function openFullImage(src) {
213
  currentFullImg = src;
214
  document.getElementById('fullImageSrc').src = src;
 
222
  a.click();
223
  }
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  function clearChat() {
226
  if(!confirm("Wipe the chat history? Knowledge base files will be kept.")) return;
227
  document.getElementById("chatBox").innerHTML = `
228
  <div class="chat-msg chat-ai">
229
+ <div class="bubble">
230
+ <div style="font-size:12px; font-weight:900; color:var(--primary); margin-bottom:10px;">✨ SYSTEM REFRESHED</div>
231
+ Chat history wiped. Ready for new questions.
232
  </div>
233
  </div>`;
234
  currentSessionId = Date.now();
235
  }
236
 
 
 
 
 
 
 
 
 
 
 
 
237
  function appendMessage(sender, htmlContent, id = "") {
238
  const chatBox = document.getElementById("chatBox");
239
  const msgDiv = document.createElement("div");
240
  msgDiv.className = `chat-msg chat-${sender}`;
241
  if (id) msgDiv.id = "wrap_" + id;
242
 
243
+ msgDiv.innerHTML = `<div class="bubble">${htmlContent}</div>`;
 
 
244
  chatBox.appendChild(msgDiv);
245
+
246
+ const scrollArea = document.getElementById("searchScrollArea");
247
+ scrollArea.scrollTop = scrollArea.scrollHeight;
248
  }
249
 
250
+ // --- UNIVERSAL KNOWLEDGE BASE ENGINE (PDF, DOCX, CSV, MD, JSON) ---
 
 
 
 
 
251
  async function processKbFiles(event) {
252
  const files = Array.from(event.target.files);
253
  if (!files.length) return;
254
 
 
 
 
255
  for (let file of files) {
256
  try {
257
  const ext = file.name.split('.').pop().toLowerCase();
258
 
259
  if (file.type.startsWith("image/")) {
260
+ if (kbImages.length >= 15) { alert("Max 15 images allowed!"); continue; }
261
  const b64 = await readFileAsBase64(file);
262
  kbImages.push(b64);
263
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'img', index: kbImages.length - 1, src: b64 });
 
276
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'pdf', index: kbTextBlocks.length - 1, wordCount: cleanText.split(/\s+/).length });
277
  }
278
  else if (ext === "docx" || file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
279
+ // 🌟 MAMMOTH.JS DOCX SUPPORT
280
  const arrayBuffer = await file.arrayBuffer();
281
  const result = await mammoth.extractRawText({arrayBuffer: arrayBuffer});
282
  const cleanText = result.value.replace(/\s+/g, ' ').trim();
 
284
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'docx', index: kbTextBlocks.length - 1, wordCount: cleanText.split(/\s+/).length });
285
  }
286
  else {
 
287
  const text = await file.text();
288
  kbTextBlocks.push(`[FILE: ${file.name}]\n${text.trim()}`);
289
  kbFilesUI.push({ id: Date.now()+Math.random(), name: file.name, type: 'txt', index: kbTextBlocks.length - 1, wordCount: text.split(/\s+/).length });
 
293
  }
294
  }
295
 
 
296
  event.target.value = "";
297
  renderKbList();
 
298
  }
299
 
300
  function readFileAsBase64(file) {
 
313
  <div style="text-align:center; padding: 30px 10px; opacity: 0.6;">
314
  <div style="font-size: 40px; margin-bottom: 10px;">📁</div>
315
  <div style="color:var(--text-main); font-size:14px; font-weight:bold;">No sources loaded</div>
 
316
  </div>`;
317
  return;
318
  }
 
326
 
327
  return `
328
  <div class="kb-item">
329
+ <div style="display:flex; align-items:center; gap:10px; overflow:hidden;">
330
  ${iconHtml}
331
  <div style="display:flex; flex-direction:column; min-width:0;">
332
+ <div style="font-size:13px; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${f.name}</div>
333
  ${statsHtml}
334
  </div>
335
  </div>
336
+ <button class="action-btn red" onclick="deleteKbItem(${i})" title="Remove file" style="padding: 6px; border-radius: 50%;">✕</button>
337
  </div>`;
338
  }).join('');
339
  }
 
354
  kbFilesUI.forEach(f => { if (f.type !== 'img') { f.index = txtIdx++; } });
355
 
356
  renderKbList();
 
357
  }
358
 
 
359
  async function handleChatImages(event) {
360
  const files = Array.from(event.target.files);
361
  for (let f of files) {
 
367
  renderChatImgPreview();
368
  }
369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  function renderChatImgPreview() {
371
  const container = document.getElementById("chatImgPreview");
372
  if (!chatImages.length) { container.style.display = "none"; return; }
373
  container.style.display = "flex";
374
  container.innerHTML = chatImages.map((img, i) => `
375
+ <div style="position:relative; width:60px; height:60px; border-radius:10px; border:2px solid var(--primary); flex-shrink:0;">
376
+ <img src="${img}" style="width:100%; height:100%; object-fit:cover; border-radius:8px;">
377
+ <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>
378
  </div>
379
  `).join('');
380
  }
381
 
382
+ function saveInteraction(q, a, provider) {
 
383
  if (typeof localforage === 'undefined') return;
384
 
385
  let sessionIndex = appHistory.findIndex(s => s.id === currentSessionId);
 
396
  id: "msg_" + Date.now(),
397
  question: q,
398
  answer: a,
 
399
  timestamp: Date.now(),
400
  provider: provider
401
  });
 
406
  localforage.setItem('aiHistory', appHistory);
407
  }
408
 
409
+ function runInsaneTypewriter(targetElement, fullHtml) {
 
410
  let tempDiv = document.createElement('div'); tempDiv.innerHTML = fullHtml;
411
  let nodes = Array.from(tempDiv.childNodes); targetElement.innerHTML = ""; let nodeIndex = 0;
412
+ const scrollArea = document.getElementById("searchScrollArea");
413
 
414
  function typeNextNode() {
415
+ if (nodeIndex >= nodes.length) {
416
+ if(window.MathJax) {
417
+ MathJax.typesetClear([targetElement]);
418
+ MathJax.typesetPromise([targetElement]);
419
+ }
420
+ return;
421
+ }
422
  let currentNode = nodes[nodeIndex].cloneNode(true);
423
  if (currentNode.nodeType === Node.TEXT_NODE) {
424
  let text = currentNode.textContent; let span = document.createElement('span'); targetElement.appendChild(span); let charIndex = 0;
 
428
  } else {
429
  span.textContent += text.substring(charIndex, charIndex + 2);
430
  charIndex += 2;
431
+ if(charIndex % 10 === 0) scrollArea.scrollTop = scrollArea.scrollHeight;
432
  }
433
  }, 5);
434
  } else { targetElement.appendChild(currentNode); nodeIndex++; typeNextNode(); }
435
  } typeNextNode();
436
  }
437
 
 
438
  function buildPrompt() {
439
  let memoryString = kbTextBlocks.join('\n\n');
440
  if (memoryString.length > 250000) {
 
444
  let chatHistoryMemory = "";
445
  let currentSession = appHistory.find(s => s.id === currentSessionId);
446
  if (currentSession && currentSession.interactions.length > 0) {
447
+ chatHistoryMemory = "\n\n=== RECENT CHAT HISTORY ===\n";
448
  currentSession.interactions.slice(-4).forEach(msg => {
449
  chatHistoryMemory += `USER: ${msg.question}\nAI: ${msg.answer}\n\n`;
450
  });
 
452
 
453
  const baseDirectives = `
454
  🔴 CRITICAL INSTRUCTIONS:
455
+ 1. LANGUAGE: You MUST answer in HINDI by default, unless the user specifically asks otherwise.
456
+ 2. Highlight key factual words by wrapping them in double percent signs like this: %%the fact%%.
457
+ 3. Use Markdown formatting (bolding, lists, code blocks).
 
458
  `;
459
 
460
  if (!isOnlineMode) {
461
  return `You are a STRICT Document Intelligence Extractor.
462
+ YOUR ONLY JOB is to read the attached documents/images and answer based STRICTLY on them.
463
 
464
  ${baseDirectives}
465
+ 4. DO NOT use your general world knowledge. Turn your brain OFF.
466
+ 5. If the answer is NOT explicitly stated in the provided text, reply exactly with: "❌ I cannot find the answer to this question in the provided sources."
467
 
468
  === SOURCE DOCUMENT CONTEXT ===
469
  ${memoryString}
 
473
  return `You are an intelligent AI Assistant operating in ONLINE MODE.
474
 
475
  ${baseDirectives}
476
+ 4. Use your general knowledge and logic to answer perfectly.
477
+ 5. You MUST start your response exactly with: "⚡ **ONLINE MODE USED TO SOLVE ANSWER**\n\n"
 
478
 
479
  === SOURCE DOCUMENT CONTEXT (IF ANY) ===
480
  ${memoryString}
 
483
  }
484
  }
485
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
  async function askQuestion() {
487
  if (isProcessing) return;
488
  const inputEl = document.getElementById("userInput");
 
490
  let question = inputEl.value.trim();
491
 
492
  if (!question && chatImages.length === 0) return;
 
493
  if (!isOnlineMode && kbFilesUI.length === 0 && chatImages.length === 0) {
494
+ alert("Upload files on the left to use STRICT MODE, or toggle to 'ONLINE MODE' at the top!");
495
  return;
496
  }
497
 
 
501
  btnEl.disabled = true;
502
  btnEl.innerHTML = "⏳";
503
 
504
+ // If user is on mobile and sidebar is open, close it automatically to show chat
505
+ const sidebar = document.getElementById('qaSidebar');
506
+ if (window.innerWidth <= 800 && sidebar.classList.contains('active')) {
507
+ toggleQaSidebar();
508
+ }
509
+
510
  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('');
511
  appendMessage("user", `${userImgsHtml}${userImgsHtml ? '<br>' : ''}${question.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, '<br>')}`);
512
 
513
  const loadId = "load_" + Date.now();
514
+ appendMessage("ai", `<div style="font-weight:900; color:var(--primary); font-size:13px; letter-spacing:1px; text-transform:uppercase;">⏳ ${isOnlineMode ? 'Analyzing & Searching...' : 'Scanning Sources...'}</div>`, loadId);
 
 
 
 
 
 
515
 
516
  let allImagesForPayload = [];
517
  if (kbImages.length > 0) allImagesForPayload.push(...kbImages);
518
  if (chatImages.length > 0) allImagesForPayload.push(...chatImages);
519
 
 
 
 
520
  chatImages = [];
521
  renderChatImgPreview();
522
 
523
  const payload = {
524
+ userPrompt: question || "Describe the contents.",
525
  systemPrompt: buildPrompt(),
526
  imageBase64Array: allImagesForPayload.length > 0 ? allImagesForPayload : null,
527
  searchStrategy: isOnlineMode ? 'auto' : 'off',
 
530
 
531
  try {
532
  const response = await fetch("/api/other", {
533
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload)
 
 
534
  });
535
 
536
  let data;
537
+ try { data = await response.json(); }
538
+ catch(e) { throw new Error(`Server crashed (Status: ${response.status}).`); }
 
 
 
539
 
540
+ if (!response.ok) throw new Error(data.error || `Server failed with status ${response.status}`);
 
 
 
541
  if (data.error) throw new Error(data.error);
542
 
543
+ let topLabel = data.provider ? `VIA: ${data.provider}` : "AI";
 
 
 
 
 
544
 
545
+ let rawText = data.text || "No text returned.";
546
+ rawText = rawText.replace(/%%([^%]+?)%%/g, '<span class="answer-highlight">$1</span>');
547
 
548
+ const markdownHtml = marked.parse(rawText);
549
+
550
+ document.getElementById(loadId).innerHTML = `
551
+ <div class="bubble">
552
+ <div style="font-size:10px; color:var(--primary); font-weight:900; margin-bottom:10px; text-transform:uppercase;">✨ ${topLabel}</div>
553
+ <div id="txt_${loadId}" class="markdown-body"></div>
554
+ </div>`;
555
+
556
+ runInsaneTypewriter(document.getElementById("txt_" + loadId), markdownHtml);
557
+ saveInteraction(question, rawText, data.provider || "AI");
 
 
 
 
 
 
 
558
 
559
  } catch (err) {
 
 
560
  document.getElementById(loadId).innerHTML = `
561
+ <div class="bubble" style="border:1px solid #ef4444; background:rgba(239,68,68,0.1);">
562
  <div style="color:#ef4444; font-weight:bold; margin-bottom:10px;">❌ Error: ${err.message}</div>
 
563
  </div>`;
564
  }
565