mini-chat-bot-widget 0.6.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,31 @@
1
- function _classCallCheck(a, n) {
2
- if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
1
+ function _defineProperty(e, r, t) {
2
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
3
+ value: t,
4
+ enumerable: true,
5
+ configurable: true,
6
+ writable: true
7
+ }) : e[r] = t, e;
3
8
  }
4
- function _defineProperties(e, r) {
5
- for (var t = 0; t < r.length; t++) {
6
- var o = r[t];
7
- o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
9
+ function ownKeys(e, r) {
10
+ var t = Object.keys(e);
11
+ if (Object.getOwnPropertySymbols) {
12
+ var o = Object.getOwnPropertySymbols(e);
13
+ r && (o = o.filter(function (r) {
14
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
15
+ })), t.push.apply(t, o);
8
16
  }
17
+ return t;
9
18
  }
10
- function _createClass(e, r, t) {
11
- return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
12
- writable: false
13
- }), e;
19
+ function _objectSpread2(e) {
20
+ for (var r = 1; r < arguments.length; r++) {
21
+ var t = null != arguments[r] ? arguments[r] : {};
22
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
23
+ _defineProperty(e, r, t[r]);
24
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
25
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
26
+ });
27
+ }
28
+ return e;
14
29
  }
15
30
  function _toPrimitive(t, r) {
16
31
  if ("object" != typeof t || !t) return t;
@@ -20,132 +35,3049 @@ function _toPrimitive(t, r) {
20
35
  if ("object" != typeof i) return i;
21
36
  throw new TypeError("@@toPrimitive must return a primitive value.");
22
37
  }
23
- return (String )(t);
38
+ return ("string" === r ? String : Number)(t);
24
39
  }
25
40
  function _toPropertyKey(t) {
26
41
  var i = _toPrimitive(t, "string");
27
42
  return "symbol" == typeof i ? i : i + "";
28
43
  }
29
44
 
30
- function getDefaultExportFromCjs (x) {
31
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
45
+ // text-chat-screen.js - Text chat screen component
46
+
47
+ class TextChatScreen {
48
+ constructor() {
49
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
50
+ this.placeholder = options.placeholder || "Type your message...";
51
+ this.primaryColor = options.primaryColor || "#1a5c4b";
52
+ this.title = options.title || "Chat Assistant";
53
+ this.onMessage = options.onMessage || (() => {});
54
+ this.onBack = options.onBack || (() => {});
55
+ this.onOpenDrawer = options.onOpenDrawer || (() => {});
56
+ this.onClose = options.onClose || (() => {});
57
+ this.container = null;
58
+ this.messages = options.messages;
59
+ this.sendMessage = options.sendMessage || null;
60
+ this.contentBlocks = options.contentBlocks || [];
61
+ this.onContentBlocksChange = options.onContentBlocksChange || (() => {});
62
+ this.navigateToAudioScreen = options.navigateToAudioScreen;
63
+ // Supported file types
64
+ this.SUPPORTED_FILE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
65
+ }
66
+ render(container) {
67
+ this.container = container;
68
+ this._applyStyles();
69
+ container.innerHTML = "\n <div class=\"text-chat-screen\">\n <div class=\"chat-header\">\n <div class=\"chat-header-content\">\n <button class=\"chat-back\" id=\"text-chat-menu\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-menu-icon lucide-menu\"><path d=\"M4 5h16\"/><path d=\"M4 12h16\"/><path d=\"M4 19h16\"/></svg>\n </button>\n \n <div class=\"chat-header-text\">\n <div class=\"chat-title\">".concat(this.title, "</div>\n </div>\n </div>\n <button class=\"chat-close\" id=\"navigate-to-audio-screen\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-mic-icon lucide-mic\"><path d=\"M12 19v3\"/><path d=\"M19 10v2a7 7 0 0 1-14 0v-2\"/><rect x=\"9\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\"/></svg>\n </button>\n &#8203; &#8203; &#8203;\n <button class=\"chat-close\" id=\"text-chat-close\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </button>\n </div>\n <div class=\"chat-messages\" id=\"chat-messages\">\n <div class=\"chat-welcome\">\n <div class=\"welcome-text\">\uD83D\uDC4B Hello! I'm your AI assistant. How can I help you today?</div>\n </div>\n </div>\n <div class=\"file-attachments-container\" id=\"file-attachments-container\" style=\"display: none;\"></div>\n <div class=\"chat-input-wrapper\">\n <div class=\"file-upload-controls\">\n <input\n type=\"file\"\n id=\"file-upload-input\"\n accept=\"image/jpeg,image/png,image/gif,image/webp\"\n style=\"display: none;\"\n />\n <button id=\"file-upload-button\" class=\"file-upload-button\" title=\"Attach files\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <path d=\"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48\"></path>\n </svg>\n </button>\n </div>\n <input type=\"text\" id=\"chat-input\" placeholder=\"").concat(this.placeholder, "\" autocomplete=\"off\" />\n <button id=\"chat-send\" disabled>\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"13\"></line>\n <polygon points=\"22 2 15 22 11 13 2 9 22 2\"></polygon>\n </svg>\n </button>\n </div>\n </div>\n ");
70
+
71
+ // Bind header events
72
+ const menuBtn = container.querySelector("#text-chat-menu");
73
+ const closeBtn = container.querySelector("#text-chat-close");
74
+ const navigateToAudioBtn = container.querySelector("#navigate-to-audio-screen");
75
+ if (menuBtn) {
76
+ menuBtn.addEventListener("click", () => {
77
+ if (this.onOpenDrawer) {
78
+ this.onOpenDrawer();
79
+ } else if (this.onBack) {
80
+ this.onBack();
81
+ }
82
+ });
83
+ }
84
+ if (closeBtn) {
85
+ closeBtn.addEventListener("click", () => {
86
+ if (this.onClose) this.onClose();
87
+ });
88
+ }
89
+ if (navigateToAudioBtn) {
90
+ navigateToAudioBtn.addEventListener("click", () => {
91
+ if (this.navigateToAudioScreen) this.navigateToAudioScreen();
92
+ });
93
+ }
94
+
95
+ // Bind text chat events
96
+ const input = container.querySelector("#chat-input");
97
+ const sendBtn = container.querySelector("#chat-send");
98
+ const fileInput = container.querySelector("#file-upload-input");
99
+ const fileUploadBtn = container.querySelector("#file-upload-button");
100
+
101
+ // File upload handler
102
+ fileUploadBtn.addEventListener("click", () => {
103
+ fileInput.click();
104
+ });
105
+ fileInput.addEventListener("change", e => {
106
+ this.handleFileUpload(e);
107
+ });
108
+
109
+ // Update send button state based on input and contentBlocks
110
+ const updateSendButton = () => {
111
+ const hasText = input.value.trim().length > 0;
112
+ const hasFiles = this.contentBlocks.length > 0;
113
+ sendBtn.disabled = !(hasText || hasFiles);
114
+ };
115
+ input.addEventListener("input", () => {
116
+ updateSendButton();
117
+ });
118
+ const send = async () => {
119
+ const text = input.value.trim();
120
+ if (!text && this.contentBlocks.length === 0) return;
121
+
122
+ // Add user message to UI immediately
123
+ this.addMessage(text || "📎 File attachments", true);
124
+ input.value = "";
125
+ sendBtn.disabled = true;
126
+ this.hideTypingIndicator();
127
+
128
+ // Use the sendMessage function from widget if available
129
+ if (this.sendMessage) {
130
+ try {
131
+ await this.sendMessage(text, this.contentBlocks);
132
+ // Content blocks are cleared in widget's sendMessage, but ensure UI is updated
133
+ this.contentBlocks = [];
134
+ this.onContentBlocksChange(this.contentBlocks);
135
+ this.renderFilePreview(); // Update preview
136
+ this.updateSendButton();
137
+ } catch (error) {
138
+ console.error("Error sending message:", error);
139
+ this.addMessage("Sorry, I encountered an error. Please try again.", false);
140
+ } finally {
141
+ this.hideTypingIndicator();
142
+ }
143
+ } else {
144
+ // Fallback to old behavior
145
+ setTimeout(() => {
146
+ this.hideTypingIndicator();
147
+ this.handleUserMessage(text);
148
+ }, 1000 + Math.random() * 1000);
149
+ }
150
+ };
151
+ sendBtn.addEventListener("click", send);
152
+ input.addEventListener("keypress", e => {
153
+ if (e.key === "Enter" && !sendBtn.disabled) send();
154
+ });
155
+
156
+ // Focus input when screen loads
157
+ setTimeout(() => input.focus(), 100);
158
+
159
+ // Render file preview if contentBlocks exist
160
+ this.renderFilePreview();
161
+
162
+ // Sync existing messages on render
163
+ if (this.messages && this.messages.length > 0) {
164
+ setTimeout(() => {
165
+ this._syncMessages(this.messages);
166
+ }, 50);
167
+ }
168
+ }
169
+
170
+ // Convert file to content block
171
+ fileToContentBlock(file) {
172
+ return new Promise((resolve, reject) => {
173
+ const reader = new FileReader();
174
+ reader.onload = () => {
175
+ const base64Data = reader.result.split(",")[1]; // Remove data:mime;base64, prefix
176
+
177
+ if (this.SUPPORTED_FILE_TYPES.includes(file.type)) {
178
+ resolve({
179
+ type: "image",
180
+ source_type: "base64",
181
+ mime_type: file.type,
182
+ data: base64Data,
183
+ metadata: {
184
+ name: file.name,
185
+ size: file.size
186
+ }
187
+ });
188
+ } else {
189
+ reject(new Error("Unsupported file type: ".concat(file.type)));
190
+ }
191
+ };
192
+ reader.onerror = () => {
193
+ reject(new Error("Failed to read file: ".concat(file.name)));
194
+ };
195
+ reader.readAsDataURL(file);
196
+ });
197
+ }
198
+
199
+ // Check if file is duplicate
200
+ isDuplicateFile(file, existingBlocks) {
201
+ if (this.SUPPORTED_FILE_TYPES.includes(file.type)) {
202
+ return existingBlocks.some(block => {
203
+ var _block$metadata;
204
+ return block.type === "image" && ((_block$metadata = block.metadata) === null || _block$metadata === void 0 ? void 0 : _block$metadata.name) === file.name && block.mime_type === file.type;
205
+ });
206
+ }
207
+ return false;
208
+ }
209
+
210
+ // Format file size
211
+ formatFileSize(bytes) {
212
+ if (bytes === 0) return "0 Bytes";
213
+ const k = 1024;
214
+ const sizes = ["Bytes", "KB", "MB", "GB"];
215
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
216
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
217
+ }
218
+
219
+ // Get file type display name
220
+ getFileTypeDisplay(mimeType) {
221
+ switch (mimeType) {
222
+ case "image/jpeg":
223
+ case "image/jpg":
224
+ return "JPEG Image";
225
+ case "image/png":
226
+ return "PNG Image";
227
+ case "image/gif":
228
+ return "GIF Image";
229
+ case "image/webp":
230
+ return "WebP Image";
231
+ default:
232
+ return "Unknown File";
233
+ }
234
+ }
235
+
236
+ // Handle file upload
237
+ async handleFileUpload(e) {
238
+ const files = e.target.files;
239
+ if (!files) return;
240
+ const fileArray = Array.from(files);
241
+ const validFiles = fileArray.filter(file => this.SUPPORTED_FILE_TYPES.includes(file.type));
242
+ const invalidFiles = fileArray.filter(file => !this.SUPPORTED_FILE_TYPES.includes(file.type));
243
+ if (invalidFiles.length > 0) {
244
+ console.warn("Invalid file type. Please upload a JPEG, PNG, GIF, or WEBP image.");
245
+ // Could show a toast/alert here
246
+ }
247
+
248
+ // Since we only allow 1 file, we take the first valid one and replace existing
249
+ const fileToProcess = validFiles[0];
250
+ if (fileToProcess) {
251
+ try {
252
+ const newBlocks = await this.fileToContentBlock(fileToProcess);
253
+ // Replace existing blocks with new one
254
+ this.contentBlocks = [newBlocks];
255
+ this.onContentBlocksChange(this.contentBlocks);
256
+ this.renderFilePreview();
257
+ this.updateSendButton();
258
+ } catch (error) {
259
+ console.error("Failed to process files: ".concat(error.message));
260
+ }
261
+ }
262
+
263
+ // Clear the input
264
+ e.target.value = "";
265
+ }
266
+
267
+ // Remove content block
268
+ removeBlock(index) {
269
+ this.contentBlocks = this.contentBlocks.filter((_, i) => i !== index);
270
+ this.onContentBlocksChange(this.contentBlocks);
271
+ this.renderFilePreview();
272
+ this.updateSendButton();
273
+ }
274
+
275
+ // Update send button state
276
+ updateSendButton() {
277
+ if (!this.container) return;
278
+ const input = this.container.querySelector("#chat-input");
279
+ const sendBtn = this.container.querySelector("#chat-send");
280
+ if (!input || !sendBtn) return;
281
+ const hasText = input.value.trim().length > 0;
282
+ const hasFiles = this.contentBlocks.length > 0;
283
+ sendBtn.disabled = !(hasText || hasFiles);
284
+ }
285
+
286
+ // Render file preview
287
+ renderFilePreview() {
288
+ if (!this.container) return;
289
+ const container = this.container.querySelector("#file-attachments-container");
290
+ if (!container) return;
291
+ if (!this.contentBlocks || this.contentBlocks.length === 0) {
292
+ container.innerHTML = "";
293
+ container.style.display = "none";
294
+ return;
295
+ }
296
+ container.style.display = "flex";
297
+ container.innerHTML = this.contentBlocks.map((block, index) => {
298
+ var _block$metadata2, _block$metadata3, _block$metadata4;
299
+ const displayName = ((_block$metadata2 = block.metadata) === null || _block$metadata2 === void 0 ? void 0 : _block$metadata2.filename) || ((_block$metadata3 = block.metadata) === null || _block$metadata3 === void 0 ? void 0 : _block$metadata3.name) || "file";
300
+ const size = this.formatFileSize(((_block$metadata4 = block.metadata) === null || _block$metadata4 === void 0 ? void 0 : _block$metadata4.size) || 0);
301
+ const isImage = block.type === "image";
302
+ const src = isImage ? "data:".concat(block.mime_type, ";base64,").concat(block.data) : null;
303
+ return "\n <div class=\"file-attachment ".concat(isImage ? "has-thumbnail" : "", "\" data-index=\"").concat(index, "\">\n ").concat(isImage ? "\n <div class=\"file-thumbnail\">\n <img src=\"".concat(src, "\" alt=\"").concat(displayName, "\" class=\"file-thumbnail-image\" />\n </div>\n ") : '<div class="file-attachment-icon">📄</div>', "\n <div class=\"file-attachment-info\">\n <div class=\"file-attachment-name\" title=\"").concat(displayName, "\">\n ").concat(displayName, "\n </div>\n <div class=\"file-attachment-size\">").concat(size, "</div>\n </div>\n <button\n class=\"file-attachment-remove\"\n data-index=\"").concat(index, "\"\n title=\"Remove file\"\n >\n \u2715\n </button>\n </div>\n ");
304
+ }).join("");
305
+
306
+ // Bind remove buttons
307
+ container.querySelectorAll(".file-attachment-remove").forEach(btn => {
308
+ btn.addEventListener("click", e => {
309
+ e.stopPropagation();
310
+ const index = parseInt(btn.getAttribute("data-index"));
311
+ this.removeBlock(index);
312
+ });
313
+ });
314
+
315
+ // Bind image click for expansion (optional - can add modal later)
316
+ container.querySelectorAll(".file-thumbnail-image").forEach(img => {
317
+ img.addEventListener("click", e => {
318
+ e.stopPropagation();
319
+ // Could add image expansion modal here
320
+ });
321
+ });
322
+ }
323
+ _formatTime(date) {
324
+ let hours = date.getHours();
325
+ const minutes = date.getMinutes();
326
+ const ampm = hours >= 12 ? 'PM' : 'AM';
327
+ hours = hours % 12;
328
+ hours = hours ? hours : 12;
329
+ const strTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ' ' + ampm;
330
+ return strTime;
331
+ }
332
+ addMessage(text, isUser) {
333
+ let messageData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
334
+ console.log("Is user", isUser);
335
+ if (!this.container) return;
336
+ const messagesContainer = this.container.querySelector("#chat-messages");
337
+ if (!messagesContainer) return;
338
+ const welcome = messagesContainer.querySelector(".chat-welcome");
339
+ if (welcome) welcome.remove();
340
+
341
+ // Check if message already exists (for syncing)
342
+ const messageId = (messageData === null || messageData === void 0 ? void 0 : messageData.id) || Date.now();
343
+ console.log("Message ID", messageId);
344
+ const existingMessage = messagesContainer.querySelector("[data-message-id=\"".concat(messageId, "\"]"));
345
+ if (existingMessage && messageData) {
346
+ // Update existing message
347
+ const bubble = existingMessage.querySelector(".message-bubble");
348
+ if (bubble) {
349
+ // Parse markdown for assistant messages, escape for user messages
350
+ const content = messageData.content || text;
351
+ bubble.innerHTML = !isUser ? this._parseMarkdown(content) : this._escapeHtml(content);
352
+ }
353
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
354
+ return;
355
+ }
356
+ const messageEl = document.createElement("div");
357
+ messageEl.className = "chat-message ".concat(isUser ? "user" : "bot");
358
+ messageEl.setAttribute("data-message-id", messageId);
359
+
360
+ // Handle different message types
361
+ let content = text;
362
+ if (messageData) {
363
+ if (messageData.isStreaming) {
364
+ content = messageData.content || "Thinking...";
365
+ } else if (messageData.isError) {
366
+ content = messageData.content || "Error occurred";
367
+ messageEl.classList.add("error");
368
+ } else {
369
+ content = messageData.content || text;
370
+ }
371
+ }
372
+
373
+ // Build attachments HTML if present
374
+ let attachmentsHTML = "";
375
+ if (messageData && messageData.attachments && messageData.attachments.length > 0) {
376
+ attachmentsHTML = "\n <div class=\"message-attachments\">\n ".concat(messageData.attachments.map((attachment, index) => {
377
+ var _attachment$metadata, _attachment$metadata2, _attachment$metadata3;
378
+ const displayName = ((_attachment$metadata = attachment.metadata) === null || _attachment$metadata === void 0 ? void 0 : _attachment$metadata.name) || ((_attachment$metadata2 = attachment.metadata) === null || _attachment$metadata2 === void 0 ? void 0 : _attachment$metadata2.filename) || "Unknown file";
379
+ const isImage = attachment.type === "image";
380
+ const imageSrc = isImage && attachment.data ? "data:".concat(attachment.mime_type, ";base64,").concat(attachment.data) : null;
381
+ return "\n <div class=\"message-attachment ".concat(isImage ? "image" : "pdf", "\" data-attachment-index=\"").concat(index, "\">\n <span class=\"message-attachment-icon\">\n ").concat(isImage ? "🖼️" : "📄", "\n </span>\n <div class=\"message-attachment-info\">\n <div \n class=\"message-attachment-name ").concat(isImage ? "clickable" : "", "\"\n ").concat(isImage && imageSrc ? "data-image-src=\"".concat(imageSrc, "\" data-image-alt=\"").concat(displayName, "\"") : "", "\n style=\"cursor: ").concat(isImage ? "pointer" : "default", ";\"\n >\n ").concat(this._escapeHtml(displayName), "\n </div>\n <div class=\"message-attachment-size\">\n ").concat(this.formatFileSize(((_attachment$metadata3 = attachment.metadata) === null || _attachment$metadata3 === void 0 ? void 0 : _attachment$metadata3.size) || 0), " \u2022 ").concat(this.getFileTypeDisplay(attachment.mime_type), "\n </div>\n </div>\n </div>\n ");
382
+ }).join(""), "\n </div>\n ");
383
+ }
384
+ const timestamp = messageData !== null && messageData !== void 0 && messageData.timestamp ? new Date(messageData.timestamp) : new Date();
385
+ const formattedTime = this._formatTime(timestamp);
386
+
387
+ // Parse markdown for assistant messages, escape for user messages
388
+ const renderedContent = !isUser ? this._parseMarkdown(content) : this._escapeHtml(content);
389
+ messageEl.innerHTML = "\n <div class=\"message-content\">\n ".concat(attachmentsHTML, "\n <div class=\"message-bubble\">\n ").concat(renderedContent, "\n </div>\n <div class=\"message-time\">").concat(formattedTime, "</div>\n </div>\n ");
390
+
391
+ // Bind image click handlers for expansion
392
+ if (messageData && messageData.attachments) {
393
+ messageEl.querySelectorAll(".message-attachment-name.clickable").forEach(el => {
394
+ el.addEventListener("click", e => {
395
+ e.stopPropagation();
396
+ const imageSrc = el.getAttribute("data-image-src");
397
+ const imageAlt = el.getAttribute("data-image-alt");
398
+ if (imageSrc) {
399
+ this.showExpandedImage(imageSrc, imageAlt);
400
+ }
401
+ });
402
+ });
403
+ }
404
+ messagesContainer.appendChild(messageEl);
405
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
406
+ }
407
+
408
+ // Sync messages from shared array
409
+ _syncMessages(messages) {
410
+ if (!this.container) return;
411
+ const messagesContainer = this.container.querySelector("#chat-messages");
412
+ if (!messagesContainer) return;
413
+
414
+ // Remove welcome message if there are any messages
415
+ if (messages.length > 0) {
416
+ const welcome = messagesContainer.querySelector(".chat-welcome");
417
+ if (welcome) welcome.remove();
418
+ }
419
+
420
+ // Get existing message elements
421
+ const existingMessages = messagesContainer.querySelectorAll("[data-message-id]");
422
+ const existingIds = new Set(Array.from(existingMessages).map(el => el.getAttribute("data-message-id")));
423
+
424
+ // Add or update messages
425
+ messages.forEach(msg => {
426
+ const msgId = String(msg.id);
427
+ if (existingIds.has(msgId)) {
428
+ // Update existing message
429
+ const existingEl = messagesContainer.querySelector("[data-message-id=\"".concat(msgId, "\"]"));
430
+ if (existingEl) {
431
+ const bubble = existingEl.querySelector(".message-bubble");
432
+ if (bubble) {
433
+ // Parse markdown for assistant messages, escape for user messages
434
+ const content = msg.content || "";
435
+ const isUserMessage = msg.sender === "user";
436
+ bubble.innerHTML = !isUserMessage ? this._parseMarkdown(content) : this._escapeHtml(content);
437
+ }
438
+
439
+ // Update attachments if they exist
440
+ const messageContent = existingEl.querySelector(".message-content");
441
+ if (messageContent && msg.attachments && msg.attachments.length > 0) {
442
+ let attachmentsHTML = "\n <div class=\"message-attachments\">\n ".concat(msg.attachments.map((attachment, index) => {
443
+ var _attachment$metadata4, _attachment$metadata5, _attachment$metadata6;
444
+ const displayName = ((_attachment$metadata4 = attachment.metadata) === null || _attachment$metadata4 === void 0 ? void 0 : _attachment$metadata4.name) || ((_attachment$metadata5 = attachment.metadata) === null || _attachment$metadata5 === void 0 ? void 0 : _attachment$metadata5.filename) || "Unknown file";
445
+ const isImage = attachment.type === "image";
446
+ const imageSrc = isImage && attachment.data ? "data:".concat(attachment.mime_type, ";base64,").concat(attachment.data) : null;
447
+ return "\n <div class=\"message-attachment ".concat(isImage ? "image" : "pdf", "\" data-attachment-index=\"").concat(index, "\">\n <span class=\"message-attachment-icon\">\n ").concat(isImage ? "🖼️" : "📄", "\n </span>\n <div class=\"message-attachment-info\">\n <div \n class=\"message-attachment-name ").concat(isImage ? "clickable" : "", "\"\n ").concat(isImage && imageSrc ? "data-image-src=\"".concat(imageSrc, "\" data-image-alt=\"").concat(displayName, "\"") : "", "\n style=\"cursor: ").concat(isImage ? "pointer" : "default", ";\"\n >\n ").concat(this._escapeHtml(displayName), "\n </div>\n <div class=\"message-attachment-size\">\n ").concat(this.formatFileSize(((_attachment$metadata6 = attachment.metadata) === null || _attachment$metadata6 === void 0 ? void 0 : _attachment$metadata6.size) || 0), " \u2022 ").concat(this.getFileTypeDisplay(attachment.mime_type), "\n </div>\n </div>\n </div>\n ");
448
+ }).join(""), "\n </div>\n ");
449
+
450
+ // Insert or update attachments
451
+ const existingAttachments = messageContent.querySelector(".message-attachments");
452
+ if (existingAttachments) {
453
+ existingAttachments.outerHTML = attachmentsHTML;
454
+ } else {
455
+ messageContent.insertAdjacentHTML("afterbegin", attachmentsHTML);
456
+ }
457
+
458
+ // Re-bind image click handlers
459
+ messageContent.querySelectorAll(".message-attachment-name.clickable").forEach(el => {
460
+ // Remove existing listeners by cloning
461
+ const newEl = el.cloneNode(true);
462
+ el.parentNode.replaceChild(newEl, el);
463
+ newEl.addEventListener("click", e => {
464
+ e.stopPropagation();
465
+ const imageSrc = newEl.getAttribute("data-image-src");
466
+ const imageAlt = newEl.getAttribute("data-image-alt");
467
+ if (imageSrc) {
468
+ this.showExpandedImage(imageSrc, imageAlt);
469
+ }
470
+ });
471
+ });
472
+ }
473
+
474
+ // Update classes based on message state
475
+ if (msg.isStreaming) {
476
+ existingEl.classList.add("streaming");
477
+ } else {
478
+ existingEl.classList.remove("streaming");
479
+ }
480
+ if (msg.isError) {
481
+ existingEl.classList.add("error");
482
+ }
483
+ }
484
+ } else {
485
+ // Add new message
486
+ this.addMessage(msg.content || "", msg.sender === "user", msg);
487
+ }
488
+ });
489
+
490
+ // Remove messages that are no longer in the array
491
+ existingMessages.forEach(el => {
492
+ const msgId = el.getAttribute("data-message-id");
493
+ const exists = messages.some(msg => String(msg.id) === msgId);
494
+ if (!exists) {
495
+ el.remove();
496
+ }
497
+ });
498
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
499
+ }
500
+ showTypingIndicator() {
501
+ if (!this.container) return;
502
+ const messagesContainer = this.container.querySelector("#chat-messages");
503
+ if (!messagesContainer) return;
504
+ const indicator = document.createElement("div");
505
+ indicator.className = "chat-message bot";
506
+ indicator.id = "typing-indicator";
507
+ indicator.innerHTML = "\n <div class=\"typing-indicator\">\n <div class=\"typing-dot\"></div>\n <div class=\"typing-dot\"></div>\n <div class=\"typing-dot\"></div>\n </div>\n ";
508
+ messagesContainer.appendChild(indicator);
509
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
510
+ }
511
+ hideTypingIndicator() {
512
+ if (!this.container) return;
513
+ const indicator = this.container.querySelector("#typing-indicator");
514
+ if (indicator) indicator.remove();
515
+ }
516
+ handleUserMessage(text) {
517
+ // Call the callback if provided, otherwise use default echo
518
+ if (this.onMessage) {
519
+ this.onMessage(text, response => {
520
+ this.addMessage(response, false);
521
+ });
522
+ } else {
523
+ // Default echo response
524
+ this.addMessage("You said: \"".concat(text, "\""), false);
525
+ }
526
+ }
527
+ _escapeHtml(text) {
528
+ const div = document.createElement("div");
529
+ div.textContent = text;
530
+ return div.innerHTML;
531
+ }
532
+
533
+ // Parse markdown to HTML
534
+ _parseMarkdown(text) {
535
+ if (!text || typeof text !== 'string') return '';
536
+ let html = text;
537
+
538
+ // Escape HTML first to prevent XSS
539
+ html = html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
540
+
541
+ // Split into lines for processing
542
+ const lines = html.split('\n');
543
+ const processedLines = [];
544
+ let inList = false;
545
+ for (let i = 0; i < lines.length; i++) {
546
+ let line = lines[i];
547
+
548
+ // Check for headers first (#, ##, ###, etc.)
549
+ const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
550
+ if (headerMatch) {
551
+ if (inList) {
552
+ processedLines.push('</ul>');
553
+ inList = false;
554
+ }
555
+ const level = headerMatch[1].length;
556
+ const headerText = headerMatch[2];
557
+ // Process markdown inside header
558
+ let processedHeader = headerText;
559
+ processedHeader = processedHeader.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
560
+ processedHeader = processedHeader.replace(/__([^_]+)__/g, '<strong>$1</strong>');
561
+ processedHeader = processedHeader.replace(/(^|[^*])\*([^*]+)\*([^*]|$)/g, '$1<em>$2</em>$3');
562
+ processedHeader = processedHeader.replace(/(^|[^_])_([^_]+)_([^_]|$)/g, '$1<em>$2</em>$3');
563
+ processedLines.push("<h".concat(level, ">").concat(processedHeader, "</h").concat(level, ">"));
564
+ continue;
565
+ }
566
+
567
+ // Check if this is a list item (before processing bold/italic)
568
+ const listMatch = line.match(/^[\s]*[-*]\s+(.+)$/);
569
+ if (listMatch) {
570
+ // Process markdown inside list item
571
+ let listContent = listMatch[1];
572
+
573
+ // Bold: **text** (must be processed before italic)
574
+ listContent = listContent.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
575
+ listContent = listContent.replace(/__([^_]+)__/g, '<strong>$1</strong>');
576
+
577
+ // Italic: *text* (single asterisk, avoid matching **text**)
578
+ listContent = listContent.replace(/(^|[^*])\*([^*]+)\*([^*]|$)/g, '$1<em>$2</em>$3');
579
+ listContent = listContent.replace(/(^|[^_])_([^_]+)_([^_]|$)/g, '$1<em>$2</em>$3');
580
+ if (!inList) {
581
+ processedLines.push('<ul>');
582
+ inList = true;
583
+ }
584
+ processedLines.push("<li>".concat(listContent, "</li>"));
585
+ } else {
586
+ if (inList) {
587
+ processedLines.push('</ul>');
588
+ inList = false;
589
+ }
590
+
591
+ // Skip empty lines (they'll become <br> later)
592
+ if (line.trim() === '') {
593
+ processedLines.push('');
594
+ continue;
595
+ }
596
+
597
+ // Process markdown in non-list lines
598
+ // Bold: **text** (must be processed before italic)
599
+ line = line.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
600
+ line = line.replace(/__([^_]+)__/g, '<strong>$1</strong>');
601
+
602
+ // Italic: *text* (single asterisk, avoid matching **text**)
603
+ line = line.replace(/(^|[^*])\*([^*]+)\*([^*]|$)/g, '$1<em>$2</em>$3');
604
+ line = line.replace(/(^|[^_])_([^_]+)_([^_]|$)/g, '$1<em>$2</em>$3');
605
+
606
+ // Inline code: `code`
607
+ line = line.replace(/`([^`]+)`/g, '<code>$1</code>');
608
+
609
+ // Links: [text](url)
610
+ line = line.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
611
+ processedLines.push(line);
612
+ }
613
+ }
614
+ if (inList) {
615
+ processedLines.push('</ul>');
616
+ }
617
+
618
+ // Join lines with <br> and return
619
+ html = processedLines.join('<br>');
620
+ return html;
621
+ }
622
+
623
+ // Show expanded image modal
624
+ showExpandedImage(src, alt) {
625
+ // Remove existing modal if any
626
+ const existingModal = document.querySelector(".expanded-image-modal");
627
+ if (existingModal) {
628
+ existingModal.remove();
629
+ }
630
+ const modal = document.createElement("div");
631
+ modal.className = "expanded-image-modal";
632
+ modal.innerHTML = "\n <div class=\"expanded-image-container\">\n <button class=\"expanded-image-close\" title=\"Close\">\u2715</button>\n <img src=\"".concat(src, "\" alt=\"").concat(alt || "Image", "\" class=\"expanded-image\" />\n <div class=\"expanded-image-caption\">").concat(this._escapeHtml(alt || "Image preview"), "</div>\n </div>\n ");
633
+
634
+ // Close handlers
635
+ const closeModal = e => {
636
+ e === null || e === void 0 || e.stopPropagation();
637
+ modal.remove();
638
+ document.removeEventListener("mousedown", handleClickOutside);
639
+ };
640
+ const handleClickOutside = e => {
641
+ if (!e.target.closest(".expanded-image-container")) {
642
+ closeModal(e);
643
+ }
644
+ };
645
+ modal.querySelector(".expanded-image-close").addEventListener("click", closeModal);
646
+ modal.addEventListener("click", e => {
647
+ if (e.target === modal) {
648
+ closeModal(e);
649
+ }
650
+ });
651
+ document.addEventListener("mousedown", handleClickOutside);
652
+ document.body.appendChild(modal);
653
+ }
654
+ _applyStyles() {
655
+ // Check if styles already applied
656
+ if (document.getElementById('text-chat-screen-styles')) return;
657
+ const style = document.createElement("style");
658
+ style.id = 'text-chat-screen-styles';
659
+ style.textContent = "\n .text-chat-screen {\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n \n }\n\n .text-chat-screen .chat-header {\n background: transparent;\n color: ".concat(this.primaryColor, ";\n padding: 20px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .text-chat-screen .chat-header-content {\n display: flex;\n align-items: center;\n gap: 12px;\n flex: 1;\n }\n\n .text-chat-screen .chat-back {\n background: ").concat(this.primaryColor, ";\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n margin-right: 8px;\n }\n\n \n\n .text-chat-screen .chat-avatar {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: rgba(255, 255, 255, 0.2);\n backdrop-filter: blur(10px);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .text-chat-screen .chat-header-text {\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n\n .text-chat-screen .chat-title {\n font-weight: 600;\n font-size: 20px;\n }\n\n .text-chat-screen .chat-status {\n font-size: 12px;\n opacity: 0.9;\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n .text-chat-screen .chat-close {\n background: ").concat(this.primaryColor, ";\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n }\n\n \n\n .text-chat-screen .chat-messages {\n flex: 1;\n padding: 20px;\n overflow-y: auto;\n background: linear-gradient(180deg, white 10%, #E1EFCC );\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .text-chat-screen .chat-messages::-webkit-scrollbar {\n width: 6px;\n }\n\n .text-chat-screen .chat-messages::-webkit-scrollbar-track {\n background: transparent;\n }\n\n .text-chat-screen .chat-messages::-webkit-scrollbar-thumb {\n background: #cbd5e1;\n border-radius: 3px;\n }\n\n .text-chat-screen .chat-welcome {\n text-align: center;\n padding: 100px 20px;\n color: #64748b;\n \n }\n\n .text-chat-screen .chat-welcome .welcome-icon {\n font-size: 48px;\n margin-bottom: 12px;\n }\n\n .text-chat-screen .welcome-text {\n font-size: 15px;\n font-weight: 500;\n color: #475569;\n }\n\n .text-chat-screen .chat-message {\n display: flex;\n gap: 8px;\n animation: messageSlide 0.3s ease-out;\n }\n\n @keyframes messageSlide {\n from {\n opacity: 0;\n transform: translateY(10px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n\n .text-chat-screen .chat-message.user {\n flex-direction: row-reverse;\n }\n\n .text-chat-screen .message-content {\n max-width: 75%;\n }\n\n .text-chat-screen .message-bubble {\n padding: 12px 16px;\n border-radius: 16px;\n font-size: 14px;\n line-height: 1.5;\n word-wrap: break-word;\n }\n\n .text-chat-screen .chat-message.user .message-bubble {\n background: #e9f5d7;\n color: ").concat(this.primaryColor, ";\n border-bottom-right-radius: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n .text-chat-screen .chat-message.bot .message-bubble {\n background: white;\n color: #1e293b;\n border-bottom-left-radius: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n /* ============================================\n Text Chat Message Bubble Styles\n ============================================ */\n\n/* Typography - Bold */\n.text-chat-screen .message-bubble strong {\n font-weight: 600;\n color: inherit;\n}\n\n/* Typography - Italic */\n.text-chat-screen .message-bubble em {\n font-style: italic;\n}\n\n/* Lists */\n.text-chat-screen .message-bubble ul {\n margin: 0px 0;\n padding-left: 20px;\n list-style-type: disc;\n margin-bottom:0px;\n margin-top:5px;\n}\n\n.text-chat-screen .message-bubble li {\n margin: 0;\n line-height: 1.1;\n padding-left: 3px;\n}\n\n/* Headings - Shared Styles */\n.text-chat-screen .message-bubble h1,\n.text-chat-screen .message-bubble h2,\n.text-chat-screen .message-bubble h3,\n.text-chat-screen .message-bubble h4,\n.text-chat-screen .message-bubble h5,\n.text-chat-screen .message-bubble h6 {\n margin: 0px 0 0px 0;\n font-weight: 600;\n color: inherit;\n line-height: 1.3;\n}\n\n/* Heading Sizes */\n.text-chat-screen .message-bubble h1 { font-size: 1.5em; }\n.text-chat-screen .message-bubble h2 { font-size: 1.3em; }\n.text-chat-screen .message-bubble h3 { font-size: 1.15em; }\n.text-chat-screen .message-bubble h4 { font-size: 1.05em; }\n.text-chat-screen .message-bubble h5 { font-size: 1em; }\n.text-chat-screen .message-bubble h6 { font-size: 0.95em; }\n\n/* Inline Code */\n.text-chat-screen .message-bubble code {\n background: rgba(0, 0, 0, 0.05);\n padding: 2px 6px;\n border-radius: 4px;\n font-family: 'Courier New', Courier, monospace;\n font-size: 0.9em;\n}\n\n/* Links */\n.text-chat-screen .message-bubble a {\n color: ").concat(this.primaryColor, ";\n text-decoration: underline;\n}\n\n.text-chat-screen .message-bubble a:hover {\n opacity: 0.8;\n}\n.text-chat-screen .message-bubble br {\n line-height: 0.1; /* Adjust between 0 and 1 */\n}\n\n .text-chat-screen .message-time {\n font-size: 10px;\n color: #94a3b8;\n margin-top: 4px;\n text-align: right;\n }\n\n .text-chat-screen .typing-indicator {\n display: flex;\n gap: 4px;\n padding: 12px 16px;\n background: white;\n border-radius: 16px;\n border-bottom-left-radius: 4px;\n max-width: 60px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n .text-chat-screen .typing-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: #94a3b8;\n animation: typing 1.4s infinite;\n }\n\n .text-chat-screen .typing-dot:nth-child(2) {\n animation-delay: 0.2s;\n }\n\n .text-chat-screen .typing-dot:nth-child(3) {\n animation-delay: 0.4s;\n }\n\n @keyframes typing {\n 0%, 60%, 100% {\n transform: translateY(0);\n opacity: 0.7;\n }\n 30% {\n transform: translateY(-10px);\n opacity: 1;\n }\n }\n\n .text-chat-screen .file-attachments-container {\n padding: 8px 12px;\n background: white;\n border-top: 1px solid #e2e8f0;\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n max-height: 120px;\n overflow-y: auto;\n }\n\n .text-chat-screen .file-attachments-container::-webkit-scrollbar {\n width: 4px;\n height: 4px;\n }\n\n .text-chat-screen .file-attachments-container::-webkit-scrollbar-track {\n background: transparent;\n }\n\n .text-chat-screen .file-attachments-container::-webkit-scrollbar-thumb {\n background: #cbd5e1;\n border-radius: 2px;\n }\n\n .text-chat-screen .file-attachment {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 10px;\n background: #f1f5f9;\n border: 1px solid #e2e8f0;\n border-radius: 8px;\n font-size: 12px;\n max-width: 200px;\n position: relative;\n }\n\n .text-chat-screen .file-attachment.has-thumbnail {\n padding: 4px;\n }\n\n .text-chat-screen .file-thumbnail {\n width: 40px;\n height: 40px;\n border-radius: 6px;\n overflow: hidden;\n flex-shrink: 0;\n background: #e2e8f0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .text-chat-screen .file-thumbnail-image {\n width: 100%;\n height: 100%;\n object-fit: cover;\n cursor: pointer;\n }\n\n .text-chat-screen .file-attachment-icon {\n font-size: 24px;\n flex-shrink: 0;\n }\n\n .text-chat-screen .file-attachment-info {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n\n .text-chat-screen .file-attachment-name {\n font-weight: 500;\n color: #1e293b;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n max-width: 120px;\n }\n\n .text-chat-screen .file-attachment-size {\n font-size: 11px;\n color: #64748b;\n }\n\n .text-chat-screen .file-attachment-remove {\n background: transparent;\n border: none;\n color: #64748b;\n cursor: pointer;\n padding: 4px;\n border-radius: 4px;\n font-size: 16px;\n line-height: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n flex-shrink: 0;\n }\n\n .text-chat-screen .file-attachment-remove:hover {\n background: #fee2e2;\n color: #dc2626;\n }\n\n .text-chat-screen .chat-input-wrapper {\n display: flex;\n padding: 10px;\n gap: 8px;\n background: white;\n border-top: 1px solid #e2e8f0;\n align-items: center;\n }\n\n .text-chat-screen .file-upload-controls {\n display: flex;\n align-items: center;\n }\n\n .text-chat-screen .file-upload-button {\n background: transparent;\n border: none;\n color: ").concat(this.primaryColor, ";\n cursor: pointer;\n padding: 8px;\n border-radius: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n }\n\n .text-chat-screen .file-upload-button:hover {\n background: rgba(26, 92, 75, 0.1);\n }\n\n .text-chat-screen .file-upload-button:active {\n transform: scale(0.95);\n }\n\n .text-chat-screen #chat-input {\n flex: 1;\n border: 2px solid #e2e8f0;\n border-radius: 12px;\n padding: 12px 16px;\n font-size: 14px;\n outline: none;\n transition: all 0.2s;\n font-family: inherit;\n }\n\n .text-chat-screen #chat-input:focus {\n border-color: ").concat(this.primaryColor, ";\n box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);\n }\n\n .text-chat-screen #chat-send {\n background: ").concat(this.primaryColor, ";\n color: white;\n border: none;\n border-radius: 12px;\n padding: 12px 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n }\n\n .text-chat-screen #chat-send:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n .text-chat-screen #chat-send:not(:disabled):hover {\n transform: scale(1.05);\n box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);\n }\n\n .text-chat-screen #chat-send:not(:disabled):active {\n transform: scale(0.95);\n }\n\n /* Message Attachments Styles */\n .text-chat-screen .message-attachments {\n display: flex;\n flex-direction: column;\n gap: 8px;\n margin-bottom: 8px;\n }\n\n .text-chat-screen .message-attachment {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 12px;\n background: #f1f5f9;\n border: 1px solid #e2e8f0;\n border-radius: 8px;\n font-size: 12px;\n max-width: 100%;\n }\n\n .text-chat-screen .message-attachment.image {\n background: #f8fafc;\n }\n\n .text-chat-screen .message-attachment.pdf {\n background: #fef2f2;\n }\n\n .text-chat-screen .message-attachment-icon {\n font-size: 20px;\n flex-shrink: 0;\n }\n\n .text-chat-screen .message-attachment-info {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n\n .text-chat-screen .message-attachment-name {\n font-weight: 500;\n color: #1e293b;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .text-chat-screen .message-attachment-name.clickable:hover {\n color: ").concat(this.primaryColor, ";\n text-decoration: underline;\n }\n\n .text-chat-screen .message-attachment-size {\n font-size: 11px;\n color: #64748b;\n }\n\n /* Expanded Image Modal Styles */\n .expanded-image-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n animation: fadeIn 0.2s ease;\n }\n\n @keyframes fadeIn {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n\n .expanded-image-container {\n position: relative;\n max-width: 90%;\n max-height: 90vh;\n background: #fff;\n border-radius: 8px;\n overflow: hidden;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);\n animation: scaleIn 0.2s ease;\n display: flex;\n flex-direction: column;\n }\n\n @keyframes scaleIn {\n from {\n transform: scale(0.9);\n opacity: 0;\n }\n to {\n transform: scale(1);\n opacity: 1;\n }\n }\n\n .expanded-image-close {\n position: absolute;\n top: 12px;\n right: 12px;\n background: rgba(0, 0, 0, 0.6);\n border: none;\n color: white;\n width: 32px;\n height: 32px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 18px;\n z-index: 1;\n transition: all 0.2s;\n }\n\n .expanded-image-close:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n }\n\n .expanded-image {\n max-width: 100%;\n max-height: calc(90vh - 60px);\n object-fit: contain;\n display: block;\n }\n\n .expanded-image-caption {\n padding: 12px 16px;\n background: #fff;\n color: #1e293b;\n font-size: 14px;\n text-align: center;\n border-top: 1px solid #e2e8f0;\n }\n ");
660
+ document.head.appendChild(style);
661
+ }
32
662
  }
33
663
 
34
- var chatWidget = {exports: {}};
35
-
36
- (function (module) {
37
- // chat-widget.js - Modern vanilla JS chat bot widget
38
- var ChatWidget = /*#__PURE__*/function () {
39
- function ChatWidget() {
40
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
41
- _classCallCheck(this, ChatWidget);
42
- this.title = options.title || "Chat Assistant";
43
- this.placeholder = options.placeholder || "Type your message...";
44
- this.primaryColor = options.primaryColor || "#6366f1";
45
- this.container = null;
46
- this.messages = [];
47
- this.isMinimized = false;
48
- this._init();
49
- }
50
- return _createClass(ChatWidget, [{
51
- key: "_init",
52
- value: function _init() {
53
- // Create container
54
- this.container = document.createElement("div");
55
- this.container.id = "chat-widget-container";
56
- this.container.innerHTML = "\n <div class=\"chat-widget-minimized\" id=\"chat-toggle\">\n <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path>\n </svg>\n </div>\n <div class=\"chat-widget-expanded\" id=\"chat-expanded\">\n <div class=\"chat-header\">\n <div class=\"chat-header-content\">\n <div class=\"chat-avatar\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <path d=\"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z\"></path>\n <path d=\"M19 10v2a7 7 0 0 1-14 0v-2\"></path>\n </svg>\n </div>\n <div class=\"chat-header-text\">\n <div class=\"chat-title\">".concat(this.title, "</div>\n <div class=\"chat-status\">\u25CF Online</div>\n </div>\n </div>\n <button class=\"chat-close\" id=\"chat-close\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </button>\n </div>\n <div class=\"chat-messages\" id=\"chat-messages\">\n <div class=\"chat-welcome\">\n <div class=\"welcome-icon\">\uD83D\uDC4B</div>\n <div class=\"welcome-text\">Hello! How can I help you today?</div>\n </div>\n </div>\n <div class=\"chat-input-wrapper\">\n <input type=\"text\" id=\"chat-input\" placeholder=\"").concat(this.placeholder, "\" autocomplete=\"off\" />\n <button id=\"chat-send\" disabled>\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"13\"></line>\n <polygon points=\"22 2 15 22 11 13 2 9 22 2\"></polygon>\n </svg>\n </button>\n </div>\n </div>\n ");
57
- document.body.appendChild(this.container);
58
- this._applyStyles();
59
- this._bindEvents();
60
- }
61
- }, {
62
- key: "_applyStyles",
63
- value: function _applyStyles() {
64
- var style = document.createElement("style");
65
- style.textContent = "\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');\n \n #chat-widget-container {\n position: fixed;\n bottom: 24px;\n right: 24px;\n z-index: 10000;\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n }\n\n .chat-widget-minimized {\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: linear-gradient(135deg, ".concat(this.primaryColor, " 0%, #8b5cf6 100%);\n color: white;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n box-shadow: 0 8px 24px rgba(99, 102, 241, 0.4);\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n animation: pulse 2s infinite;\n }\n\n .chat-widget-minimized:hover {\n transform: scale(1.1);\n box-shadow: 0 12px 32px rgba(99, 102, 241, 0.5);\n }\n\n @keyframes pulse {\n 0%, 100% { box-shadow: 0 8px 24px rgba(99, 102, 241, 0.4); }\n 50% { box-shadow: 0 8px 32px rgba(99, 102, 241, 0.6); }\n }\n\n .chat-widget-expanded {\n width: 380px;\n height: 600px;\n background: white;\n border-radius: 16px;\n box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);\n display: none;\n flex-direction: column;\n overflow: hidden;\n animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n }\n\n @keyframes slideUp {\n from {\n opacity: 0;\n transform: translateY(20px) scale(0.95);\n }\n to {\n opacity: 1;\n transform: translateY(0) scale(1);\n }\n }\n\n .chat-widget-expanded.visible {\n display: flex;\n }\n\n .chat-header {\n background: linear-gradient(135deg, ").concat(this.primaryColor, " 0%, #8b5cf6 100%);\n color: white;\n padding: 20px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .chat-header-content {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .chat-avatar {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: rgba(255, 255, 255, 0.2);\n backdrop-filter: blur(10px);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .chat-header-text {\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n\n .chat-title {\n font-weight: 600;\n font-size: 16px;\n }\n\n .chat-status {\n font-size: 12px;\n opacity: 0.9;\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n .chat-close {\n background: transparent;\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n border-radius: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n }\n\n .chat-close:hover {\n background: rgba(255, 255, 255, 0.15);\n }\n\n .chat-messages {\n flex: 1;\n padding: 20px;\n overflow-y: auto;\n background: #f9fafb;\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .chat-messages::-webkit-scrollbar {\n width: 6px;\n }\n\n .chat-messages::-webkit-scrollbar-track {\n background: transparent;\n }\n\n .chat-messages::-webkit-scrollbar-thumb {\n background: #cbd5e1;\n border-radius: 3px;\n }\n\n .chat-welcome {\n text-align: center;\n padding: 40px 20px;\n color: #64748b;\n }\n\n .welcome-icon {\n font-size: 48px;\n margin-bottom: 12px;\n }\n\n .welcome-text {\n font-size: 15px;\n font-weight: 500;\n color: #475569;\n }\n\n .chat-message {\n display: flex;\n gap: 8px;\n animation: messageSlide 0.3s ease-out;\n }\n\n @keyframes messageSlide {\n from {\n opacity: 0;\n transform: translateY(10px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n\n .chat-message.user {\n flex-direction: row-reverse;\n }\n\n .message-bubble {\n max-width: 75%;\n padding: 12px 16px;\n border-radius: 16px;\n font-size: 14px;\n line-height: 1.5;\n word-wrap: break-word;\n }\n\n .chat-message.user .message-bubble {\n background: linear-gradient(135deg, ").concat(this.primaryColor, " 0%, #8b5cf6 100%);\n color: white;\n border-bottom-right-radius: 4px;\n }\n\n .chat-message.bot .message-bubble {\n background: white;\n color: #1e293b;\n border-bottom-left-radius: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n .typing-indicator {\n display: flex;\n gap: 4px;\n padding: 12px 16px;\n background: white;\n border-radius: 16px;\n border-bottom-left-radius: 4px;\n max-width: 60px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n .typing-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: #94a3b8;\n animation: typing 1.4s infinite;\n }\n\n .typing-dot:nth-child(2) {\n animation-delay: 0.2s;\n }\n\n .typing-dot:nth-child(3) {\n animation-delay: 0.4s;\n }\n\n @keyframes typing {\n 0%, 60%, 100% {\n transform: translateY(0);\n opacity: 0.7;\n }\n 30% {\n transform: translateY(-10px);\n opacity: 1;\n }\n }\n\n .chat-input-wrapper {\n display: flex;\n padding: 16px;\n gap: 8px;\n background: white;\n border-top: 1px solid #e2e8f0;\n }\n\n #chat-input {\n flex: 1;\n border: 2px solid #e2e8f0;\n border-radius: 12px;\n padding: 12px 16px;\n font-size: 14px;\n outline: none;\n transition: all 0.2s;\n font-family: inherit;\n }\n\n #chat-input:focus {\n border-color: ").concat(this.primaryColor, ";\n box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);\n }\n\n #chat-send {\n background: linear-gradient(135deg, ").concat(this.primaryColor, " 0%, #8b5cf6 100%);\n color: white;\n border: none;\n border-radius: 12px;\n padding: 12px 16px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n }\n\n #chat-send:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n\n #chat-send:not(:disabled):hover {\n transform: scale(1.05);\n box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);\n }\n\n #chat-send:not(:disabled):active {\n transform: scale(0.95);\n }\n ");
66
- document.head.appendChild(style);
67
- }
68
- }, {
69
- key: "_bindEvents",
70
- value: function _bindEvents() {
71
- var _this = this;
72
- var toggle = this.container.querySelector("#chat-toggle");
73
- var closeBtn = this.container.querySelector("#chat-close");
74
- var expanded = this.container.querySelector("#chat-expanded");
75
- var input = this.container.querySelector("#chat-input");
76
- var sendBtn = this.container.querySelector("#chat-send");
77
- toggle.addEventListener("click", function () {
78
- toggle.style.display = "none";
79
- expanded.classList.add("visible");
80
- input.focus();
664
+ class BhashiniFrontend {
665
+ constructor() {
666
+ this.apiKey = '23588533c1-d990-4a7d-b052-d970c886147e';
667
+ this.userId = '749bd0b0c65e4d17a372be0ad92af981';
668
+ this.callbackUrl = 'https://meity-auth.ulcacontrib.org/ulca/apis/v0/model/getModelsPipeline';
669
+ this.inferenceUrl = null;
670
+ this.inferenceHeaders = {};
671
+ this.asrServiceId = {
672
+ 'hi': 'ai4bharat/conformer-hi-gpu--t4',
673
+ 'en': 'ai4bharat/whisper-medium-en--gpu--t4'
674
+ };
675
+ this.ttsServiceId = {
676
+ 'hi': 'ai4bharat/indic-tts-coqui-indo_aryan-gpu--t4',
677
+ 'en': 'ai4bharat/indic-tts-coqui-misc-gpu--t4'
678
+ };
679
+ this.translationServiceId = 'ai4bharat/indictrans-v2-all-gpu--t4';
680
+ }
681
+ async initialize() {
682
+ try {
683
+ const response = await fetch(this.callbackUrl, {
684
+ method: 'POST',
685
+ headers: {
686
+ 'Content-Type': 'application/json',
687
+ 'userID': this.userId,
688
+ 'ulcaApiKey': this.apiKey
689
+ },
690
+ body: JSON.stringify({
691
+ pipelineTasks: [{
692
+ taskType: 'asr'
693
+ }],
694
+ pipelineRequestConfig: {
695
+ pipelineId: '64392f96daac500b55c543cd'
696
+ }
697
+ })
698
+ });
699
+ const data = await response.json();
700
+ if (data.pipelineInferenceAPIEndPoint) {
701
+ this.inferenceUrl = data.pipelineInferenceAPIEndPoint.callbackUrl;
702
+ const keyName = data.pipelineInferenceAPIEndPoint.inferenceApiKey.name;
703
+ const keyValue = data.pipelineInferenceAPIEndPoint.inferenceApiKey.value;
704
+ this.inferenceHeaders = {
705
+ 'Content-Type': 'application/json',
706
+ [keyName]: keyValue
707
+ };
708
+ } else {
709
+ // Fallback to direct endpoint
710
+ this.inferenceUrl = 'https://dhruva-api.bhashini.gov.in/services/inference/pipeline';
711
+ this.inferenceHeaders = {
712
+ 'Content-Type': 'application/json',
713
+ 'userID': this.userId,
714
+ 'ulcaApiKey': this.apiKey
715
+ };
716
+ }
717
+ return true;
718
+ } catch (error) {
719
+ console.error('Failed to initialize Bhashini:', error);
720
+ // Use fallback endpoint
721
+ this.inferenceUrl = 'https://dhruva-api.bhashini.gov.in/services/inference/pipeline';
722
+ this.inferenceHeaders = {
723
+ 'Content-Type': 'application/json',
724
+ 'userID': this.userId,
725
+ 'ulcaApiKey': this.apiKey
726
+ };
727
+ return false;
728
+ }
729
+ }
730
+ async convertToWav(audioBlob) {
731
+ return new Promise((resolve, reject) => {
732
+ const audioContext = new (window.AudioContext || window.webkitAudioContext)();
733
+ const reader = new FileReader();
734
+ reader.onload = async e => {
735
+ try {
736
+ const arrayBuffer = e.target.result;
737
+ const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
738
+
739
+ // Convert to mono 16kHz
740
+ const offlineContext = new OfflineAudioContext(1, audioBuffer.duration * 16000, 16000);
741
+ const source = offlineContext.createBufferSource();
742
+ source.buffer = audioBuffer;
743
+ source.connect(offlineContext.destination);
744
+ source.start();
745
+ const renderedBuffer = await offlineContext.startRendering();
746
+
747
+ // Convert to WAV
748
+ const wav = this.audioBufferToWav(renderedBuffer);
749
+ const wavBlob = new Blob([wav], {
750
+ type: 'audio/wav'
751
+ });
752
+
753
+ // Convert to base64
754
+ const wavReader = new FileReader();
755
+ wavReader.onloadend = () => {
756
+ const base64 = wavReader.result.split(',')[1];
757
+ resolve(base64);
758
+ };
759
+ wavReader.readAsDataURL(wavBlob);
760
+ } catch (error) {
761
+ reject(error);
762
+ }
763
+ };
764
+ reader.onerror = reject;
765
+ reader.readAsArrayBuffer(audioBlob);
766
+ });
767
+ }
768
+ audioBufferToWav(buffer) {
769
+ const length = buffer.length * buffer.numberOfChannels * 2 + 44;
770
+ const arrayBuffer = new ArrayBuffer(length);
771
+ const view = new DataView(arrayBuffer);
772
+ const channels = [];
773
+ let offset = 0;
774
+ let pos = 0;
775
+
776
+ // Write WAV header
777
+ const setUint16 = data => {
778
+ view.setUint16(pos, data, true);
779
+ pos += 2;
780
+ };
781
+ const setUint32 = data => {
782
+ view.setUint32(pos, data, true);
783
+ pos += 4;
784
+ };
785
+
786
+ // "RIFF" chunk descriptor
787
+ setUint32(0x46464952); // "RIFF"
788
+ setUint32(length - 8); // file length - 8
789
+ setUint32(0x45564157); // "WAVE"
790
+
791
+ // "fmt " sub-chunk
792
+ setUint32(0x20746d66); // "fmt "
793
+ setUint32(16); // SubChunk1Size = 16
794
+ setUint16(1); // AudioFormat = 1 (PCM)
795
+ setUint16(buffer.numberOfChannels);
796
+ setUint32(buffer.sampleRate);
797
+ setUint32(buffer.sampleRate * 2 * buffer.numberOfChannels); // byte rate
798
+ setUint16(buffer.numberOfChannels * 2); // block align
799
+ setUint16(16); // bits per sample
800
+
801
+ // "data" sub-chunk
802
+ setUint32(0x61746164); // "data"
803
+ setUint32(length - pos - 4); // SubChunk2Size
804
+
805
+ // Write interleaved data
806
+ for (let i = 0; i < buffer.numberOfChannels; i++) {
807
+ channels.push(buffer.getChannelData(i));
808
+ }
809
+ while (pos < length) {
810
+ for (let i = 0; i < buffer.numberOfChannels; i++) {
811
+ let sample = Math.max(-1, Math.min(1, channels[i][offset]));
812
+ sample = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
813
+ view.setInt16(pos, sample, true);
814
+ pos += 2;
815
+ }
816
+ offset++;
817
+ }
818
+ return arrayBuffer;
819
+ }
820
+ async speechToText(base64Audio) {
821
+ let sourceLanguage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'auto';
822
+ let targetLanguage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hi';
823
+ if (!this.inferenceUrl) {
824
+ await this.initialize();
825
+ }
826
+ const pipelineTasks = [{
827
+ taskType: 'asr',
828
+ config: {
829
+ language: {
830
+ sourceLanguage
831
+ },
832
+ serviceId: this.asrServiceId[sourceLanguage] || this.asrServiceId['hi'],
833
+ audioFormat: 'wav',
834
+ samplingRate: 16000
835
+ }
836
+ }];
837
+
838
+ // Only translate if languages differ
839
+ if (sourceLanguage !== targetLanguage) {
840
+ pipelineTasks.push({
841
+ taskType: 'translation',
842
+ config: {
843
+ sourceLanguage: sourceLanguage === 'auto' ? undefined : sourceLanguage,
844
+ targetLanguage
845
+ }
846
+ });
847
+ }
848
+ const response = await fetch(this.inferenceUrl, {
849
+ method: 'POST',
850
+ headers: this.inferenceHeaders,
851
+ body: JSON.stringify({
852
+ pipelineTasks,
853
+ inputData: {
854
+ audio: [{
855
+ audioContent: base64Audio
856
+ }]
857
+ }
858
+ })
859
+ });
860
+ if (!response.ok) {
861
+ throw new Error("API error: ".concat(response.status, " ").concat(response.statusText));
862
+ }
863
+ const data = await response.json();
864
+
865
+ // If translated, return translation
866
+ if (pipelineTasks.length > 1) {
867
+ return data.pipelineResponse[1].output[0].target;
868
+ }
869
+
870
+ // Otherwise return raw transcription
871
+ return data.pipelineResponse[0].output[0].source;
872
+ }
873
+ async textToSpeech(text) {
874
+ let language = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en';
875
+ let gender = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'female';
876
+ if (!this.inferenceUrl) {
877
+ await this.initialize();
878
+ }
879
+
880
+ // ✅ Clean the text first
881
+ const cleanedText = text.replace(/!/g, ".");
882
+ const response = await fetch(this.inferenceUrl, {
883
+ method: 'POST',
884
+ headers: this.inferenceHeaders,
885
+ body: JSON.stringify({
886
+ pipelineTasks: [{
887
+ taskType: "tts",
888
+ config: {
889
+ language: {
890
+ sourceLanguage: language
891
+ },
892
+ serviceId: this.ttsServiceId[language] || this.ttsServiceId["en"],
893
+ samplingRate: 8000,
894
+ gender: gender
895
+ }
896
+ }],
897
+ inputData: {
898
+ input: [{
899
+ source: cleanedText
900
+ }]
901
+ }
902
+ })
903
+ });
904
+ if (!response.ok) {
905
+ throw new Error("TTS API error: ".concat(response.status, " ").concat(response.statusText));
906
+ }
907
+ const data = await response.json();
908
+ return data.pipelineResponse[0].audio[0].audioContent;
909
+ }
910
+ async translateText(text, sourceLanguage, targetLanguage) {
911
+ if (!this.inferenceUrl) {
912
+ await this.initialize();
913
+ }
914
+ const response = await fetch(this.inferenceUrl, {
915
+ method: 'POST',
916
+ headers: this.inferenceHeaders,
917
+ body: JSON.stringify({
918
+ pipelineTasks: [{
919
+ taskType: 'translation',
920
+ config: {
921
+ language: {
922
+ sourceLanguage: sourceLanguage,
923
+ targetLanguage: targetLanguage
924
+ },
925
+ serviceId: this.translationServiceId
926
+ }
927
+ }],
928
+ inputData: {
929
+ input: [{
930
+ source: text
931
+ }]
932
+ }
933
+ })
934
+ });
935
+ if (!response.ok) {
936
+ throw new Error("Translation API error: ".concat(response.status, " ").concat(response.statusText));
937
+ }
938
+ const data = await response.json();
939
+ return data.pipelineResponse[0].output[0].target;
940
+ }
941
+ async speechToEnglish(base64Audio) {
942
+ let sourceLanguage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'hi';
943
+ // Step 1: Transcribe audio to source language text
944
+ const transcribedText = await this.speechToText(base64Audio, sourceLanguage);
945
+
946
+ // Step 2: If already English, return as is
947
+ if (sourceLanguage === 'en') {
948
+ return {
949
+ transcription: transcribedText,
950
+ translation: transcribedText
951
+ };
952
+ }
953
+
954
+ // Step 3: Translate to English
955
+ const translatedText = await this.translateText(transcribedText, sourceLanguage, 'en');
956
+ return {
957
+ transcription: transcribedText,
958
+ translation: translatedText
959
+ };
960
+ }
961
+ async speechToHindi(base64Audio) {
962
+ let sourceLanguage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en';
963
+ // Step 1: Transcribe audio to source language text
964
+ const transcribedText = await this.speechToText(base64Audio, sourceLanguage);
965
+
966
+ // Step 2: If already Hindi, return as is
967
+ if (sourceLanguage === 'hi') {
968
+ return {
969
+ transcription: transcribedText,
970
+ translation: transcribedText
971
+ };
972
+ }
973
+
974
+ // Step 3: Translate to Hindi
975
+ const translatedText = await this.translateText(transcribedText, sourceLanguage, 'hi');
976
+ return {
977
+ transcription: transcribedText,
978
+ translation: translatedText
979
+ };
980
+ }
981
+ async transcribeSpeechToEnglish(base64Audio) {
982
+ let sourceLanguage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "hi";
983
+ // Step 1: Transcribe audio to source language text
984
+ const transcribedText = await this.speechToText(base64Audio, sourceLanguage);
985
+
986
+ // Step 2: If already English, return as is
987
+ if (sourceLanguage === "en") {
988
+ return {
989
+ transcription: transcribedText,
990
+ translation: transcribedText
991
+ };
992
+ }
993
+
994
+ // Step 3: Translate to English
995
+ const translatedText = await this.translateText(transcribedText, sourceLanguage, "en");
996
+ return {
997
+ transcription: transcribedText,
998
+ translation: translatedText
999
+ };
1000
+ }
1001
+ }
1002
+
1003
+ // audio-chat-screen.js - Audio chat screen component
1004
+ class AudioChatScreen {
1005
+ constructor() {
1006
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1007
+ this.primaryColor = options.primaryColor || "#1a5c4b";
1008
+ this.title = options.title || "Chat Assistant";
1009
+ this.onRecordStart = options.onRecordStart || (() => {});
1010
+ this.onRecordStop = options.onRecordStop || (() => {});
1011
+ this.onBack = options.onBack || (() => {});
1012
+ this.onOpenDrawer = options.onOpenDrawer || (() => {});
1013
+ this.onClose = options.onClose || (() => {});
1014
+ this.navigateToTextScreen = options.navigateToTextScreen;
1015
+ this.sendMessage = options.sendMessage || null;
1016
+ this.selectedLanguage = options.selectedLanguage || "en";
1017
+ this.container = null;
1018
+ this.messages = options.messages || [];
1019
+
1020
+ // Bhashini Integration
1021
+ this.bhashini = new BhashiniFrontend();
1022
+ this.mediaRecorder = null;
1023
+ this.audioChunks = [];
1024
+ this.isRecording = false;
1025
+
1026
+ // TTS tracking
1027
+ this.playedMessageIds = new Set();
1028
+ this.audioQueue = [];
1029
+ this.isPlaying = false;
1030
+
1031
+ // File attachments
1032
+ this.contentBlocks = [];
1033
+ this.SUPPORTED_FILE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
1034
+ }
1035
+ render(container) {
1036
+ this.container = container;
1037
+ this._applyStyles();
1038
+ container.innerHTML = "\n <div class=\"audio-chat-screen\">\n <div class=\"chat-header\">\n <div class=\"chat-header-content\">\n <button class=\"chat-back\" id=\"audio-chat-menu\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-menu-icon lucide-menu\"><path d=\"M4 5h16\"/><path d=\"M4 12h16\"/><path d=\"M4 19h16\"/></svg>\n </button>\n \n <div class=\"chat-header-text\">\n <div class=\"chat-title\">".concat(this.title, "</div>\n </div>\n </div>\n <button class=\"chat-close\" id=\"navigate-to-text-screen\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-message-square-text-icon lucide-message-square-text\"><path d=\"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z\"/><path d=\"M7 11h10\"/><path d=\"M7 15h6\"/><path d=\"M7 7h8\"/></svg>\n </button>\n &#8203; &#8203; &#8203;\n <button class=\"chat-close\" id=\"audio-chat-close\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </button>\n </div>\n \n \n <div class=\"chat-messages\" id=\"chat-messages\">\n <div class=\"chat-welcome\">\n <div class=\"welcome-text\">\uD83D\uDC4B Hello! I'm your AI assistant. How can I help you today?</div>\n </div>\n </div> \n \n \n <div class=\"file-attachments-container\" id=\"file-attachments-container\" style=\"display: none;\"></div>\n <div class=\"bottom-inputs\">\n <button id=\"record-button\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-mic-icon lucide-mic\"><path d=\"M12 19v3\"/><path d=\"M19 10v2a7 7 0 0 1-14 0v-2\"/><rect x=\"9\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\"/></svg>\n </button>\n &#8203; &#8203; &#8203;&#8203; &#8203; &#8203;\n <input\n type=\"file\"\n id=\"file-upload-input\"\n accept=\"image/jpeg,image/png,image/gif,image/webp\"\n style=\"display: none;\"\n />\n <button id=\"attachment-button\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-paperclip-icon lucide-paperclip\"><path d=\"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551\"/></svg>\n </button>\n </div>\n \n \n </div>\n ");
1039
+
1040
+ // Bind header events
1041
+ const menuBtn = container.querySelector("#audio-chat-menu");
1042
+ const closeBtn = container.querySelector("#audio-chat-close");
1043
+ const navigateToTextScreen = container.querySelector("#navigate-to-text-screen");
1044
+ if (menuBtn) {
1045
+ menuBtn.addEventListener("click", () => {
1046
+ if (this.onOpenDrawer) {
1047
+ this.onOpenDrawer();
1048
+ } else if (this.onBack) {
1049
+ this.onBack();
1050
+ }
1051
+ });
1052
+ }
1053
+ if (closeBtn) {
1054
+ closeBtn.addEventListener("click", () => {
1055
+ if (this.onClose) this.onClose();
1056
+ });
1057
+ }
1058
+ if (navigateToTextScreen) {
1059
+ navigateToTextScreen.addEventListener("click", () => {
1060
+ if (this.navigateToTextScreen) this.navigateToTextScreen();
1061
+ });
1062
+ }
1063
+
1064
+ // Bind audio chat events
1065
+ const recordBtn = container.querySelector("#record-button");
1066
+ const attachmentBtn = container.querySelector("#attachment-button");
1067
+ if (recordBtn) {
1068
+ recordBtn.addEventListener("click", () => {
1069
+ this.toggleRecording(recordBtn);
1070
+ });
1071
+ }
1072
+ const fileInput = container.querySelector("#file-upload-input");
1073
+ if (attachmentBtn && fileInput) {
1074
+ attachmentBtn.addEventListener("click", () => {
1075
+ fileInput.click();
1076
+ });
1077
+ fileInput.addEventListener("change", e => {
1078
+ this.handleFileUpload(e);
1079
+ });
1080
+ }
1081
+
1082
+ // Sync existing messages on render
1083
+ if (this.messages && this.messages.length > 0) {
1084
+ setTimeout(() => {
1085
+ this._syncMessages(this.messages);
1086
+ }, 50);
1087
+ }
1088
+ }
1089
+
1090
+ // Convert file to content block
1091
+ fileToContentBlock(file) {
1092
+ return new Promise((resolve, reject) => {
1093
+ const reader = new FileReader();
1094
+ reader.onload = () => {
1095
+ const base64Data = reader.result.split(",")[1];
1096
+ if (this.SUPPORTED_FILE_TYPES.includes(file.type)) {
1097
+ resolve({
1098
+ type: "image",
1099
+ source_type: "base64",
1100
+ mime_type: file.type,
1101
+ data: base64Data,
1102
+ metadata: {
1103
+ name: file.name,
1104
+ size: file.size
1105
+ }
1106
+ });
1107
+ } else {
1108
+ reject(new Error("Unsupported file type: ".concat(file.type)));
1109
+ }
1110
+ };
1111
+ reader.onerror = () => {
1112
+ reject(new Error("Failed to read file: ".concat(file.name)));
1113
+ };
1114
+ reader.readAsDataURL(file);
1115
+ });
1116
+ }
1117
+
1118
+ // Handle file upload
1119
+ async handleFileUpload(e) {
1120
+ const files = e.target.files;
1121
+ if (!files) return;
1122
+ const fileArray = Array.from(files);
1123
+ const validFiles = fileArray.filter(file => this.SUPPORTED_FILE_TYPES.includes(file.type));
1124
+ if (validFiles.length === 0) {
1125
+ if (fileArray.length > 0) {
1126
+ console.warn("Invalid file type.");
1127
+ }
1128
+ return;
1129
+ }
1130
+
1131
+ // Replace existing with the new one
1132
+ const file = validFiles[0];
1133
+ try {
1134
+ const block = await this.fileToContentBlock(file);
1135
+ this.contentBlocks = [block];
1136
+ this.renderFilePreview();
1137
+ } catch (error) {
1138
+ console.error("Error processing file:", error);
1139
+ }
1140
+
1141
+ // Clear input
1142
+ e.target.value = "";
1143
+ }
1144
+ removeBlock(index) {
1145
+ this.contentBlocks = []; // Since we only have max 1, removing index 0 means clearing all
1146
+ this.renderFilePreview();
1147
+ }
1148
+ renderFilePreview() {
1149
+ if (!this.container) return;
1150
+ const container = this.container.querySelector("#file-attachments-container");
1151
+ if (!container) return;
1152
+ if (!this.contentBlocks || this.contentBlocks.length === 0) {
1153
+ container.innerHTML = "";
1154
+ container.style.display = "none";
1155
+ return;
1156
+ }
1157
+ container.style.display = "flex";
1158
+ container.innerHTML = this.contentBlocks.map((block, index) => {
1159
+ var _block$metadata, _block$metadata2, _block$metadata3;
1160
+ const displayName = ((_block$metadata = block.metadata) === null || _block$metadata === void 0 ? void 0 : _block$metadata.filename) || ((_block$metadata2 = block.metadata) === null || _block$metadata2 === void 0 ? void 0 : _block$metadata2.name) || "file";
1161
+ const size = this.formatFileSize(((_block$metadata3 = block.metadata) === null || _block$metadata3 === void 0 ? void 0 : _block$metadata3.size) || 0);
1162
+ const isImage = block.type === "image";
1163
+ const src = isImage ? "data:".concat(block.mime_type, ";base64,").concat(block.data) : null;
1164
+ return "\n <div class=\"file-attachment ".concat(isImage ? "has-thumbnail" : "", "\" data-index=\"").concat(index, "\">\n <div class=\"file-thumbnail\">\n <img src=\"").concat(src, "\" alt=\"").concat(displayName, "\" class=\"file-thumbnail-image\" />\n </div>\n <div class=\"file-attachment-info\">\n <div class=\"file-attachment-name\" title=\"").concat(displayName, "\">\n ").concat(displayName, "\n </div>\n <div class=\"file-attachment-size\">").concat(size, "</div>\n </div>\n <button\n class=\"file-attachment-remove\"\n data-index=\"").concat(index, "\"\n title=\"Remove file\"\n >\n \u2715\n </button>\n </div>\n ");
1165
+ }).join("");
1166
+
1167
+ // Bind remove buttons
1168
+ container.querySelectorAll(".file-attachment-remove").forEach(btn => {
1169
+ btn.addEventListener("click", e => {
1170
+ e.stopPropagation();
1171
+ const index = parseInt(btn.getAttribute("data-index"));
1172
+ this.removeBlock(index);
1173
+ });
1174
+ });
1175
+ }
1176
+ async toggleRecording(btn) {
1177
+ if (this.isRecording) {
1178
+ this.stopRecording(btn);
1179
+ } else {
1180
+ await this.startRecording(btn);
1181
+ }
1182
+ }
1183
+ async startRecording(btn) {
1184
+ try {
1185
+ const stream = await navigator.mediaDevices.getUserMedia({
1186
+ audio: true
1187
+ });
1188
+ this.mediaRecorder = new MediaRecorder(stream);
1189
+ this.audioChunks = [];
1190
+ this.mediaRecorder.ondataavailable = event => {
1191
+ this.audioChunks.push(event.data);
1192
+ };
1193
+ this.mediaRecorder.onstop = async () => {
1194
+ const audioBlob = new Blob(this.audioChunks, {
1195
+ type: "audio/wav"
81
1196
  });
82
- closeBtn.addEventListener("click", function () {
83
- expanded.classList.remove("visible");
84
- toggle.style.display = "flex";
1197
+ this.audioChunks = [];
1198
+
1199
+ // Stop all tracks
1200
+ stream.getTracks().forEach(track => track.stop());
1201
+
1202
+ // Process audio
1203
+ await this.processAudioInput(audioBlob);
1204
+ };
1205
+ this.mediaRecorder.start();
1206
+ this.isRecording = true;
1207
+ this.onRecordStart();
1208
+
1209
+ // Update UI
1210
+ btn.classList.add("recording");
1211
+ btn.innerHTML = "\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-square-icon\"><rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" ry=\"2\"></rect></svg>\n ";
1212
+
1213
+ // Stop current TTS if any
1214
+ this.stopTTS();
1215
+ } catch (error) {
1216
+ console.error("Error accessing microphone:", error);
1217
+ alert("Could not access microphone. Please check permissions.");
1218
+ }
1219
+ }
1220
+ stopRecording(btn) {
1221
+ if (this.mediaRecorder && this.isRecording) {
1222
+ this.mediaRecorder.stop();
1223
+ this.isRecording = false;
1224
+ this.onRecordStop();
1225
+
1226
+ // Update UI
1227
+ btn.classList.remove("recording");
1228
+ btn.innerHTML = "\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-mic-icon lucide-mic\"><path d=\"M12 19v3\"/><path d=\"M19 10v2a7 7 0 0 1-14 0v-2\"/><rect x=\"9\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\"/></svg>\n ";
1229
+ }
1230
+ }
1231
+ async processAudioInput(audioBlob) {
1232
+ try {
1233
+ // Show processing state?
1234
+
1235
+ // 1. Convert to WAV Base64 (using Bhashini helper)
1236
+ const base64Audio = await this.bhashini.convertToWav(audioBlob);
1237
+
1238
+ // 2. STT
1239
+ const text = await this.bhashini.speechToText(base64Audio, this.selectedLanguage, this.selectedLanguage);
1240
+ if (text && text.trim()) {
1241
+ // 3. Send Message
1242
+ if (this.sendMessage) {
1243
+ await this.sendMessage(text, this.contentBlocks);
1244
+ // Clear attachments after sending
1245
+ this.contentBlocks = [];
1246
+ this.renderFilePreview(); // Update UI to remove preview
1247
+ }
1248
+ }
1249
+ } catch (error) {
1250
+ console.error("Error processing audio:", error);
1251
+ this.addMessage("Sorry, I couldn't understand that.", false, {
1252
+ isError: true
1253
+ });
1254
+ }
1255
+ }
1256
+ // 9113770648
1257
+ stopTTS() {
1258
+ // Cancel any active speech synthesis (if using browser API) or stop audio element
1259
+ if (this.currentAudio) {
1260
+ this.currentAudio.pause();
1261
+ this.currentAudio = null;
1262
+ }
1263
+ this.audioQueue = [];
1264
+ this.isPlaying = false;
1265
+ }
1266
+ async playNextInQueue() {
1267
+ // Check if audio screen is active
1268
+ const isVisible = this.container && this.container.querySelector(".audio-chat-screen");
1269
+ if (!isVisible) return;
1270
+ console.log("Playing next in queue", this.audioQueue);
1271
+ if (this.isPlaying || this.audioQueue.length === 0) return;
1272
+ this.isPlaying = true;
1273
+ const text = this.audioQueue.shift();
1274
+ try {
1275
+ const audioContent = await this.bhashini.textToSpeech(text, this.selectedLanguage);
1276
+ if (audioContent) {
1277
+ const audioSrc = "data:audio/wav;base64,".concat(audioContent);
1278
+ this.currentAudio = new Audio(audioSrc);
1279
+ this.currentAudio.onended = () => {
1280
+ this.isPlaying = false;
1281
+ this.playNextInQueue();
1282
+ };
1283
+ this.currentAudio.onerror = () => {
1284
+ this.isPlaying = false;
1285
+ this.playNextInQueue();
1286
+ };
1287
+ await this.currentAudio.play();
1288
+ } else {
1289
+ this.isPlaying = false;
1290
+ this.playNextInQueue();
1291
+ }
1292
+ } catch (error) {
1293
+ console.error("TTS Error:", error);
1294
+ this.isPlaying = false;
1295
+ this.playNextInQueue();
1296
+ }
1297
+ }
1298
+
1299
+ // Format file size (mirrors TextChatScreen)
1300
+ formatFileSize(bytes) {
1301
+ if (bytes === 0) return "0 Bytes";
1302
+ const k = 1024;
1303
+ const sizes = ["Bytes", "KB", "MB", "GB"];
1304
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1305
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
1306
+ }
1307
+
1308
+ // Get file type display name (mirrors TextChatScreen)
1309
+ getFileTypeDisplay(mimeType) {
1310
+ switch (mimeType) {
1311
+ case "image/jpeg":
1312
+ case "image/jpg":
1313
+ return "JPEG Image";
1314
+ case "image/png":
1315
+ return "PNG Image";
1316
+ case "image/gif":
1317
+ return "GIF Image";
1318
+ case "image/webp":
1319
+ return "WebP Image";
1320
+ case "application/pdf":
1321
+ return "PDF Document";
1322
+ default:
1323
+ return "Unknown File";
1324
+ }
1325
+ }
1326
+ _formatTime(date) {
1327
+ let hours = date.getHours();
1328
+ const minutes = date.getMinutes();
1329
+ const ampm = hours >= 12 ? 'PM' : 'AM';
1330
+ hours = hours % 12;
1331
+ hours = hours ? hours : 12;
1332
+ const strTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ' ' + ampm;
1333
+ return strTime;
1334
+ }
1335
+ addMessage(text, isUser) {
1336
+ let messageData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
1337
+ if (!this.container) return;
1338
+ const messagesContainer = this.container.querySelector("#chat-messages");
1339
+ if (!messagesContainer) return;
1340
+ const welcome = messagesContainer.querySelector(".chat-welcome");
1341
+ if (welcome) welcome.remove();
1342
+
1343
+ // Check if message already exists (for syncing)
1344
+ const messageId = (messageData === null || messageData === void 0 ? void 0 : messageData.id) || Date.now();
1345
+ const existingMessage = messagesContainer.querySelector("[data-message-id=\"".concat(messageId, "\"]"));
1346
+ if (existingMessage && messageData) {
1347
+ // Update existing message
1348
+ const bubble = existingMessage.querySelector(".message-bubble");
1349
+ if (bubble) {
1350
+ // Parse markdown for assistant messages, escape for user messages
1351
+ const content = messageData.content || text;
1352
+ bubble.innerHTML = !isUser ? this._parseMarkdown(content) : this._escapeHtml(content);
1353
+ }
1354
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
1355
+ return;
1356
+ }
1357
+ const messageEl = document.createElement("div");
1358
+ messageEl.className = "chat-message ".concat(isUser ? "user" : "bot");
1359
+ messageEl.setAttribute("data-message-id", messageId);
1360
+
1361
+ // Handle different message types
1362
+ let content = text;
1363
+ if (messageData) {
1364
+ if (messageData.isStreaming) {
1365
+ content = messageData.content || "Thinking...";
1366
+ } else if (messageData.isError) {
1367
+ content = messageData.content || "Error occurred";
1368
+ messageEl.classList.add("error");
1369
+ } else {
1370
+ content = messageData.content || text;
1371
+ }
1372
+ }
1373
+
1374
+ // Build attachments HTML if present
1375
+ let attachmentsHTML = "";
1376
+ if (messageData && messageData.attachments && messageData.attachments.length > 0) {
1377
+ attachmentsHTML = "\n <div class=\"message-attachments\">\n ".concat(messageData.attachments.map((attachment, index) => {
1378
+ var _attachment$metadata, _attachment$metadata2, _attachment$metadata3;
1379
+ const displayName = ((_attachment$metadata = attachment.metadata) === null || _attachment$metadata === void 0 ? void 0 : _attachment$metadata.name) || ((_attachment$metadata2 = attachment.metadata) === null || _attachment$metadata2 === void 0 ? void 0 : _attachment$metadata2.filename) || "Unknown file";
1380
+ const isImage = attachment.type === "image";
1381
+ const imageSrc = isImage && attachment.data ? "data:".concat(attachment.mime_type, ";base64,").concat(attachment.data) : null;
1382
+ return "\n <div class=\"message-attachment ".concat(isImage ? "image" : "pdf", "\" data-attachment-index=\"").concat(index, "\">\n <span class=\"message-attachment-icon\">\n ").concat(isImage ? "🖼️" : "📄", "\n </span>\n <div class=\"message-attachment-info\">\n <div \n class=\"message-attachment-name ").concat(isImage ? "clickable" : "", "\"\n ").concat(isImage && imageSrc ? "data-image-src=\"".concat(imageSrc, "\" data-image-alt=\"").concat(displayName, "\"") : "", "\n style=\"cursor: ").concat(isImage ? "pointer" : "default", ";\"\n >\n ").concat(this._escapeHtml(displayName), "\n </div>\n <div class=\"message-attachment-size\">\n ").concat(this.formatFileSize(((_attachment$metadata3 = attachment.metadata) === null || _attachment$metadata3 === void 0 ? void 0 : _attachment$metadata3.size) || 0), " \u2022 ").concat(this.getFileTypeDisplay(attachment.mime_type), "\n </div>\n </div>\n </div>\n ");
1383
+ }).join(""), "\n </div>\n ");
1384
+ }
1385
+ const timestamp = messageData !== null && messageData !== void 0 && messageData.timestamp ? new Date(messageData.timestamp) : new Date();
1386
+ const formattedTime = this._formatTime(timestamp);
1387
+
1388
+ // Parse markdown for assistant messages, escape for user messages
1389
+ const renderedContent = !isUser ? this._parseMarkdown(content) : this._escapeHtml(content);
1390
+ messageEl.innerHTML = "\n <div class=\"message-content\">\n ".concat(attachmentsHTML, "\n <div class=\"message-bubble\">").concat(renderedContent, "</div>\n <div class=\"message-time\">").concat(formattedTime, "</div>\n </div>\n ");
1391
+
1392
+ // Bind image click handlers for expansion
1393
+ if (messageData && messageData.attachments) {
1394
+ messageEl.querySelectorAll(".message-attachment-name.clickable").forEach(el => {
1395
+ el.addEventListener("click", e => {
1396
+ e.stopPropagation();
1397
+ const imageSrc = el.getAttribute("data-image-src");
1398
+ const imageAlt = el.getAttribute("data-image-alt");
1399
+ if (imageSrc) {
1400
+ this.showExpandedImage(imageSrc, imageAlt);
1401
+ }
85
1402
  });
86
- input.addEventListener("input", function () {
87
- sendBtn.disabled = !input.value.trim();
1403
+ });
1404
+ }
1405
+ messagesContainer.appendChild(messageEl);
1406
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
1407
+ }
1408
+
1409
+ // Sync messages from shared array, using same DOM structure as TextChatScreen
1410
+ _syncMessages(messages) {
1411
+ if (!this.container) return;
1412
+ const messagesContainer = this.container.querySelector("#chat-messages");
1413
+ if (!messagesContainer) return;
1414
+
1415
+ // Remove welcome message if there are any messages
1416
+ if (messages.length > 0) {
1417
+ const welcome = messagesContainer.querySelector(".chat-welcome");
1418
+ if (welcome) welcome.remove();
1419
+ }
1420
+
1421
+ // Get existing message elements
1422
+ const existingMessages = messagesContainer.querySelectorAll("[data-message-id]");
1423
+ const existingIds = new Set(Array.from(existingMessages).map(el => el.getAttribute("data-message-id")));
1424
+
1425
+ // Add or update messages
1426
+ messages.forEach(msg => {
1427
+ const msgId = String(msg.id);
1428
+
1429
+ // Handle TTS for new bot messages
1430
+ if (msg.sender !== "user" && !this.playedMessageIds.has(msgId) && !msg.isStreaming && !msg.isProcessing && msg.content) {
1431
+ this.playedMessageIds.add(msgId);
1432
+ this.audioQueue.push(msg.content);
1433
+ this.playNextInQueue();
1434
+ }
1435
+ if (existingIds.has(msgId)) {
1436
+ // Update existing message
1437
+ const existingEl = messagesContainer.querySelector("[data-message-id=\"".concat(msgId, "\"]"));
1438
+ if (existingEl) {
1439
+ const bubble = existingEl.querySelector(".message-bubble");
1440
+ if (bubble) {
1441
+ // Parse markdown for assistant messages, escape for user messages
1442
+ const content = msg.content || "";
1443
+ const isUserMessage = msg.sender === "user";
1444
+ bubble.innerHTML = !isUserMessage ? this._parseMarkdown(content) : this._escapeHtml(content);
1445
+ }
1446
+
1447
+ // Update attachments if they exist
1448
+ const messageContent = existingEl.querySelector(".message-content");
1449
+ if (messageContent && msg.attachments && msg.attachments.length > 0) {
1450
+ let attachmentsHTML = "\n <div class=\"message-attachments\">\n ".concat(msg.attachments.map((attachment, index) => {
1451
+ var _attachment$metadata4, _attachment$metadata5, _attachment$metadata6;
1452
+ const displayName = ((_attachment$metadata4 = attachment.metadata) === null || _attachment$metadata4 === void 0 ? void 0 : _attachment$metadata4.name) || ((_attachment$metadata5 = attachment.metadata) === null || _attachment$metadata5 === void 0 ? void 0 : _attachment$metadata5.filename) || "Unknown file";
1453
+ const isImage = attachment.type === "image";
1454
+ const imageSrc = isImage && attachment.data ? "data:".concat(attachment.mime_type, ";base64,").concat(attachment.data) : null;
1455
+ return "\n <div class=\"message-attachment ".concat(isImage ? "image" : "pdf", "\" data-attachment-index=\"").concat(index, "\">\n <span class=\"message-attachment-icon\">\n ").concat(isImage ? "🖼️" : "📄", "\n </span>\n <div class=\"message-attachment-info\">\n <div \n class=\"message-attachment-name ").concat(isImage ? "clickable" : "", "\"\n ").concat(isImage && imageSrc ? "data-image-src=\"".concat(imageSrc, "\" data-image-alt=\"").concat(displayName, "\"") : "", "\n style=\"cursor: ").concat(isImage ? "pointer" : "default", ";\"\n >\n ").concat(this._escapeHtml(displayName), "\n </div>\n <div class=\"message-attachment-size\">\n ").concat(this.formatFileSize(((_attachment$metadata6 = attachment.metadata) === null || _attachment$metadata6 === void 0 ? void 0 : _attachment$metadata6.size) || 0), " \u2022 ").concat(this.getFileTypeDisplay(attachment.mime_type), "\n </div>\n </div>\n </div>\n ");
1456
+ }).join(""), "\n </div>\n ");
1457
+
1458
+ // Insert or update attachments
1459
+ const existingAttachments = messageContent.querySelector(".message-attachments");
1460
+ if (existingAttachments) {
1461
+ existingAttachments.outerHTML = attachmentsHTML;
1462
+ } else {
1463
+ messageContent.insertAdjacentHTML("afterbegin", attachmentsHTML);
1464
+ }
1465
+
1466
+ // Re-bind image click handlers
1467
+ messageContent.querySelectorAll(".message-attachment-name.clickable").forEach(el => {
1468
+ // Remove existing listeners by cloning
1469
+ const newEl = el.cloneNode(true);
1470
+ el.parentNode.replaceChild(newEl, el);
1471
+ newEl.addEventListener("click", e => {
1472
+ e.stopPropagation();
1473
+ const imageSrc = newEl.getAttribute("data-image-src");
1474
+ const imageAlt = newEl.getAttribute("data-image-alt");
1475
+ if (imageSrc) {
1476
+ this.showExpandedImage(imageSrc, imageAlt);
1477
+ }
1478
+ });
1479
+ });
1480
+ }
1481
+
1482
+ // Update classes based on message state
1483
+ if (msg.isStreaming) {
1484
+ existingEl.classList.add("streaming");
1485
+ } else {
1486
+ existingEl.classList.remove("streaming");
1487
+ }
1488
+ if (msg.isError) {
1489
+ existingEl.classList.add("error");
1490
+ }
1491
+ }
1492
+ } else {
1493
+ // Add new message
1494
+ this.addMessage(msg.content || "", msg.sender === "user", msg);
1495
+ }
1496
+ });
1497
+
1498
+ // Remove messages that are no longer in the array
1499
+ existingMessages.forEach(el => {
1500
+ const msgId = el.getAttribute("data-message-id");
1501
+ const exists = messages.some(msg => String(msg.id) === msgId);
1502
+ if (!exists) {
1503
+ el.remove();
1504
+ }
1505
+ });
1506
+ messagesContainer.scrollTop = messagesContainer.scrollHeight;
1507
+ }
1508
+ _escapeHtml(text) {
1509
+ const div = document.createElement("div");
1510
+ div.textContent = text;
1511
+ return div.innerHTML;
1512
+ }
1513
+
1514
+ // Parse markdown to HTML
1515
+ _parseMarkdown(text) {
1516
+ if (!text || typeof text !== 'string') return '';
1517
+ let html = text;
1518
+
1519
+ // Escape HTML first to prevent XSS
1520
+ html = html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1521
+
1522
+ // Split into lines for processing
1523
+ const lines = html.split('\n');
1524
+ const processedLines = [];
1525
+ let inList = false;
1526
+ for (let i = 0; i < lines.length; i++) {
1527
+ let line = lines[i];
1528
+
1529
+ // Check for headers first (#, ##, ###, etc.)
1530
+ const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
1531
+ if (headerMatch) {
1532
+ if (inList) {
1533
+ processedLines.push('</ul>');
1534
+ inList = false;
1535
+ }
1536
+ const level = headerMatch[1].length;
1537
+ const headerText = headerMatch[2];
1538
+ // Process markdown inside header
1539
+ let processedHeader = headerText;
1540
+ processedHeader = processedHeader.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
1541
+ processedHeader = processedHeader.replace(/__([^_]+)__/g, '<strong>$1</strong>');
1542
+ processedHeader = processedHeader.replace(/(^|[^*])\*([^*]+)\*([^*]|$)/g, '$1<em>$2</em>$3');
1543
+ processedHeader = processedHeader.replace(/(^|[^_])_([^_]+)_([^_]|$)/g, '$1<em>$2</em>$3');
1544
+ processedLines.push("<h".concat(level, ">").concat(processedHeader, "</h").concat(level, ">"));
1545
+ continue;
1546
+ }
1547
+
1548
+ // Check if this is a list item (before processing bold/italic)
1549
+ const listMatch = line.match(/^[\s]*[-*]\s+(.+)$/);
1550
+ if (listMatch) {
1551
+ // Process markdown inside list item
1552
+ let listContent = listMatch[1];
1553
+
1554
+ // Bold: **text** (must be processed before italic)
1555
+ listContent = listContent.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
1556
+ listContent = listContent.replace(/__([^_]+)__/g, '<strong>$1</strong>');
1557
+
1558
+ // Italic: *text* (single asterisk, avoid matching **text**)
1559
+ listContent = listContent.replace(/(^|[^*])\*([^*]+)\*([^*]|$)/g, '$1<em>$2</em>$3');
1560
+ listContent = listContent.replace(/(^|[^_])_([^_]+)_([^_]|$)/g, '$1<em>$2</em>$3');
1561
+ if (!inList) {
1562
+ processedLines.push('<ul>');
1563
+ inList = true;
1564
+ }
1565
+ processedLines.push("<li>".concat(listContent, "</li>"));
1566
+ } else {
1567
+ if (inList) {
1568
+ processedLines.push('</ul>');
1569
+ inList = false;
1570
+ }
1571
+
1572
+ // Skip empty lines (they'll become <br> later)
1573
+ if (line.trim() === '') {
1574
+ processedLines.push('');
1575
+ continue;
1576
+ }
1577
+
1578
+ // Process markdown in non-list lines
1579
+ // Bold: **text** (must be processed before italic)
1580
+ line = line.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
1581
+ line = line.replace(/__([^_]+)__/g, '<strong>$1</strong>');
1582
+
1583
+ // Italic: *text* (single asterisk, avoid matching **text**)
1584
+ line = line.replace(/(^|[^*])\*([^*]+)\*([^*]|$)/g, '$1<em>$2</em>$3');
1585
+ line = line.replace(/(^|[^_])_([^_]+)_([^_]|$)/g, '$1<em>$2</em>$3');
1586
+
1587
+ // Inline code: `code`
1588
+ line = line.replace(/`([^`]+)`/g, '<code>$1</code>');
1589
+
1590
+ // Links: [text](url)
1591
+ line = line.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
1592
+ processedLines.push(line);
1593
+ }
1594
+ }
1595
+ if (inList) {
1596
+ processedLines.push('</ul>');
1597
+ }
1598
+
1599
+ // Join lines with <br> and return
1600
+ html = processedLines.join('<br>');
1601
+ return html;
1602
+ }
1603
+
1604
+ // Show expanded image modal (mirrors TextChatScreen)
1605
+ showExpandedImage(src, alt) {
1606
+ const existingModal = document.querySelector(".expanded-image-modal");
1607
+ if (existingModal) {
1608
+ existingModal.remove();
1609
+ }
1610
+ const modal = document.createElement("div");
1611
+ modal.className = "expanded-image-modal";
1612
+ modal.innerHTML = "\n <div class=\"expanded-image-container\">\n <button class=\"expanded-image-close\" title=\"Close\">\u2715</button>\n <img src=\"".concat(src, "\" alt=\"").concat(alt || "Image", "\" class=\"expanded-image\" />\n <div class=\"expanded-image-caption\">").concat(this._escapeHtml(alt || "Image preview"), "</div>\n </div>\n ");
1613
+ const closeModal = e => {
1614
+ if (e) e.stopPropagation();
1615
+ modal.remove();
1616
+ document.removeEventListener("mousedown", handleClickOutside);
1617
+ };
1618
+ const handleClickOutside = e => {
1619
+ if (!e.target.closest(".expanded-image-container")) {
1620
+ closeModal(e);
1621
+ }
1622
+ };
1623
+ modal.querySelector(".expanded-image-close").addEventListener("click", closeModal);
1624
+ modal.addEventListener("click", e => {
1625
+ if (e.target === modal) {
1626
+ closeModal(e);
1627
+ }
1628
+ });
1629
+ document.addEventListener("mousedown", handleClickOutside);
1630
+ document.body.appendChild(modal);
1631
+ }
1632
+ _applyStyles() {
1633
+ // Check if styles already applied
1634
+ if (document.getElementById('audio-chat-screen-styles')) return;
1635
+ const style = document.createElement("style");
1636
+ style.id = 'audio-chat-screen-styles';
1637
+ style.textContent = "\n .audio-chat-screen {\n flex: 1;\n height: 100%;\n display: flex;\n flex-direction: column;\n position: relative;\n overflow: hidden;\n background: linear-gradient(180deg, white 10%, #E1EFCC );\n }\n\n .audio-chat-screen .chat-header {\n color: ".concat(this.primaryColor, ";\n padding: 20px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n flex-shrink: 0;\n background: transparent;\n z-index: 20;\n }\n\n .audio-chat-screen .chat-header-content {\n display: flex;\n align-items: center;\n gap: 12px;\n flex: 1;\n }\n\n .audio-chat-screen .chat-back {\n background: ").concat(this.primaryColor, ";\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n margin-right: 8px;\n }\n\n .bottom-inputs {\n width: 100%;\n padding: 20px;\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n z-index: 10;\n flex-shrink: 0;\n }\n\n .bottom-inputs button {\n border: none;\n border-radius: 9999px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: all 0.2s ease;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n }\n\n #record-button {\n width: 50px;\n height: 50px;\n background: ").concat(this.primaryColor, ";\n color: #ffffff;\n }\n\n #record-button.recording {\n background: #ef4444;\n animation: pulse-ring 2s cubic-bezier(0.25, 0.46, 0.45, 0.94) infinite;\n }\n\n @keyframes pulse-ring {\n 0% {\n box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);\n }\n 70% {\n box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);\n }\n 100% {\n box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);\n }\n }\n\n #record-button:hover {\n transform: translateY(-2px) scale(1.03);\n box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);\n }\n\n #record-button:active {\n transform: translateY(0) scale(0.97);\n box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);\n }\n\n #attachment-button {\n width: 50px;\n height: 50px;\n background: #ffffff;\n color: ").concat(this.primaryColor, ";\n border: 1px solid rgba(148, 163, 184, 0.5);\n }\n\n #attachment-button:hover {\n transform: translateY(-2px) scale(1.03);\n box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);\n }\n\n #attachment-button:active {\n transform: translateY(1px);\n box-shadow: 0 3px 8px rgba(15, 23, 42, 0.15);\n }\n .audio-chat-screen .chat-avatar {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: rgba(255, 255, 255, 0.2);\n backdrop-filter: blur(10px);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .audio-chat-screen .chat-header-text {\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n\n .audio-chat-screen .chat-title {\n font-weight: 600;\n font-size: 20px;\n }\n\n .audio-chat-screen .chat-status {\n font-size: 12px;\n opacity: 0.9;\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n .audio-chat-screen .chat-close {\n background: ").concat(this.primaryColor, ";\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n }\n\n\n .audio-chat-screen .audio-chat-content {\n flex: 1;\n height:100%;\n display: flex;\n flex-direction: column;\n padding: 20px;\n gap: 20px;\n }\n\n .audio-chat-screen .audio-status {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 40px 20px;\n background: white;\n border-radius: 16px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n .audio-chat-screen .audio-status-icon {\n font-size: 48px;\n margin-bottom: 12px;\n transition: transform 0.3s;\n }\n\n .audio-chat-screen .audio-status-text {\n font-size: 16px;\n font-weight: 500;\n color: #475569;\n }\n\n /* Message list styles mirrored from TextChatScreen */\n .audio-chat-screen .chat-messages {\n flex: 1;\n padding: 20px;\n overflow-y: auto;\n overflow-x: hidden; /* Prevent horizontal scroll */\n min-height: 0; /* Crucial for nested flex scrolling */\n background: transparent;\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .audio-chat-screen .chat-messages::-webkit-scrollbar {\n width: 6px;\n }\n\n .audio-chat-screen .chat-messages::-webkit-scrollbar-track {\n background: transparent;\n }\n\n .audio-chat-screen .chat-messages::-webkit-scrollbar-thumb {\n background: #cbd5e1;\n border-radius: 3px;\n }\n\n .audio-chat-screen .file-attachments-container {\n padding: 8px 12px;\n background: transparent;\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n max-height: 120px;\n overflow-y: auto;\n position: relative;\n z-index: 5;\n }\n\n .audio-chat-screen .file-attachment {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 6px 10px;\n background: #f1f5f9;\n border: 1px solid #e2e8f0;\n border-radius: 8px;\n font-size: 12px;\n max-width: 200px;\n }\n\n .audio-chat-screen .file-thumbnail {\n width: 40px;\n height: 40px;\n border-radius: 6px;\n overflow: hidden;\n flex-shrink: 0;\n background: #e2e8f0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .audio-chat-screen .file-thumbnail-image {\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n .audio-chat-screen .file-attachment-info {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n\n .audio-chat-screen .file-attachment-name {\n font-weight: 500;\n color: #1e293b;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n max-width: 120px;\n }\n\n .audio-chat-screen .file-attachment-size {\n font-size: 11px;\n color: #64748b;\n }\n\n .audio-chat-screen .file-attachment-remove {\n background: transparent;\n border: none;\n color: #64748b;\n cursor: pointer;\n padding: 4px;\n border-radius: 4px;\n font-size: 16px;\n line-height: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n flex-shrink: 0;\n }\n\n .audio-chat-screen .file-attachment-remove:hover {\n background: #fee2e2;\n color: #dc2626;\n }\n\n .audio-chat-screen .chat-welcome {\n text-align: center;\n padding: 100px 20px;\n color: #64748b;\n }\n\n .audio-chat-screen .chat-welcome .welcome-icon {\n font-size: 48px;\n margin-bottom: 12px;\n }\n\n .audio-chat-screen .welcome-text {\n font-size: 15px;\n font-weight: 500;\n color: #475569;\n }\n\n .audio-chat-screen .chat-message {\n display: flex;\n gap: 8px;\n animation: messageSlide 0.3s ease-out;\n }\n\n @keyframes messageSlide {\n from {\n opacity: 0;\n transform: translateY(10px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n\n .audio-chat-screen .chat-message.user {\n flex-direction: row-reverse;\n }\n\n .audio-chat-screen .message-content {\n max-width: 75%;\n }\n\n .audio-chat-screen .message-bubble {\n padding: 12px 16px;\n border-radius: 16px;\n font-size: 14px;\n line-height: 1.5;\n word-wrap: break-word;\n }\n\n .audio-chat-screen .chat-message.user .message-bubble {\n background: #e9f5d7;\n color: ").concat(this.primaryColor, ";\n border-bottom-right-radius: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n .audio-chat-screen .chat-message.bot .message-bubble {\n background: white;\n color: #1e293b;\n border-bottom-left-radius: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n /* Markdown styles */\n .audio-chat-screen .message-bubble strong {\n font-weight: 600;\n color: inherit;\n }\n\n .audio-chat-screen .message-bubble em {\n font-style: italic;\n }\n\n .audio-chat-screen .message-bubble ul {\n margin: 0px 0;\n padding-left: 20px;\n list-style-type: disc;\n margin-bottom:0px;\n margin-top:5px;\n }\n\n .audio-chat-screen .message-bubble li {\n margin: 0;\n line-height: 1.1;\n padding-left: 3px;\n }\n\n .audio-chat-screen .message-bubble h1,\n .audio-chat-screen .message-bubble h2,\n .audio-chat-screen .message-bubble h3,\n .audio-chat-screen .message-bubble h4,\n .audio-chat-screen .message-bubble h5,\n .audio-chat-screen .message-bubble h6 {\n margin: 0px 0 0px 0;\n font-weight: 600;\n color: inherit;\n line-height: 1.3;\n }\n\n .audio-chat-screen .message-bubble h1 {\n font-size: 1.5em;\n }\n\n .audio-chat-screen .message-bubble h2 {\n font-size: 1.3em;\n }\n\n .audio-chat-screen .message-bubble h3 {\n font-size: 1.15em;\n }\n\n .audio-chat-screen .message-bubble h4 {\n font-size: 1.05em;\n }\n\n .audio-chat-screen .message-bubble h5 {\n font-size: 1em;\n }\n\n .audio-chat-screen .message-bubble h6 {\n font-size: 0.95em;\n }\n\n .audio-chat-screen .message-bubble code {\n background: rgba(0, 0, 0, 0.05);\n padding: 2px 6px;\n border-radius: 4px;\n font-family: 'Courier New', Courier, monospace;\n font-size: 0.9em;\n }\n\n .audio-chat-screen .message-bubble a {\n color: ").concat(this.primaryColor, ";\n text-decoration: underline;\n }\n\n .audio-chat-screen .message-bubble a:hover {\n opacity: 0.8;\n }\n \n .audio-chat-screen .message-bubble br {\n line-height: 0.1; /* Adjust between 0 and 1 */\n}\n\n\n .audio-chat-screen .message-time {\n font-size: 10px;\n color: #94a3b8;\n margin-top: 4px;\n text-align: right;\n }\n\n /* Message Attachments Styles (mirrored from TextChatScreen) */\n .audio-chat-screen .message-attachments {\n display: flex;\n flex-direction: column;\n gap: 8px;\n margin-bottom: 8px;\n }\n\n .audio-chat-screen .message-attachment {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 12px;\n background: #f1f5f9;\n border: 1px solid #e2e8f0;\n border-radius: 8px;\n font-size: 12px;\n max-width: 100%;\n }\n\n .audio-chat-screen .message-attachment.image {\n background: #f8fafc;\n }\n\n .audio-chat-screen .message-attachment.pdf {\n background: #fef2f2;\n }\n\n .audio-chat-screen .message-attachment-icon {\n font-size: 20px;\n flex-shrink: 0;\n }\n\n .audio-chat-screen .message-attachment-info {\n flex: 1;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n\n .audio-chat-screen .message-attachment-name {\n font-weight: 500;\n color: #1e293b;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n .audio-chat-screen .message-attachment-name.clickable:hover {\n color: ").concat(this.primaryColor, ";\n text-decoration: underline;\n }\n\n .audio-chat-screen .message-attachment-size {\n font-size: 11px;\n color: #64748b;\n }\n\n .audio-chat-screen .audio-messages {\n flex: 1;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-height: 200px;\n }\n\n .audio-chat-screen .audio-message {\n display: flex;\n gap: 8px;\n animation: messageSlide 0.3s ease-out;\n }\n\n .audio-chat-screen .audio-message.user {\n flex-direction: row-reverse;\n }\n\n .audio-chat-screen .audio-message-content {\n max-width: 75%;\n }\n\n .audio-chat-screen .audio-message-bubble {\n padding: 12px 16px;\n border-radius: 16px;\n font-size: 14px;\n line-height: 1.5;\n word-wrap: break-word;\n }\n\n .audio-chat-screen .audio-message.user .audio-message-bubble {\n background: ").concat(this.primaryColor, ";\n color: white;\n border-bottom-right-radius: 4px;\n }\n\n .audio-chat-screen .audio-message.assistant .audio-message-bubble {\n background: white;\n color: #1e293b;\n border-bottom-left-radius: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);\n }\n\n @keyframes messageSlide {\n from {\n opacity: 0;\n transform: translateY(10px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n\n .audio-chat-screen .audio-messages::-webkit-scrollbar {\n width: 6px;\n }\n\n .audio-chat-screen .audio-messages::-webkit-scrollbar-track {\n background: transparent;\n }\n\n .audio-chat-screen .audio-messages::-webkit-scrollbar-thumb {\n background: #cbd5e1;\n border-radius: 3px;\n }\n\n .audio-chat-screen .audio-controls {\n position: absolute;\n left: 50%;\n bottom: 20px;\n transform: translateX(-50%);\n display: flex;\n justify-content: center;\n align-items: center;\n pointer-events: none; /* let only the button receive events */\n }\n\n .audio-chat-screen .audio-controls .audio-record-btn {\n pointer-events: auto;\n }\n\n .audio-chat-screen .audio-record-btn {\n width: 80px;\n height: 80px;\n border-radius: 50%;\n background: ").concat(this.primaryColor, ";\n color: white;\n border: none;\n cursor: pointer;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 8px;\n transition: all 0.3s;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n }\n\n .audio-chat-screen .audio-record-btn:hover {\n transform: scale(1.05);\n box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);\n }\n\n .audio-chat-screen .audio-record-btn:active {\n transform: scale(0.95);\n }\n\n .audio-chat-screen .audio-record-btn.recording {\n background: #ef4444;\n animation: pulse-record 1.5s infinite;\n }\n\n @keyframes pulse-record {\n 0%, 100% {\n box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);\n }\n 50% {\n box-shadow: 0 4px 24px rgba(239, 68, 68, 0.6);\n }\n }\n\n .audio-chat-screen .audio-record-btn span {\n font-size: 11px;\n font-weight: 500;\n margin-top: 4px;\n }\n\n .audio-chat-screen .audio-record-btn svg {\n width: 32px;\n height: 32px;\n }\n\n @media (max-width: 768px) {\n .audio-chat-screen .audio-record-btn {\n width: 100px;\n height: 100px;\n }\n }\n\n /* Expanded Image Modal Styles */\n .expanded-image-modal {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.8);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n animation: fadeIn 0.2s ease;\n }\n\n @keyframes fadeIn {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n }\n\n .expanded-image-container {\n position: relative;\n max-width: 90%;\n max-height: 90vh;\n background: #fff;\n border-radius: 8px;\n overflow: hidden;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);\n animation: scaleIn 0.2s ease;\n display: flex;\n flex-direction: column;\n }\n\n @keyframes scaleIn {\n from {\n transform: scale(0.9);\n opacity: 0;\n }\n to {\n transform: scale(1);\n opacity: 1;\n }\n }\n\n .expanded-image-close {\n position: absolute;\n top: 12px;\n right: 12px;\n background: rgba(0, 0, 0, 0.6);\n border: none;\n color: white;\n width: 32px;\n height: 32px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 18px;\n z-index: 1;\n transition: all 0.2s;\n }\n\n .expanded-image-close:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n }\n\n .expanded-image {\n max-width: 100%;\n max-height: calc(90vh - 60px);\n object-fit: contain;\n display: block;\n }\n\n .expanded-image-caption {\n padding: 12px 16px;\n background: #fff;\n color: #1e293b;\n font-size: 14px;\n text-align: center;\n border-top: 1px solid #e2e8f0;\n }\n ");
1638
+ document.head.appendChild(style);
1639
+ }
1640
+ }
1641
+
1642
+ class ChatWidget {
1643
+ constructor() {
1644
+ let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1645
+ this.title = options.title || "Chat Assistant";
1646
+ this.placeholder = options.placeholder || "Type your message...";
1647
+ this.primaryColor = options.primaryColor || "#1a5c4b";
1648
+ this.container = null;
1649
+ this.messages = [];
1650
+ this.isMinimized = false;
1651
+ this.currentScreen = "welcome"; // welcome, text, audio
1652
+ this.textChatScreen = null;
1653
+ this.audioChatScreen = null;
1654
+
1655
+ // Configuration options for message sending
1656
+ this.langgraphUrl = options.langgraphUrl || "http://localhost:8080";
1657
+ this.authToken = options.authToken || null;
1658
+ this.threadId = options.threadId || null;
1659
+ this.assistantId = options.assistantId || null;
1660
+ this.selectedLanguage = options.selectedLanguage || "en";
1661
+ this.accessToken = options.accessToken || "";
1662
+ this.supabaseToken = options.supabaseToken || "";
1663
+ this.userInfo = options.userInfo || {};
1664
+ this.mcpServerUrl = options.mcpServerUrl || "http://localhost:8010/mcp";
1665
+ // Store the custom getHeaders function or use default
1666
+ this._customGetHeaders = options.getHeaders;
1667
+
1668
+ // Default getHeaders implementation
1669
+ this.getHeaders = () => {
1670
+ if (this._customGetHeaders) {
1671
+ return this._customGetHeaders();
1672
+ }
1673
+ const authToken = this.authToken || this.accessToken;
1674
+ const supabaseToken = this.supabaseToken || authToken;
1675
+ return _objectSpread2(_objectSpread2(_objectSpread2({
1676
+ "Content-Type": "application/json"
1677
+ }, authToken && {
1678
+ Authorization: "Bearer ".concat(authToken)
1679
+ }), supabaseToken && {
1680
+ "x-supabase-access-token": supabaseToken
1681
+ }), {}, {
1682
+ Origin: (typeof window !== 'undefined' ? window.location.origin : "*") || "*"
1683
+ });
1684
+ };
1685
+ this.getLatestCheckpoint = options.getLatestCheckpoint || (async () => null);
1686
+ this.updateThread = options.updateThread || (async () => {});
1687
+ this.getUserThreads = options.getUserThreads || (async _ref => {
1688
+ let {
1689
+ userId,
1690
+ userUuid
1691
+ } = _ref;
1692
+ try {
1693
+ const params = new URLSearchParams();
1694
+ if (userUuid) params.append("user_uuid", userUuid);
1695
+ const url = "".concat(this.langgraphUrl, "/history?").concat(params.toString());
1696
+ const response = await fetch(url, {
1697
+ method: "GET",
1698
+ headers: this.getHeaders()
88
1699
  });
89
- var send = function send() {
90
- var text = input.value.trim();
91
- if (!text) return;
92
- _this._addMessage(text, true);
93
- input.value = "";
94
- sendBtn.disabled = true;
95
- _this._showTypingIndicator();
96
- setTimeout(function () {
97
- _this._hideTypingIndicator();
98
- _this._addMessage("Thanks for your message! You said: \"".concat(text, "\""), false);
99
- }, 1000 + Math.random() * 1000);
1700
+ if (!response.ok) return {
1701
+ threads: []
1702
+ };
1703
+ return await response.json();
1704
+ } catch (e) {
1705
+ console.error("Error fetching threads", e);
1706
+ return {
1707
+ threads: []
100
1708
  };
101
- sendBtn.addEventListener("click", send);
102
- input.addEventListener("keypress", function (e) {
103
- if (e.key === "Enter" && !sendBtn.disabled) send();
104
- });
105
1709
  }
1710
+ });
1711
+ this.setUserInfoFromDirectChatLogin = options.setUserInfoFromDirectChatLogin || (() => {});
1712
+ this.setUserThreads = options.setUserThreads || (() => {});
1713
+ this.setUserThreadsMetaData = options.setUserThreadsMetaData || (() => {});
1714
+ this.languageOptions = [{
1715
+ label: "Assamese",
1716
+ value: "as"
106
1717
  }, {
107
- key: "_addMessage",
108
- value: function _addMessage(text, isUser) {
109
- var messagesContainer = this.container.querySelector("#chat-messages");
110
- var welcome = messagesContainer.querySelector(".chat-welcome");
111
- if (welcome) welcome.remove();
112
- var messageEl = document.createElement("div");
113
- messageEl.className = "chat-message ".concat(isUser ? "user" : "bot");
114
- messageEl.innerHTML = "<div class=\"message-bubble\">".concat(this._escapeHtml(text), "</div>");
115
- messagesContainer.appendChild(messageEl);
116
- messagesContainer.scrollTop = messagesContainer.scrollHeight;
117
- }
1718
+ label: "Bengali",
1719
+ value: "bn"
118
1720
  }, {
119
- key: "_showTypingIndicator",
120
- value: function _showTypingIndicator() {
121
- var messagesContainer = this.container.querySelector("#chat-messages");
122
- var indicator = document.createElement("div");
123
- indicator.className = "chat-message bot";
124
- indicator.id = "typing-indicator";
125
- indicator.innerHTML = "\n <div class=\"typing-indicator\">\n <div class=\"typing-dot\"></div>\n <div class=\"typing-dot\"></div>\n <div class=\"typing-dot\"></div>\n </div>\n ";
126
- messagesContainer.appendChild(indicator);
127
- messagesContainer.scrollTop = messagesContainer.scrollHeight;
128
- }
1721
+ label: "Dogri",
1722
+ value: "doi"
129
1723
  }, {
130
- key: "_hideTypingIndicator",
131
- value: function _hideTypingIndicator() {
132
- var indicator = this.container.querySelector("#typing-indicator");
133
- if (indicator) indicator.remove();
134
- }
1724
+ label: "English",
1725
+ value: "en"
1726
+ }, {
1727
+ label: "Gujarati",
1728
+ value: "gu"
135
1729
  }, {
136
- key: "_escapeHtml",
137
- value: function _escapeHtml(text) {
138
- var div = document.createElement("div");
139
- div.textContent = text;
140
- return div.innerHTML;
1730
+ label: "Hindi",
1731
+ value: "hi"
1732
+ }, {
1733
+ label: "Kannada",
1734
+ value: "kn"
1735
+ }, {
1736
+ label: "Konkani",
1737
+ value: "gom"
1738
+ }, {
1739
+ label: "Maithili",
1740
+ value: "mai"
1741
+ }, {
1742
+ label: "Malayalam",
1743
+ value: "ml"
1744
+ }, {
1745
+ label: "Marathi",
1746
+ value: "mr"
1747
+ }, {
1748
+ label: "Oriya",
1749
+ value: "or"
1750
+ }, {
1751
+ label: "Punjabi",
1752
+ value: "pa"
1753
+ }, {
1754
+ label: "Sanskrit",
1755
+ value: "sa"
1756
+ }, {
1757
+ label: "Sindhi",
1758
+ value: "sd"
1759
+ }, {
1760
+ label: "Tamil",
1761
+ value: "ta"
1762
+ }, {
1763
+ label: "Telugu",
1764
+ value: "te"
1765
+ }, {
1766
+ label: "Urdu",
1767
+ value: "ur"
1768
+ }];
1769
+
1770
+ // State management
1771
+ this.isLoading = false;
1772
+ this.isConnected = false;
1773
+ this.initialized = false;
1774
+ this.contentBlocks = [];
1775
+ this.playedAudioIds = new Set();
1776
+ this.currentInputAudio = null;
1777
+ this.submissionInProgress = false;
1778
+ this.processingAudioId = null;
1779
+ this._init();
1780
+
1781
+ // Initialize chat after DOM is ready
1782
+ if (typeof window !== 'undefined') {
1783
+ // Use setTimeout to ensure DOM is ready
1784
+ setTimeout(() => {
1785
+ this.initializeChat();
1786
+ }, 100);
1787
+ }
1788
+ }
1789
+ _init() {
1790
+ // Create container
1791
+ this.container = document.createElement("div");
1792
+ this.container.id = "chat-widget-container";
1793
+ this.container.innerHTML = "\n <div class=\"chat-widget-minimized\" id=\"chat-toggle\">\n <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path>\n </svg>\n </div>\n <div class=\"chat-widget-expanded\" id=\"chat-expanded\">\n <div class=\"chat-screen-container\" id=\"chat-screen-container\">\n <!-- Screens will be rendered here -->\n </div>\n <div class=\"chat-drawer-overlay\" id=\"chat-drawer-overlay\">\n <div class=\"chat-drawer\">\n <div class=\"drawer-header\">\n <div class=\"drawer-title\">Menu</div>\n </div>\n <div class=\"drawer-content\">\n <button class=\"drawer-item\" id=\"drawer-new-chat\">\n New Chat\n </button> \n <div class=\"language-selector-container\">\n <div class=\"custom-select\" id=\"language-selector\">\n <div class=\"select-trigger\" id=\"language-trigger\">\n <span id=\"selected-language-text\">English</span>\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"chevron\"><path d=\"m6 9 6 6 6-6\"/></svg>\n </div>\n <div class=\"select-options\" id=\"language-options\"></div>\n </div>\n </div>\n <div class=\"drawer-divider\" style=\"height: 1px; background: #e2e8f0; margin: 8px 0;\"></div>\n \n <div id=\"drawer-threads\" class=\"threads-container\">\n <!-- Threads will be rendered here -->\n <div class=\"threads-loading\">Loading history...</div>\n </div>\n </div>\n \n </div>\n <div class=\"drawer-backdrop\" id=\"drawer-backdrop\"></div>\n </div>\n </div>\n ";
1794
+ document.body.appendChild(this.container);
1795
+ this._applyStyles();
1796
+ this._initScreens();
1797
+ this._renderScreen();
1798
+ this._populateLanguageOptions();
1799
+ this._bindEvents();
1800
+ }
1801
+ _applyStyles() {
1802
+ const style = document.createElement("style");
1803
+ style.textContent = "\n @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');\n \n #chat-widget-container {\n position: fixed;\n bottom: 24px;\n right: 24px;\n z-index: 10000;\n font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n }\n.text-chat-screen {\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n .chat-header {\n color: ".concat(this.primaryColor, ";\n padding: 20px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .chat-header-content {\n display: flex;\n align-items: center;\n gap: 12px;\n flex: 1;\n }\n\n .chat-back {\n background: transparent;\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n border-radius: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n margin-right: 8px;\n }\n\n .chat-back:hover {\n background: rgba(255, 255, 255, 0.15);\n }\n\n .chat-avatar {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: rgba(255, 255, 255, 0.2);\n backdrop-filter: blur(10px);\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .chat-header-text {\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n \n .chat-title {\n font-weight: 600;\n font-size: 20px;\n }\n\n .chat-status {\n font-size: 12px;\n opacity: 0.9;\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n .chat-close {\n background: ").concat(this.primaryColor, ";\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n }\n\n .chat-widget-minimized {\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background: ").concat(this.primaryColor, ";\n color: white;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n }\n\n .chat-widget-minimized:hover {\n transform: scale(1.1);\n }\n\n @keyframes pulse {\n 0%, 100% { box-shadow: 0 8px 24px rgba(99, 102, 241, 0.4); }\n 50% { box-shadow: 0 8px 32px rgba(99, 102, 241, 0.6); }\n }\n\n .chat-widget-expanded {\n position: relative;\n width: 480px;\n height: 640px;\n background: white;\n border-radius: 16px;\n box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);\n display: none;\n flex-direction: column;\n overflow: hidden;\n animation: slideUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n }\n\n @keyframes slideUp {\n from {\n opacity: 0;\n transform: translateY(20px) scale(0.95);\n }\n to {\n opacity: 1;\n transform: translateY(0) scale(1);\n }\n }\n\n .chat-widget-expanded.visible {\n display: flex;\n }\n\n .chat-screen-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n /* Welcome Screen Styles */\n .welcome-screen {\n flex: 1;\n height: 100%;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n justify-content: start;\n background: linear-gradient(180deg, white 10%, #E1EFCC );\n padding: 0px;\n }\n\n .welcome-content {\n width: 80%;\n margin: auto;\n text-align: center;\n padding-top: 20px;\n }\n\n .welcome-icon {\n font-size: 64px;\n margin-bottom: 16px;\n animation: bounce 2s infinite;\n }\n\n @keyframes bounce {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-10px); }\n }\n\n .welcome-title {\n font-size: 24px;\n font-weight: 600;\n color: #1e293b;\n margin: 0 0 8px 0;\n }\n\n .welcome-subtitle {\n font-size: 14px;\n color: #64748b;\n margin: 0 0 32px 0;\n }\n\n .welcome-options {\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .welcome-option-btn {\n background: white;\n border: 2px solid #e2e8f0;\n border-radius: 12px;\n padding: 16px;\n display: flex;\n align-items: center;\n gap: 12px;\n cursor: pointer;\n transition: all 0.2s;\n text-align: left;\n width: 100%;\n }\n\n .welcome-option-btn:hover {\n border-color: ").concat(this.primaryColor, ";\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);\n transform: translateY(-2px);\n }\n\n .option-icon {\n font-size: 32px;\n flex-shrink: 0;\n }\n\n .option-content {\n flex: 1;\n }\n\n .option-title {\n font-size: 16px;\n font-weight: 600;\n color: #1e293b;\n margin-bottom: 4px;\n }\n\n .option-description {\n font-size: 13px;\n color: #64748b;\n }\n\n .welcome-option-btn svg {\n color: #94a3b8;\n flex-shrink: 0;\n }\n\n .welcome-option-btn:hover svg {\n color: ").concat(this.primaryColor, ";\n }\n.gradient-sphere-welcome-screen {\n width: 200px !important;\n height: 200px !important;\n border-radius: 50%;\n background: linear-gradient(135deg, #0a0d120f 0%, #85bc31 50%, #d0f19e 100%)\n !important;\n position: relative;\n margin: 20px auto 30px auto;\n box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);\n animation: float 3s ease-in-out infinite;\n flex-shrink: 0;\n}\n\n.sphere-highlight {\n position: absolute;\n top: 20%;\n right: 20%;\n width: 35px;\n height: 35px;\n background: radial-gradient(\n circle,\n rgba(255, 255, 255, 0.8) 0%,\n transparent 70%\n );\n border-radius: 50%;\n filter: blur(1px);\n}\n\n@keyframes float {\n 0%,\n 100% {\n transform: translateY(0px);\n }\n 50% {\n transform: translateY(-10px);\n }\n}\n\n.welcome-text {\n max-width: 400px;\n margin-bottom: 30px;\n flex-shrink: 0;\n text-align: left;\n}\n\n.greeting {\n font-size: 24px;\n font-weight: 600;\n color: #1a5c4b;\n margin: 0 0 16px 0;\n}\n\n.intro {\n font-size: 18px;\n font-weight: 500;\n color: #1a5c4b;\n margin: 0 0 12px 0;\n line-height: 1.4;\n}\n\n\n.action-buttons {\n display: flex;\n align-items: center;\n gap: 16px;\n flex-shrink: 0;\n margin-top: auto;\n /* padding-top: 10px; */\n padding-bottom: 20px;\n justify-content: center;\n width: 100%;\n align-self: center;\n}\n\n.primary-button {\n background: #1a5c4b;\n display:flex;\n color: white;\n border: none;\n padding: 16px 32px;\n border-radius: 25px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.3s ease;\n box-shadow: 0 4px 12px rgba(26, 92, 75, 0.3);\n}\n\n.primary-button:hover {\n transform: translateY(-2px);\n box-shadow: 0 6px 16px rgba(26, 92, 75, 0.4);\n}\n\n @media (max-width: 768px) {\n #chat-widget-container {\n bottom: 16px;\n right: 16px;\n }\n\n .chat-widget-expanded {\n width: 100vw;\n height: 100vh;\n border-radius: 0;\n max-width: 100vw;\n max-height: 100vh;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n }\n\n .chat-widget-expanded.visible {\n display: flex;\n }\n\n .welcome-content {\n max-width: 100%;\n padding-top: 40px;\n }\n\n .chat-drawer {\n width: 85% !important; /* Wider drawer on mobile */\n }\n }\n\n /* Drawer Styles */\n .chat-drawer-overlay {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2000;\n display: flex;\n pointer-events: none;\n visibility: hidden;\n }\n\n .chat-drawer-overlay.visible {\n pointer-events: auto;\n visibility: visible;\n }\n\n .chat-drawer {\n width: 65%;\n background: white;\n height: 100%;\n transform: translateX(-100%);\n transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);\n display: flex;\n flex-direction: column;\n z-index: 2002;\n box-shadow: 4px 0 24px rgba(0,0,0,0.1);\n }\n\n .chat-drawer-overlay.visible .chat-drawer {\n transform: translateX(0);\n }\n\n .drawer-backdrop {\n flex: 1;\n background: rgba(0, 0, 0, 0.5);\n opacity: 0;\n transition: opacity 0.3s ease;\n backdrop-filter: blur(2px);\n cursor: pointer;\n }\n\n .chat-drawer-overlay.visible .drawer-backdrop {\n opacity: 1;\n }\n\n .drawer-header {\n padding: 24px;\n border-bottom: 1px solid #f1f5f9;\n }\n\n .drawer-title {\n font-size: 20px;\n font-weight: 600;\n color: ").concat(this.primaryColor, ";\n }\n\n .drawer-content {\n flex: 1;\n padding: 16px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n overflow-y: auto;\n }\n\n .drawer-item {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 12px 16px;\n background: transparent;\n border: none;\n border-radius: 8px;\n color: #475569;\n font-size: 15px;\n font-weight: 500;\n cursor: pointer;\n transition: all 0.2s;\n text-align: left;\n }\n\n .drawer-item:hover {\n background: #f1f5f9;\n color: ").concat(this.primaryColor, ";\n }\n\n .drawer-item svg {\n opacity: 0.7;\n }\n\n .drawer-item:hover svg {\n opacity: 1;\n color: ").concat(this.primaryColor, ";\n }\n\n .drawer-footer {\n padding: 16px 24px;\n border-top: 1px solid #f1f5f9;\n }\n\n .drawer-version {\n font-size: 12px;\n color: #94a3b8;\n text-align: center;\n }\n\n /* Language Selector Styles */\n .language-selector-container {\n margin-top: 8px;\n margin-bottom: 8px;\n }\n\n .language-label {\n font-size: 11px;\n font-weight: 600;\n color: #94a3b8;\n margin-bottom: 6px;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n padding-left: 4px;\n }\n\n .custom-select {\n position: relative;\n width: 100%;\n user-select: none;\n }\n\n .select-trigger {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 12px;\n background: #f8fafc;\n border: 1px solid #e2e8f0;\n border-radius: 8px;\n cursor: pointer;\n transition: all 0.2s;\n font-size: 14px;\n color: #334155;\n }\n\n .select-trigger:hover {\n border-color: ").concat(this.primaryColor, ";\n background: white;\n }\n\n .select-trigger.active {\n border-color: ").concat(this.primaryColor, ";\n background: white;\n box-shadow: 0 0 0 2px rgba(26, 92, 75, 0.1);\n }\n\n .select-options {\n position: absolute;\n top: calc(100% + 4px);\n left: 0;\n right: 0;\n background: white;\n border: 1px solid #e2e8f0;\n border-radius: 8px;\n box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);\n max-height: 200px;\n overflow-y: auto;\n z-index: 50;\n display: none;\n opacity: 0;\n transform: translateY(-10px);\n transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n }\n\n .select-options.open {\n display: block;\n opacity: 1;\n transform: translateY(0);\n }\n\n .select-option {\n padding: 10px 12px;\n font-size: 14px;\n color: #334155;\n cursor: pointer;\n transition: all 0.1s;\n }\n\n .select-option:hover {\n background: #f1f5f9;\n color: ").concat(this.primaryColor, ";\n }\n\n .select-option.selected {\n background: rgba(26, 92, 75, 0.08);\n color: ").concat(this.primaryColor, ";\n font-weight: 500;\n }\n \n .chevron {\n transition: transform 0.2s ease;\n color: #94a3b8;\n }\n \n .select-trigger.active .chevron {\n transform: rotate(180deg);\n color: ").concat(this.primaryColor, ";\n }\n \n /* Thread List Styles */\n .threads-container {\n flex: 1;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding-top: 8px;\n }\n \n .threads-loading {\n padding: 16px;\n text-align: center;\n color: #94a3b8;\n font-size: 13px;\n }\n \n .thread-item {\n display: flex;\n flex-direction: column;\n padding: 10px 12px;\n border-radius: 8px;\n cursor: pointer;\n transition: all 0.2s;\n text-align: left;\n border: none;\n background: transparent;\n width: 100%;\n color: #475569;\n }\n \n .thread-item:hover {\n background-color: #f1f5f9; /* action.hover */\n color: ").concat(this.primaryColor, ";\n }\n \n .thread-item.selected {\n background-color: rgba(26, 92, 75, 0.08); /* action.selected */\n }\n \n .thread-content {\n font-size: 0.9rem;\n color: #334155;\n line-height: 1.3;\n margin-bottom: 4px;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n font-weight: 500;\n }\n \n .thread-date {\n font-size: 0.75rem;\n font-weight: 600;\n color: #94a3b8;\n }\n \n .no-history {\n padding: 16px;\n text-align: center;\n color: #94a3b8;\n font-size: 14px;\n }\n ");
1804
+ document.head.appendChild(style);
1805
+ }
1806
+ _renderScreen() {
1807
+ const screenContainer = this.container.querySelector("#chat-screen-container");
1808
+ switch (this.currentScreen) {
1809
+ case "welcome":
1810
+ this._renderWelcomeScreen(screenContainer);
1811
+ break;
1812
+ case "text":
1813
+ this._renderTextChatScreen(screenContainer);
1814
+ break;
1815
+ case "audio":
1816
+ this._renderAudioChatScreen(screenContainer);
1817
+ break;
1818
+ }
1819
+ }
1820
+ _initScreens() {
1821
+ // Initialize text chat screen
1822
+ this.textChatScreen = new TextChatScreen({
1823
+ title: this.title,
1824
+ placeholder: this.placeholder,
1825
+ primaryColor: this.primaryColor,
1826
+ onMessage: (text, respond) => {
1827
+ this._handleUserMessage(text, respond);
1828
+ },
1829
+ onBack: () => {
1830
+ this.currentScreen = "welcome";
1831
+ this._renderScreen();
1832
+ },
1833
+ onOpenDrawer: () => {
1834
+ this._toggleDrawer(true);
1835
+ },
1836
+ onClose: () => {
1837
+ const expanded = this.container.querySelector("#chat-expanded");
1838
+ const toggle = this.container.querySelector("#chat-toggle");
1839
+ expanded.classList.remove("visible");
1840
+ toggle.style.display = "flex";
1841
+ this.currentScreen = "welcome";
1842
+ this.messages = [];
1843
+ this.contentBlocks = [];
1844
+ this._initScreens();
1845
+ },
1846
+ messages: this.messages,
1847
+ sendMessage: (text, contentBlocks) => {
1848
+ return this.sendMessage(text, contentBlocks);
1849
+ },
1850
+ contentBlocks: this.contentBlocks,
1851
+ onContentBlocksChange: contentBlocks => {
1852
+ this.contentBlocks = contentBlocks;
1853
+ },
1854
+ navigateToAudioScreen: () => {
1855
+ this._navigateToScreen("audio");
141
1856
  }
142
- }]);
143
- }(); // Export as UMD and ESM compatible
144
- {
145
- module.exports = ChatWidget;
1857
+ });
1858
+
1859
+ // Initialize audio chat screen
1860
+ this.audioChatScreen = new AudioChatScreen({
1861
+ title: this.title,
1862
+ primaryColor: this.primaryColor,
1863
+ onRecordStart: () => {
1864
+ // Handle recording start
1865
+ },
1866
+ onRecordStop: () => {
1867
+ // Handle recording stop
1868
+ },
1869
+ onBack: () => {
1870
+ this.currentScreen = "welcome";
1871
+ this._renderScreen();
1872
+ },
1873
+ onOpenDrawer: () => {
1874
+ this._toggleDrawer(true);
1875
+ },
1876
+ onClose: () => {
1877
+ const expanded = this.container.querySelector("#chat-expanded");
1878
+ const toggle = this.container.querySelector("#chat-toggle");
1879
+ expanded.classList.remove("visible");
1880
+ toggle.style.display = "flex";
1881
+ this.currentScreen = "welcome";
1882
+ this.messages = [];
1883
+ this._initScreens();
1884
+ },
1885
+ messages: this.messages,
1886
+ sendMessage: (text, contentBlocks) => {
1887
+ return this.sendMessage(text, contentBlocks);
1888
+ },
1889
+ selectedLanguage: this.selectedLanguage,
1890
+ navigateToTextScreen: () => {
1891
+ this._navigateToScreen("text");
1892
+ }
1893
+ });
1894
+ }
1895
+ _renderWelcomeScreen(container) {
1896
+ container.innerHTML = "\n <main class=\"welcome-screen\">\n <div class=\"chat-header\">\n <div class=\"chat-header-content visible\">\n <div class=\"chat-header-text\">\n <div class=\"chat-title\">".concat(this.title, "</div>\n </div>\n </div>\n <button class=\"chat-close\" id=\"text-chat-close\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\">\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\"></line>\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\"></line>\n </svg>\n </button>\n </div>\n <div >\n <div class=\"welcome-content\">\n <div class=\"gradient-sphere-welcome-screen\">\n <div class=\"sphere-highlight\">\n </div>\n </div>\n \n <div class=\"welcome-text\">\n <p class=\"greeting\">Hello!</p>\n <p class=\"intro\">\n We are your Krishi Vigyan Sahayak\u2014KVS, a companion to help with every farming question! Tell us, what do you want to know today?\n </p>\n </div>\n \n <div class=\"action-buttons\">\n <button\n class=\"primary-button !rounded-full\"\n id=\"welcome-audio-btn\"\n >\n Let's talk &#8203; &#8203; <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-mic-icon lucide-mic\"><path d=\"M12 19v3\"/><path d=\"M19 10v2a7 7 0 0 1-14 0v-2\"/><rect x=\"9\" y=\"2\" width=\"6\" height=\"13\" rx=\"3\"/></svg>\n </button>\n </div>\n \n \n\n </div>\n </div>\n </main>\n ");
1897
+
1898
+ // Bind welcome screen events
1899
+ // const textBtn = container.querySelector("#welcome-text-btn");
1900
+ const audioBtn = container.querySelector("#welcome-audio-btn");
1901
+ const closeBtn = container.querySelector("#text-chat-close");
1902
+
1903
+ // textBtn.addEventListener("click", () => this._navigateToScreen("text"));
1904
+ audioBtn.addEventListener("click", () => this._navigateToScreen("audio"));
1905
+ if (closeBtn) {
1906
+ closeBtn.addEventListener("click", () => {
1907
+ const expanded = this.container.querySelector("#chat-expanded");
1908
+ const toggle = this.container.querySelector("#chat-toggle");
1909
+ expanded.classList.remove("visible");
1910
+ toggle.style.display = "flex";
1911
+ this.currentScreen = "welcome";
1912
+ this.messages = [];
1913
+ this._initScreens();
1914
+ });
1915
+ }
146
1916
  }
147
- })(chatWidget);
148
- var chatWidgetExports = chatWidget.exports;
149
- var chatWidget_default = /*@__PURE__*/getDefaultExportFromCjs(chatWidgetExports);
1917
+ _renderTextChatScreen(container) {
1918
+ if (this.textChatScreen) {
1919
+ // Sync contentBlocks before rendering
1920
+ this.textChatScreen.contentBlocks = this.contentBlocks;
1921
+ this.textChatScreen.messages = this.messages;
1922
+ this.textChatScreen.render(container);
1923
+ }
1924
+ }
1925
+ _renderAudioChatScreen(container) {
1926
+ if (this.audioChatScreen) {
1927
+ this.audioChatScreen.messages = this.messages;
1928
+ this.audioChatScreen.render(container);
1929
+ }
1930
+ }
1931
+ _navigateToScreen(screen) {
1932
+ this.currentScreen = screen;
1933
+ this._renderScreen();
1934
+ }
1935
+ _populateLanguageOptions() {
1936
+ const optionsContainer = this.container.querySelector("#language-options");
1937
+ if (!optionsContainer) return;
1938
+ optionsContainer.innerHTML = this.languageOptions.map(opt => "\n <div class=\"select-option ".concat(opt.value === this.selectedLanguage ? 'selected' : '', "\" data-value=\"").concat(opt.value, "\">\n ").concat(opt.label, "\n </div>\n ")).join('');
1939
+ this._updateSelectedLanguageDisplay();
1940
+ }
1941
+ _updateSelectedLanguageDisplay() {
1942
+ const textSpan = this.container.querySelector("#selected-language-text");
1943
+ if (textSpan) {
1944
+ const option = this.languageOptions.find(opt => opt.value === this.selectedLanguage);
1945
+ textSpan.textContent = option ? option.label : "English";
1946
+ }
1947
+ }
1948
+ _bindLanguageSelectorEvents() {
1949
+ const selector = this.container.querySelector("#language-selector");
1950
+ const trigger = this.container.querySelector("#language-trigger");
1951
+ const optionsFn = this.container.querySelector("#language-options");
1952
+ if (trigger && optionsFn) {
1953
+ trigger.addEventListener("click", e => {
1954
+ e.stopPropagation();
1955
+ const isOpen = optionsFn.classList.contains("open");
1956
+ if (isOpen) {
1957
+ optionsFn.classList.remove("open");
1958
+ trigger.classList.remove("active");
1959
+ } else {
1960
+ optionsFn.classList.add("open");
1961
+ trigger.classList.add("active");
1962
+ }
1963
+ });
1964
+ const options = optionsFn.querySelectorAll(".select-option");
1965
+ options.forEach(opt => {
1966
+ opt.addEventListener("click", e => {
1967
+ const value = e.currentTarget.dataset.value;
1968
+ this.selectedLanguage = value;
1969
+
1970
+ // Update UI
1971
+ this._updateSelectedLanguageDisplay();
1972
+ optionsFn.querySelectorAll(".select-option").forEach(o => o.classList.remove("selected"));
1973
+ e.currentTarget.classList.add("selected");
1974
+
1975
+ // Close dropdown
1976
+ optionsFn.classList.remove("open");
1977
+ trigger.classList.remove("active");
1978
+ console.log("Language selected:", this.selectedLanguage);
1979
+ });
1980
+ });
1981
+
1982
+ // Close on click outside
1983
+ document.addEventListener("click", e => {
1984
+ if (selector && !selector.contains(e.target)) {
1985
+ optionsFn.classList.remove("open");
1986
+ trigger.classList.remove("active");
1987
+ }
1988
+ });
1989
+ }
1990
+ }
1991
+ async _fetchThreads() {
1992
+ const threadsContainer = this.container.querySelector("#drawer-threads");
1993
+ if (!threadsContainer) return;
1994
+ threadsContainer.innerHTML = '<div class="threads-loading">Loading history...</div>';
1995
+ try {
1996
+ const storedUser = localStorage.getItem("DfsWeb.user-info");
1997
+ const user = storedUser ? JSON.parse(storedUser) : null;
1998
+ if (!(user !== null && user !== void 0 && user.uuid)) {
1999
+ threadsContainer.innerHTML = '<div class="no-history">Please log in to view history</div>';
2000
+ return;
2001
+ }
2002
+ console.log("USER ID", user.id, "USER UUID", user.uuid);
2003
+ const data = await this.getUserThreads({
2004
+ userId: user.id,
2005
+ userUuid: user.uuid
2006
+ });
2007
+ console.log("THREAD DATA", data);
2008
+ const threads = data.threads || [];
2009
+ const threadsWithHistory = threads.filter(thread => thread.history && thread.history.length > 0);
2010
+ this._renderThreadList(threadsWithHistory);
2011
+ } catch (error) {
2012
+ console.error("UNEXPECTED ERROR IN FETCHING THREADS", error.message);
2013
+ threadsContainer.innerHTML = '<div class="no-history">Failed to load history</div>';
2014
+ }
2015
+ }
2016
+ _renderThreadList(threads) {
2017
+ const threadsContainer = this.container.querySelector("#drawer-threads");
2018
+ if (!threadsContainer) return;
2019
+ if (threads.length === 0) {
2020
+ threadsContainer.innerHTML = '<div class="no-history">No history available</div>';
2021
+ return;
2022
+ }
2023
+ threadsContainer.innerHTML = '';
2024
+ threads.forEach(thread => {
2025
+ var _thread$history$;
2026
+ const isSelected = thread.thread_id === this.threadId; // Use current threadId
2027
+
2028
+ const threadItem = document.createElement('div');
2029
+ threadItem.className = "thread-item ".concat(isSelected ? 'selected' : '');
2030
+
2031
+ // Get primary text (first user message)
2032
+ const primaryText = ((_thread$history$ = thread.history[0]) === null || _thread$history$ === void 0 || (_thread$history$ = _thread$history$.values) === null || _thread$history$ === void 0 || (_thread$history$ = _thread$history$.messages[0]) === null || _thread$history$ === void 0 ? void 0 : _thread$history$.content) || "New Chat";
2033
+ // Handle array content (if content is array of blocks)
2034
+ let displayText = primaryText;
2035
+ if (Array.isArray(primaryText)) {
2036
+ const textBlock = primaryText.find(b => b.type === 'text');
2037
+ displayText = textBlock ? textBlock.text : "Multimedia Message";
2038
+ } else if (typeof primaryText === 'object') {
2039
+ displayText = "Message";
2040
+ }
2041
+ const date = new Date(thread.created_at).toLocaleString();
2042
+ threadItem.innerHTML = "\n <div class=\"thread-content\">".concat(displayText, "</div>\n <div class=\"thread-date\">").concat(date, "</div>\n ");
2043
+ threadItem.addEventListener('click', () => {
2044
+ this._handleThreadSelect(thread.thread_id);
2045
+ });
2046
+ threadsContainer.appendChild(threadItem);
2047
+ });
2048
+ }
2049
+ _handleThreadSelect(threadId) {
2050
+ console.log("Select thread:", threadId);
2051
+ this.threadId = threadId;
2052
+ this._toggleDrawer(false);
2053
+
2054
+ // Switch to text screen to show history
2055
+ this.currentScreen = "text";
2056
+
2057
+ // Clear current messages
2058
+ this.messages = [];
2059
+ this.setIsLoading = true; // Set loading state if you have setter, otherwise this.isLoading = true
2060
+ this.isLoading = true;
2061
+
2062
+ // Re-initialize screens (clears them)
2063
+ // this._initScreens(); // Can't fully re-init as it might break event listeners
2064
+ // Better to just load history and render
2065
+
2066
+ this._renderScreen();
2067
+
2068
+ // Load history for this thread
2069
+ this.loadHistory(threadId).then(() => {
2070
+ this.isLoading = false;
2071
+ this._renderScreen(); // Re-render with new messages
2072
+ });
2073
+ }
2074
+ _bindEvents() {
2075
+ const toggle = this.container.querySelector("#chat-toggle");
2076
+ const expanded = this.container.querySelector("#chat-expanded");
2077
+
2078
+ // Ensure toggle button is visible
2079
+ if (toggle) {
2080
+ toggle.style.display = "flex";
2081
+ }
2082
+ toggle.addEventListener("click", () => {
2083
+ console.log("Clicked");
2084
+ toggle.style.display = "none";
2085
+ expanded.classList.add("visible");
2086
+ this.currentScreen = "welcome";
2087
+ this._renderScreen();
2088
+ });
2089
+
2090
+ // Drawer events
2091
+ const drawerBackdrop = this.container.querySelector("#drawer-backdrop");
2092
+ if (drawerBackdrop) {
2093
+ drawerBackdrop.addEventListener("click", () => {
2094
+ this._toggleDrawer(false);
2095
+ });
2096
+ }
2097
+ const drawerItems = this.container.querySelectorAll(".drawer-item");
2098
+ drawerItems.forEach(item => {
2099
+ item.addEventListener("click", e => {
2100
+ // Handle drawer item click
2101
+ this._toggleDrawer(false);
2102
+ const targetId = e.currentTarget.id;
2103
+ if (targetId === "drawer-new-chat") {
2104
+ this._resetChat();
2105
+ }
2106
+ });
2107
+ });
2108
+ this._bindLanguageSelectorEvents();
2109
+ }
2110
+ _toggleDrawer(show) {
2111
+ const overlay = this.container.querySelector("#chat-drawer-overlay");
2112
+ if (!overlay) return;
2113
+ if (show) {
2114
+ overlay.classList.add("visible");
2115
+ // Fetch threads when drawer is opened
2116
+ this._fetchThreads();
2117
+ } else {
2118
+ overlay.classList.remove("visible");
2119
+ }
2120
+ }
2121
+ _resetChat() {
2122
+ this.messages = [];
2123
+ this.threadId = null;
2124
+ this.contentBlocks = [];
2125
+ // this.currentScreen = "welcome";
2126
+ this._initScreens();
2127
+ this._renderScreen();
2128
+ }
2129
+ _handleUserMessage(text, respond) {
2130
+ // Simple echo response - just returns what the user typed
2131
+ // The respond callback is provided by TextChatScreen
2132
+ if (respond) {
2133
+ respond("You said: \"".concat(text, "\""));
2134
+ }
2135
+ }
2136
+
2137
+ // Add message to shared messages array and update UI
2138
+ _addMessageToArray(message) {
2139
+ this.messages.push(message);
2140
+ this._notifyScreensUpdate();
2141
+ }
2142
+
2143
+ // Update message in shared messages array
2144
+ _updateMessageInArray(messageId, updates) {
2145
+ const index = this.messages.findIndex(msg => msg.id === messageId);
2146
+ if (index !== -1) {
2147
+ this.messages[index] = _objectSpread2(_objectSpread2({}, this.messages[index]), updates);
2148
+ this._notifyScreensUpdate();
2149
+ }
2150
+ }
2151
+
2152
+ // Notify all screens to update their UI
2153
+ _notifyScreensUpdate() {
2154
+ if (this.textChatScreen && this.textChatScreen.container) {
2155
+ this.textChatScreen._syncMessages(this.messages);
2156
+ }
2157
+ if (this.audioChatScreen && this.audioChatScreen.container) {
2158
+ this.audioChatScreen._syncMessages(this.messages);
2159
+ }
2160
+ }
2161
+
2162
+ // Send message function adapted from React version
2163
+ async sendMessage(inputValue) {
2164
+ let contentBlocks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
2165
+ if (!inputValue.trim() && contentBlocks.length === 0 || this.isLoading) {
2166
+ return;
2167
+ }
2168
+ console.log("📤 Sending text message - Language:", this.selectedLanguage, "Assistant ID:", this.assistantId || "Not available", "Thread ID:", this.threadId || "Not available", "Access token:", this.accessToken ? "Present" : "Empty - backend will handle");
2169
+
2170
+ // Prepare content blocks for the message
2171
+ const messageContent = [];
2172
+
2173
+ // Add text content if present
2174
+ if (inputValue.trim()) {
2175
+ const textContent = inputValue;
2176
+ messageContent.push({
2177
+ type: "text",
2178
+ text: textContent
2179
+ });
2180
+ }
2181
+
2182
+ // Add file attachments
2183
+ contentBlocks.forEach(block => {
2184
+ messageContent.push(block);
2185
+ });
2186
+
2187
+ // Create user message for display
2188
+ const userMessage = {
2189
+ id: Date.now(),
2190
+ content: inputValue.trim() || "📎 File attachments",
2191
+ sender: "user",
2192
+ timestamp: new Date().toISOString(),
2193
+ attachments: contentBlocks.length > 0 ? contentBlocks : null
2194
+ };
2195
+ console.log("USER MESSAGE", userMessage);
2196
+ console.log("USER MESSAGE CONTENTBLOCKS", contentBlocks);
2197
+ console.log("USER MESSAGE CONTENT", messageContent);
2198
+ this._addMessageToArray(userMessage);
2199
+ this.contentBlocks = [];
2200
+
2201
+ // Clear contentBlocks in text chat screen
2202
+ if (this.textChatScreen) {
2203
+ this.textChatScreen.contentBlocks = [];
2204
+ this.textChatScreen.renderFilePreview();
2205
+ this.textChatScreen.updateSendButton();
2206
+ }
2207
+
2208
+ // Reset states for text messages
2209
+ this.playedAudioIds.clear();
2210
+ this.currentInputAudio = null;
2211
+ this.submissionInProgress = false;
2212
+ this.processingAudioId = null;
2213
+ this.isLoading = true;
2214
+ try {
2215
+ // Always attempt to send message, let backend handle auth
2216
+ await this.sendMessageWithStreaming(messageContent);
2217
+ } catch (error) {
2218
+ console.error("Error sending message:", error);
2219
+ const errorMessage = {
2220
+ id: Date.now() + 1,
2221
+ content: "Sorry, I encountered an error. Please try again.",
2222
+ sender: "assistant",
2223
+ timestamp: new Date().toISOString(),
2224
+ isError: true
2225
+ };
2226
+ this._addMessageToArray(errorMessage);
2227
+ } finally {
2228
+ this.isLoading = false;
2229
+ }
2230
+ }
2231
+
2232
+ // Send message with streaming function adapted from React version
2233
+ async sendMessageWithStreaming(messageContent) {
2234
+ console.log("USER MESSAGE STREAMING", messageContent);
2235
+ console.log("📤 Sending text message - Language:", this.selectedLanguage, "Access token:", this.accessToken ? "Present" : "Not found");
2236
+ const assistantMessage = {
2237
+ id: Date.now() + 1,
2238
+ content: "",
2239
+ sender: "assistant",
2240
+ timestamp: new Date().toISOString(),
2241
+ isStreaming: true,
2242
+ isProcessing: true,
2243
+ textSessionId: Date.now() + 1,
2244
+ hasAudioResponse: false,
2245
+ inputType: "text"
2246
+ };
2247
+ this._addMessageToArray(assistantMessage);
2248
+ let latestRunId = null;
2249
+ try {
2250
+ var _currentAssistantMess;
2251
+ // Get the latest checkpoint to resume from the latest state
2252
+ const latestCheckpoint = await this.getLatestCheckpoint(this.threadId);
2253
+ console.log("📤 Sending message to backend:", _objectSpread2({
2254
+ input: {
2255
+ messages: [{
2256
+ id: "msg-".concat(Date.now()),
2257
+ type: "human",
2258
+ content: messageContent
2259
+ }],
2260
+ user_language: this.selectedLanguage,
2261
+ access_token: "[redacted]",
2262
+ user_info: JSON.stringify(this.userInfo)
2263
+ },
2264
+ config: {
2265
+ configurable: {}
2266
+ },
2267
+ metadata: {
2268
+ supabaseAccessToken: "[redacted]",
2269
+ user_language: this.selectedLanguage,
2270
+ input_type: "text",
2271
+ audio_content: null
2272
+ },
2273
+ stream_mode: ["values", "messages-tuple", "custom"],
2274
+ stream_subgraphs: true,
2275
+ assistant_id: this.assistantId,
2276
+ on_disconnect: "cancel"
2277
+ }, latestCheckpoint && {
2278
+ checkpoint: latestCheckpoint
2279
+ }));
2280
+ const response = await fetch("".concat(this.langgraphUrl, "/threads/").concat(this.threadId, "/runs/stream"), {
2281
+ method: "POST",
2282
+ headers: this.getHeaders(),
2283
+ body: JSON.stringify(_objectSpread2({
2284
+ input: {
2285
+ messages: [{
2286
+ id: "msg-".concat(Date.now()),
2287
+ type: "human",
2288
+ content: messageContent
2289
+ }],
2290
+ user_language: this.selectedLanguage,
2291
+ access_token: this.accessToken,
2292
+ user_info: JSON.stringify(this.userInfo)
2293
+ },
2294
+ config: {
2295
+ configurable: {}
2296
+ },
2297
+ metadata: {
2298
+ supabaseAccessToken: this.supabaseToken,
2299
+ user_language: this.selectedLanguage
2300
+ },
2301
+ stream_mode: ["values", "messages-tuple", "custom"],
2302
+ stream_subgraphs: true,
2303
+ assistant_id: this.assistantId,
2304
+ on_disconnect: "cancel"
2305
+ }, latestCheckpoint && {
2306
+ checkpoint: latestCheckpoint
2307
+ }))
2308
+ });
2309
+ if (!response.ok) {
2310
+ throw new Error("HTTP error! status: ".concat(response.status));
2311
+ }
2312
+
2313
+ // Handle streaming response
2314
+ const reader = response.body.getReader();
2315
+ const decoder = new TextDecoder();
2316
+ let buffer = "";
2317
+ let currentMessage = ""; // Local to this function scope
2318
+ let bestMessageText = "";
2319
+ let bestMessagePriority = -1;
2320
+ let lastUpdateTime = 0;
2321
+ const UPDATE_THROTTLE = 150; // Throttle updates to max ~7 per second
2322
+ const requestId = Date.now(); // Unique ID for this request
2323
+ let currentEvent = null; // Track current event type
2324
+ let currentData = null; // Track current data
2325
+ let hasReceivedMeaningfulResponse = false; // Track if we've received a meaningful response
2326
+ let finalResponse = ""; // Store the final meaningful response
2327
+ let latestUiAction = null; // Track the last ui_action from the last ui_action_mapper
2328
+ let endEventFinalized = false; // Track if we finalized on 'end' event
2329
+ let endFinalContent = ""; // Content used at 'end' event
2330
+ let currentAdditionalKwargs = null; // Chart-related additional kwargs captured from stream
2331
+ let chartUrlFromViz = null; // If stream provides a chart image URL, store it here and use it for the assistant message
2332
+
2333
+ console.log("🔍 Starting to process streaming response for requestId:", requestId);
2334
+
2335
+ // Prioritize human-readable assistant text over tool/JSON outputs
2336
+ const getNodePriority = nodeKey => {
2337
+ if (!nodeKey) return 0;
2338
+ const key = String(nodeKey).toLowerCase();
2339
+ if (key.includes("mdms_assistant") || key.includes("grievance_assistant") || key.includes("mandiprice_assistant")) return 0;
2340
+ if (key.includes("assistant") && !key.includes("tools")) return 3;
2341
+ if (key.includes("response_processor")) return 2;
2342
+ if (key.includes("post_assistant")) return 2;
2343
+ if (key.includes("ui_action_mapper")) return 1;
2344
+ return 0;
2345
+ };
2346
+ while (true) {
2347
+ const {
2348
+ done,
2349
+ value
2350
+ } = await reader.read();
2351
+ if (done) break;
2352
+ buffer += decoder.decode(value, {
2353
+ stream: true
2354
+ });
2355
+ const lines = buffer.split("\n");
2356
+ buffer = lines.pop() || "";
2357
+ for (const line of lines) {
2358
+ if (line.trim() === "") continue;
2359
+ console.log("📝 Processing SSE line:", {
2360
+ line: line.substring(0, 100) + (line.length > 100 ? "..." : ""),
2361
+ requestId: requestId
2362
+ });
2363
+ if (line.startsWith("data:")) {
2364
+ try {
2365
+ const data = JSON.parse(line.slice(5).trim());
2366
+ if (data.run_id) {
2367
+ console.log("🟢 Run ID:", data.run_id);
2368
+ latestRunId = data.run_id;
2369
+ }
2370
+ } catch (err) {
2371
+ console.error("Error parsing JSON:", err, line);
2372
+ }
2373
+ }
2374
+ if (line.startsWith("event: ")) {
2375
+ currentEvent = line.slice(7).trim();
2376
+ console.log("🎯 Event type:", currentEvent);
2377
+ } else if (line.startsWith("data: ")) {
2378
+ const jsonStr = line.slice(6).trim();
2379
+ if (jsonStr === "[DONE]") {
2380
+ console.log("🏁 Stream completed");
2381
+ break;
2382
+ }
2383
+ try {
2384
+ const data = JSON.parse(jsonStr);
2385
+ currentData = data;
2386
+ if (data.run_id) {
2387
+ console.log("🟢 Capturing run_id from parsed data:", data.run_id);
2388
+ latestRunId = data.run_id;
2389
+ }
2390
+
2391
+ // Handle end event
2392
+ if (currentEvent === "end") {
2393
+ console.log("🏁 Received event: end - finalizing message with run_id:", latestRunId);
2394
+ if (data.run_id) {
2395
+ latestRunId = data.run_id;
2396
+ console.log("🟢 Updated run_id from end event:", latestRunId);
2397
+ }
2398
+ if (currentMessage && currentMessage.length > 0) {
2399
+ var _this$messages$find;
2400
+ this._updateMessageInArray(assistantMessage.id, {
2401
+ content: currentMessage,
2402
+ additional_kwargs: currentAdditionalKwargs,
2403
+ isStreaming: false,
2404
+ isProcessing: false,
2405
+ hasAudioResponse: ((_this$messages$find = this.messages.find(m => m.id === assistantMessage.id)) === null || _this$messages$find === void 0 ? void 0 : _this$messages$find.hasAudioResponse) || false,
2406
+ latestRunId: latestRunId
2407
+ });
2408
+ endEventFinalized = true;
2409
+ endFinalContent = currentMessage;
2410
+ } else if (latestRunId) {
2411
+ this._updateMessageInArray(assistantMessage.id, {
2412
+ latestRunId: latestRunId,
2413
+ isStreaming: false,
2414
+ isProcessing: false
2415
+ });
2416
+ }
2417
+ }
2418
+ console.log("🔍 Parsed SSE data:", {
2419
+ event: currentEvent,
2420
+ hasData: !!data,
2421
+ dataKeys: data ? Object.keys(data) : "no data",
2422
+ topLevelKeys: Object.keys(data),
2423
+ hasAudioContent: data !== null && data !== void 0 && data.audio_content ? "YES" : "NO",
2424
+ hasResponseProcessor: data !== null && data !== void 0 && data.response_processor ? "YES" : "NO",
2425
+ hasRunId: data !== null && data !== void 0 && data.run_id ? "YES" : "NO",
2426
+ runId: (data === null || data === void 0 ? void 0 : data.run_id) || "N/A",
2427
+ requestId: requestId
2428
+ });
2429
+
2430
+ // Handle Authentication from smart_router
2431
+ if (data.smart_router && data.smart_router.access_token && data.smart_router.farmer_profile && data.smart_router.farmer_profile_fetched === true) {
2432
+ var _data$smart_router$fa, _data$smart_router$fa2;
2433
+ console.log("🔐 Authentication data detected in smart_router:", {
2434
+ hasAccessToken: !!data.smart_router.access_token,
2435
+ mobileNumber: data.smart_router.mobile_number,
2436
+ userUuid: data.smart_router.userUuid,
2437
+ hasFarmerProfile: !!data.smart_router.farmer_profile,
2438
+ farmerId: (_data$smart_router$fa = data.smart_router.farmer_profile) === null || _data$smart_router$fa === void 0 ? void 0 : _data$smart_router$fa.individualId,
2439
+ farmerName: (_data$smart_router$fa2 = data.smart_router.farmer_profile) === null || _data$smart_router$fa2 === void 0 ? void 0 : _data$smart_router$fa2.name,
2440
+ requestId: requestId
2441
+ });
2442
+ try {
2443
+ const smartRouter = data.smart_router;
2444
+ const farmerProfile = smartRouter.farmer_profile;
2445
+ const accessToken = smartRouter.access_token;
2446
+ localStorage.setItem("DfsWeb.access-token", accessToken);
2447
+ let userInfo = {};
2448
+ if (farmerProfile.user_details) {
2449
+ userInfo = _objectSpread2({}, farmerProfile.user_details);
2450
+ userInfo.name = farmerProfile.name || userInfo.name || "";
2451
+ if (!userInfo.uuid) {
2452
+ userInfo.uuid = smartRouter.userUuid;
2453
+ }
2454
+ if (!userInfo.mobileNumber) {
2455
+ userInfo.mobileNumber = smartRouter.mobile_number || farmerProfile.mobileNumber;
2456
+ }
2457
+ } else {
2458
+ userInfo = {
2459
+ id: null,
2460
+ uuid: smartRouter.userUuid,
2461
+ userName: smartRouter.mobile_number,
2462
+ name: farmerProfile.name || "",
2463
+ mobileNumber: smartRouter.mobile_number || farmerProfile.mobileNumber,
2464
+ emailId: farmerProfile.email || null,
2465
+ locale: null,
2466
+ type: "CITIZEN",
2467
+ roles: [{
2468
+ name: "Citizen",
2469
+ code: "CITIZEN",
2470
+ tenantId: farmerProfile.tenantId || "br"
2471
+ }],
2472
+ active: true,
2473
+ tenantId: farmerProfile.tenantId || "br",
2474
+ permanentCity: null
2475
+ };
2476
+ this.setUserInfoFromDirectChatLogin(userInfo);
2477
+ }
2478
+ this.userInfo = userInfo;
2479
+ this.accessToken = accessToken;
2480
+ if (userInfo.uuid) {
2481
+ console.log("USER INFO FOR UPDATING THREAD", userInfo);
2482
+ if (this.threadId) {
2483
+ this.updateThread(this.threadId, userInfo.uuid).then(updatedThread => {
2484
+ console.log("✅ Thread updated after authentication:", updatedThread);
2485
+ }).catch(error => {
2486
+ console.error("❌ Error updating thread after authentication:", error.message);
2487
+ });
2488
+ }
2489
+ this.getUserThreads({
2490
+ userId: userInfo.id,
2491
+ userUuid: userInfo.uuid
2492
+ }).then(data => {
2493
+ console.log("✅ Thread data fetched after authentication:", data);
2494
+ this.setUserThreads(data.threads);
2495
+ this.setUserThreadsMetaData({
2496
+ threads_processed: data.threads_processed,
2497
+ total_history_items: data.total_history_items,
2498
+ total_threads: data.total_threads
2499
+ });
2500
+ }).catch(error => {
2501
+ console.error("❌ Error fetching threads after authentication:", error.message);
2502
+ });
2503
+ }
2504
+ } catch (authError) {
2505
+ console.error("❌ Error processing authentication data:", authError);
2506
+ }
2507
+ }
2508
+
2509
+ // Handle UI Actions
2510
+ let uiActionSource = null;
2511
+ let actions = null;
2512
+ if (data.response_processor && Array.isArray(data.response_processor.ui_actions)) {
2513
+ actions = data.response_processor.ui_actions;
2514
+ } else if (data.response_processor && data.response_processor.messages && Array.isArray(data.response_processor.messages) && data.response_processor.messages.length > 0 && data.response_processor.messages[0].additional_kwargs && Array.isArray(data.response_processor.messages[0].additional_kwargs.ui_actions)) {
2515
+ actions = data.response_processor.messages[0].additional_kwargs.ui_actions;
2516
+ } else if (data.ui_action_mapper && Array.isArray(data.ui_action_mapper.ui_actions)) {
2517
+ uiActionSource = data.ui_action_mapper;
2518
+ actions = uiActionSource.ui_actions;
2519
+ } else if (data.mdms_ui_action_mapper && Array.isArray(data.mdms_ui_action_mapper.ui_actions)) {
2520
+ uiActionSource = data.mdms_ui_action_mapper;
2521
+ actions = uiActionSource.ui_actions;
2522
+ }
2523
+ if (actions && actions.length > 0) {
2524
+ console.log("UI ACTIONS", actions);
2525
+ const action = actions[actions.length - 1];
2526
+ if (action.web && action.web.link) {
2527
+ var _action$web$parameter, _action$web$parameter2, _action$web$parameter3, _action$web$parameter4, _action$web$parameter5;
2528
+ let scrollToId = null;
2529
+ let navigationParams = {};
2530
+ if (action.web.parameters) {
2531
+ if (action.web.parameters.scrollTo) {
2532
+ scrollToId = action.web.parameters.scrollTo;
2533
+ }
2534
+ navigationParams = _objectSpread2({}, action.web.parameters);
2535
+ } else if (action.web.link && action.web.link.includes("scrollTo=")) {
2536
+ const urlParams = new URLSearchParams(action.web.link.split("?")[1]);
2537
+ scrollToId = urlParams.get("scrollTo");
2538
+ }
2539
+ let finalLink = action.web.link;
2540
+ let finalMessage = action.message || "";
2541
+ const hasSchemeId = ((_action$web$parameter = action.web.parameters) === null || _action$web$parameter === void 0 ? void 0 : _action$web$parameter.schemeId) && action.web.parameters.schemeId !== "";
2542
+ let hasHelpName = null;
2543
+ if ((_action$web$parameter2 = action.web.parameters) !== null && _action$web$parameter2 !== void 0 && _action$web$parameter2.button_title) {
2544
+ hasHelpName = true;
2545
+ } else if ((_action$web$parameter3 = action.web.parameters) !== null && _action$web$parameter3 !== void 0 && _action$web$parameter3.name) {
2546
+ hasHelpName = true;
2547
+ } else {
2548
+ hasHelpName = false;
2549
+ }
2550
+ if (!hasSchemeId && !hasHelpName) {
2551
+ finalLink = "/help";
2552
+ finalMessage = "Please find more information about available schemes and services";
2553
+ }
2554
+ latestUiAction = {
2555
+ content: "",
2556
+ url: finalLink && !finalLink.startsWith("http") ? window.location.origin + finalLink : finalLink,
2557
+ originalUrl: finalLink,
2558
+ uiActionType: action.ui_action,
2559
+ scrollToId: scrollToId,
2560
+ navigationParams: _objectSpread2(_objectSpread2({}, navigationParams), hasHelpName && {
2561
+ name: ((_action$web$parameter4 = action.web.parameters) === null || _action$web$parameter4 === void 0 ? void 0 : _action$web$parameter4.button_title) || ((_action$web$parameter5 = action.web.parameters) === null || _action$web$parameter5 === void 0 ? void 0 : _action$web$parameter5.name)
2562
+ })
2563
+ };
2564
+ }
2565
+ }
2566
+
2567
+ // Chart Image Extraction
2568
+ if (data.analytics_visualization_node && data.analytics_visualization_node.messages) {
2569
+ const vizMessages = data.analytics_visualization_node.messages;
2570
+ if (vizMessages.length > 0) {
2571
+ const vizMessage = vizMessages[vizMessages.length - 1];
2572
+ if (typeof vizMessage === "string" && vizMessage.includes("additional_kwargs")) {
2573
+ const kwargsStart = vizMessage.indexOf("additional_kwargs=") + 18;
2574
+ const kwargsEnd = vizMessage.indexOf("} response_metadata");
2575
+ if (kwargsStart < kwargsEnd) {
2576
+ const kwargsString = vizMessage.substring(kwargsStart, kwargsEnd + 1);
2577
+ try {
2578
+ let cleanedKwargsString = kwargsString.replace(/'/g, '"').replace(/None/g, "null").replace(/True/g, "true").replace(/False/g, "false");
2579
+ const additionalKwargs = JSON.parse(cleanedKwargsString);
2580
+ if (additionalKwargs.chart_image_url) {
2581
+ console.log("🎯 Found chart image URL:", additionalKwargs.chart_image_url);
2582
+ currentAdditionalKwargs = additionalKwargs;
2583
+ try {
2584
+ const chartUrl = String(additionalKwargs.chart_image_url).trim();
2585
+ if (chartUrl.startsWith("http")) {
2586
+ chartUrlFromViz = chartUrl;
2587
+ console.log("🔖 Stored chartUrlFromViz:", chartUrlFromViz);
2588
+ }
2589
+ } catch (e) {
2590
+ console.warn("Failed to store chart image URL:", e);
2591
+ }
2592
+ } else if (additionalKwargs.antv_chart_data) {
2593
+ console.log("🎯 Found chart data (fallback):", additionalKwargs.antv_chart_data);
2594
+ currentAdditionalKwargs = additionalKwargs;
2595
+ }
2596
+ } catch (e) {
2597
+ console.warn("Failed to parse chart image additional_kwargs:", e);
2598
+ }
2599
+ }
2600
+ }
2601
+ if (typeof vizMessage === "string") {
2602
+ const contentMatch = vizMessage.match(/content=['"]([^'"]+)['"]/);
2603
+ if (contentMatch && contentMatch[1]) {
2604
+ const extractedUrl = contentMatch[1].trim();
2605
+ if (extractedUrl.startsWith("http")) {
2606
+ chartUrlFromViz = extractedUrl;
2607
+ console.log("🔖 Stored extracted chartUrlFromViz:", chartUrlFromViz);
2608
+ }
2609
+ }
2610
+ }
2611
+ }
2612
+ }
2613
+
2614
+ // Generic Content Extraction
2615
+ let lastContent = null;
2616
+ let lastNodeKey = null;
2617
+ let lastNodeMessages = null;
2618
+ Object.keys(data).forEach(nodeKey => {
2619
+ if (nodeKey !== "audio_content" && nodeKey !== "audio_processor" && nodeKey !== "ui_action_mapper") {
2620
+ const nodeData = data[nodeKey];
2621
+ if (nodeData && Array.isArray(nodeData.messages) && nodeData.messages.length > 0) {
2622
+ lastNodeKey = nodeKey;
2623
+ lastNodeMessages = nodeData.messages;
2624
+ }
2625
+ }
2626
+ });
2627
+ if (lastNodeMessages && lastNodeMessages.length > 0) {
2628
+ let lastMessage = lastNodeMessages[lastNodeMessages.length - 1];
2629
+ let content = "";
2630
+ if (typeof lastMessage === "string") {
2631
+ if (lastMessage.startsWith("content='") && lastMessage.includes("' additional_kwargs")) {
2632
+ const start = lastMessage.indexOf("content='") + 9;
2633
+ const end = lastMessage.indexOf("' additional_kwargs");
2634
+ content = lastMessage.substring(start, end).replace(/\\n/g, "\n").replace(/\\t/g, "\t").replace(/\\"/g, '"').replace(/\\'/g, "'");
2635
+ } else if (lastMessage.startsWith('content="') && lastMessage.includes('" additional_kwargs')) {
2636
+ const start = lastMessage.indexOf('content="') + 9;
2637
+ const end = lastMessage.indexOf('" additional_kwargs');
2638
+ content = lastMessage.substring(start, end).replace(/\\n/g, "\n").replace(/\\t/g, "\t").replace(/\\"/g, '"').replace(/\\'/g, "'");
2639
+ } else {
2640
+ const singleQuoteMatch = lastMessage.match(/content='([^']+)'/);
2641
+ const doubleQuoteMatch = lastMessage.match(/content="([^"]+)"/);
2642
+ if (singleQuoteMatch) {
2643
+ content = singleQuoteMatch[1];
2644
+ } else if (doubleQuoteMatch) {
2645
+ content = doubleQuoteMatch[1];
2646
+ } else {
2647
+ content = lastMessage;
2648
+ }
2649
+ }
2650
+ } else if (lastMessage && typeof lastMessage === "object") {
2651
+ if (typeof lastMessage.content === "string") {
2652
+ content = lastMessage.content;
2653
+ } else if (Array.isArray(lastMessage.content) && lastMessage.content.length > 0) {
2654
+ const textParts = lastMessage.content.map(part => typeof part === "string" ? part : typeof (part === null || part === void 0 ? void 0 : part.text) === "string" ? part.text : typeof (part === null || part === void 0 ? void 0 : part.value) === "string" ? part.value : "").filter(Boolean);
2655
+ content = textParts.join(" ").trim();
2656
+ } else {
2657
+ content = "";
2658
+ }
2659
+ }
2660
+ if (typeof content === "string" && content.trim().length > 0) {
2661
+ const looksLikeJson = content.trim().startsWith("{") || content.trim().startsWith("[");
2662
+ const priority = getNodePriority(lastNodeKey);
2663
+ if (looksLikeJson && priority < 2) {
2664
+ console.log("\u23ED\uFE0F Skipping JSON-like content from ".concat(lastNodeKey));
2665
+ } else {
2666
+ const MAX_LEN = 8000;
2667
+ const safeContent = content.length > MAX_LEN ? content.slice(0, MAX_LEN) + "\n\n… (truncated)" : content;
2668
+ currentMessage = safeContent;
2669
+ if (priority > bestMessagePriority || priority === bestMessagePriority && safeContent.length > bestMessageText.length) {
2670
+ bestMessageText = safeContent;
2671
+ bestMessagePriority = priority;
2672
+ }
2673
+ hasReceivedMeaningfulResponse = true;
2674
+ console.log("\uD83D\uDFE2 Found content from ".concat(lastNodeKey, ":"), safeContent.substring(0, 100) + "...");
2675
+ }
2676
+ }
2677
+ }
2678
+
2679
+ // Process based on event type
2680
+ if (data) {
2681
+ // Set default event type for data messages without explicit event
2682
+ const eventType = currentEvent || "values";
2683
+ console.log("🎵 Processing data message:", {
2684
+ eventType: eventType,
2685
+ currentEvent: currentEvent,
2686
+ dataKeys: Object.keys(data),
2687
+ requestId: requestId
2688
+ });
2689
+
2690
+ // Handle audio content in response
2691
+ if (data.audio_content && typeof data.audio_content === "string") {
2692
+ console.log("🎵 AUDIO CONTENT FOUND in text stream:", {
2693
+ audioContentLength: data.audio_content.length,
2694
+ audioContentPreview: data.audio_content.substring(0, 20) + "..."
2695
+ });
2696
+ const audioResponseId = "text_response_".concat(requestId, "_").concat(data.audio_content.substring(0, 30));
2697
+ const alreadyPlayed = this.playedAudioIds.has(audioResponseId);
2698
+ console.log("🔊 Text stream audio content received:", {
2699
+ audioResponseId: audioResponseId,
2700
+ requestId: requestId,
2701
+ alreadyPlayed: alreadyPlayed,
2702
+ audioContentLength: data.audio_content.length
2703
+ });
2704
+ if (!alreadyPlayed) {
2705
+ this.playedAudioIds.add(audioResponseId);
2706
+ // Mark the current assistant message as having audio response
2707
+ console.log("🔍 Setting audio content for message:", {
2708
+ targetMessageId: assistantMessage.id,
2709
+ audioContentLength: data.audio_content.length,
2710
+ audioContentPreview: data.audio_content.substring(0, 20) + "..."
2711
+ });
2712
+ this._updateMessageInArray(assistantMessage.id, {
2713
+ hasAudioResponse: true,
2714
+ audioContent: data.audio_content,
2715
+ latestRunId: latestRunId
2716
+ });
2717
+ console.log("✅ Stored audio response (text stream)");
2718
+
2719
+ // Clean up old audio IDs to prevent memory issues
2720
+ if (this.playedAudioIds.size > 10) {
2721
+ const audioIds = Array.from(this.playedAudioIds);
2722
+ this.playedAudioIds.clear();
2723
+ audioIds.slice(-5).forEach(id => this.playedAudioIds.add(id));
2724
+ }
2725
+ } else {
2726
+ console.log("⏭️ Skipping audio: already played");
2727
+ }
2728
+ } else {
2729
+ console.log("❌ No audio_content found in text stream data");
2730
+ }
2731
+
2732
+ // Handle audio content in response_processor
2733
+ if (data.response_processor && data.response_processor.audio_content && typeof data.response_processor.audio_content === "string") {
2734
+ console.log("🔍 Found audio_content in response_processor:", {
2735
+ audioContentLength: data.response_processor.audio_content.length,
2736
+ audioContentPreview: data.response_processor.audio_content.substring(0, 50) + "..."
2737
+ });
2738
+ const audioResponseId = "text_response_".concat(requestId, "_").concat(data.response_processor.audio_content.substring(0, 30));
2739
+ const alreadyPlayed = this.playedAudioIds.has(audioResponseId);
2740
+ console.log("🔊 Response processor audio content received:", {
2741
+ audioResponseId: audioResponseId,
2742
+ requestId: requestId,
2743
+ alreadyPlayed: alreadyPlayed,
2744
+ audioContentLength: data.response_processor.audio_content.length
2745
+ });
2746
+ if (!alreadyPlayed) {
2747
+ this.playedAudioIds.add(audioResponseId);
2748
+
2749
+ // Mark the current assistant message as having audio response
2750
+ console.log("🔍 Setting response processor audio content for message:", {
2751
+ targetMessageId: assistantMessage.id,
2752
+ audioContentLength: data.response_processor.audio_content.length,
2753
+ audioContentPreview: data.response_processor.audio_content.substring(0, 20) + "..."
2754
+ });
2755
+ this._updateMessageInArray(assistantMessage.id, {
2756
+ latestRunId: latestRunId,
2757
+ hasAudioResponse: true,
2758
+ audioContent: data.response_processor.audio_content
2759
+ });
2760
+ console.log("✅ Found matching message, setting response processor audio content");
2761
+
2762
+ // Clean up old audio IDs to prevent memory issues
2763
+ if (this.playedAudioIds.size > 10) {
2764
+ const audioIds = Array.from(this.playedAudioIds);
2765
+ this.playedAudioIds.clear();
2766
+ audioIds.slice(-5).forEach(id => this.playedAudioIds.add(id));
2767
+ }
2768
+ } else {
2769
+ console.log("⏭️ Skipping response processor audio: already played");
2770
+ }
2771
+ }
2772
+ }
2773
+ } catch (parseError) {
2774
+ console.log("⚠️ Failed to parse streaming data:", parseError);
2775
+ }
2776
+ }
2777
+ }
2778
+ }
2779
+
2780
+ // Ensure streaming is marked as complete for this specific assistant message
2781
+ console.log("🏁 Finalizing assistant message:", assistantMessage.id);
2782
+
2783
+ // Add a small delay to ensure audio content is properly set
2784
+ await new Promise(resolve => setTimeout(resolve, 100));
2785
+
2786
+ // Get the current state to ensure we have the latest audio content
2787
+ const currentAssistantMessage = this.messages.find(msg => msg.id === assistantMessage.id);
2788
+ console.log("🔍 Current assistant message before finalization:", {
2789
+ messageId: assistantMessage.id,
2790
+ hasAudioContent: !!(currentAssistantMessage !== null && currentAssistantMessage !== void 0 && currentAssistantMessage.audioContent),
2791
+ hasAudioResponse: currentAssistantMessage === null || currentAssistantMessage === void 0 ? void 0 : currentAssistantMessage.hasAudioResponse,
2792
+ audioContentLength: (currentAssistantMessage === null || currentAssistantMessage === void 0 || (_currentAssistantMess = currentAssistantMessage.audioContent) === null || _currentAssistantMess === void 0 ? void 0 : _currentAssistantMess.length) || 0
2793
+ });
2794
+
2795
+ // If message was already finalized at 'end' with content, do not override
2796
+ if (endEventFinalized && endFinalContent && endFinalContent.length > 10) {
2797
+ console.log("✅ Message already finalized on end event; skipping overwrite");
2798
+ } else {
2799
+ // Check if we have a meaningful response to display
2800
+ const finalText = bestMessageText && bestMessageText.length > 5 ? bestMessageText : currentMessage;
2801
+ // If a chart URL was captured from the viz node, prefer it and show only the image
2802
+ const contentToSet = chartUrlFromViz && String(chartUrlFromViz).startsWith("http") ? chartUrlFromViz : finalText;
2803
+ if (contentToSet && contentToSet.length > 10) {
2804
+ var _currentMsg$audioCont;
2805
+ console.log("🔍 Finalizing message with content:", {
2806
+ messageId: assistantMessage.id,
2807
+ currentMessageLength: String(contentToSet).length,
2808
+ currentMessagePreview: String(contentToSet).substring(0, 50) + "..."
2809
+ });
2810
+ const currentMsg = this.messages.find(m => m.id === assistantMessage.id);
2811
+ console.log("🔍 Finalizing message:", {
2812
+ latestRunId,
2813
+ messageId: assistantMessage.id,
2814
+ existingAudioContent: !!(currentMsg !== null && currentMsg !== void 0 && currentMsg.audioContent),
2815
+ existingAudioResponse: currentMsg === null || currentMsg === void 0 ? void 0 : currentMsg.hasAudioResponse,
2816
+ audioContentLength: (currentMsg === null || currentMsg === void 0 || (_currentMsg$audioCont = currentMsg.audioContent) === null || _currentMsg$audioCont === void 0 ? void 0 : _currentMsg$audioCont.length) || 0
2817
+ });
2818
+ this._updateMessageInArray(assistantMessage.id, {
2819
+ latestRunId: latestRunId,
2820
+ content: contentToSet,
2821
+ additional_kwargs: currentAdditionalKwargs,
2822
+ isStreaming: false,
2823
+ isProcessing: false,
2824
+ hasAudioResponse: (currentMsg === null || currentMsg === void 0 ? void 0 : currentMsg.hasAudioResponse) || false,
2825
+ // Preserve existing audio response state
2826
+ audioContent: (currentMsg === null || currentMsg === void 0 ? void 0 : currentMsg.audioContent) || null // Preserve existing audio content
2827
+ });
2828
+ } else {
2829
+ // If no meaningful response was found, show a clear, user-friendly fallback
2830
+ console.log("🔍 Finalizing message with friendly fallback");
2831
+ const currentMsg = this.messages.find(m => m.id === assistantMessage.id);
2832
+ this._updateMessageInArray(assistantMessage.id, {
2833
+ content: "Processing your request...",
2834
+ latestRunId: latestRunId,
2835
+ additional_kwargs: currentAdditionalKwargs,
2836
+ isStreaming: false,
2837
+ isProcessing: false,
2838
+ hasAudioResponse: (currentMsg === null || currentMsg === void 0 ? void 0 : currentMsg.hasAudioResponse) || false,
2839
+ audioContent: (currentMsg === null || currentMsg === void 0 ? void 0 : currentMsg.audioContent) || null
2840
+ });
2841
+ }
2842
+ }
2843
+
2844
+ // Handle UI actions if present
2845
+ if (latestUiAction) {
2846
+ console.log("🔗 Adding UI action message:", latestUiAction);
2847
+ const uiActionMessage = {
2848
+ id: Date.now() + 2,
2849
+ content: "",
2850
+ sender: "assistant",
2851
+ timestamp: new Date().toISOString(),
2852
+ isUiAction: true,
2853
+ url: latestUiAction.url,
2854
+ uiActionType: latestUiAction.uiActionType,
2855
+ scrollToId: latestUiAction.scrollToId,
2856
+ navigationParams: latestUiAction.navigationParams,
2857
+ originalUrl: latestUiAction.originalUrl,
2858
+ isScrollAction: latestUiAction.uiActionType === "scroll",
2859
+ isNavigateStateAction: latestUiAction.uiActionType === "navigate-state"
2860
+ };
2861
+ const lastMessage = this.messages[this.messages.length - 1];
2862
+ if (lastMessage) {
2863
+ const updatedLastMessage = _objectSpread2(_objectSpread2({}, lastMessage), {}, {
2864
+ uiActionMessage,
2865
+ latestRunId
2866
+ });
2867
+ console.log("UPDATED LAST MESSAGE", updatedLastMessage);
2868
+ this._updateMessageInArray(lastMessage.id, {
2869
+ uiActionMessage,
2870
+ latestRunId
2871
+ });
2872
+ }
2873
+ }
2874
+ } catch (error) {
2875
+ console.error("❌ Streaming error:", error);
2876
+ const currentMsg = this.messages.find(m => m.id === assistantMessage.id);
2877
+ this._updateMessageInArray(assistantMessage.id, {
2878
+ isStreaming: false,
2879
+ isProcessing: false,
2880
+ isError: true,
2881
+ content: "Error occurred while processing request",
2882
+ latestRunId: latestRunId || (currentMsg === null || currentMsg === void 0 ? void 0 : currentMsg.latestRunId) // Preserve or set latestRunId
2883
+ });
2884
+ }
2885
+ }
2886
+
2887
+ // Fetch assistant ID from API
2888
+ async fetchAssistantId() {
2889
+ try {
2890
+ console.log("🔍 Fetching assistant ID from API...");
2891
+
2892
+ // Use provided authToken or fallback to accessToken
2893
+ const authToken = this.authToken || this.accessToken;
2894
+ const supabaseToken = this.supabaseToken || authToken;
2895
+ const response = await fetch("".concat(this.langgraphUrl, "/assistants/search"), {
2896
+ method: "POST",
2897
+ headers: {
2898
+ "Content-Type": "application/json",
2899
+ Authorization: "Bearer ".concat(authToken),
2900
+ "x-supabase-access-token": supabaseToken,
2901
+ Origin: window.location.origin || "*"
2902
+ },
2903
+ body: JSON.stringify({
2904
+ limit: 100,
2905
+ offset: 0
2906
+ })
2907
+ });
2908
+ if (!response.ok) {
2909
+ console.log("\u274C API call failed with status: ".concat(response.status, " - backend may have rejected due to auth"));
2910
+ return null; // Return null instead of throwing to let backend handle auth
2911
+ }
2912
+ const assistants = await response.json();
2913
+ console.log("📋 Available assistants:", assistants);
2914
+
2915
+ // Log assistant details for debugging
2916
+ assistants.forEach((assistant, index) => {
2917
+ console.log("Assistant ".concat(index, ":"), {
2918
+ id: assistant.assistant_id,
2919
+ name: assistant.name,
2920
+ hasName: !!assistant.name,
2921
+ type: typeof assistant.name
2922
+ });
2923
+ });
2924
+
2925
+ // Find the assistant with name "Default Assistant"
2926
+ const defaultAssistant = assistants.filter(assistant => assistant.name && assistant.name.includes("Default"))[0];
2927
+ if (defaultAssistant) {
2928
+ console.log("✅ Found Default Assistant:", defaultAssistant.assistant_id);
2929
+ this.assistantId = defaultAssistant.assistant_id;
2930
+ return defaultAssistant.assistant_id;
2931
+ } else {
2932
+ console.log("⚠️ Default Assistant not found in the list");
2933
+
2934
+ // Find first assistant with a valid name
2935
+ const firstValidAssistant = assistants.find(assistant => assistant.name && assistant.name.trim() !== "");
2936
+ if (firstValidAssistant) {
2937
+ console.log("⚠️ Using first valid assistant as fallback:", firstValidAssistant.assistant_id, "Name:", firstValidAssistant.name);
2938
+ this.assistantId = firstValidAssistant.assistant_id;
2939
+ return firstValidAssistant.assistant_id;
2940
+ } else {
2941
+ console.log("❌ No assistants with valid names available");
2942
+ return null;
2943
+ }
2944
+ }
2945
+ } catch (error) {
2946
+ console.error("❌ Error fetching assistant ID:", error);
2947
+ console.log("🔍 Error details:", {
2948
+ name: error.name,
2949
+ message: error.message,
2950
+ isNetworkError: error.name === "TypeError"
2951
+ });
2952
+ return null; // Return null instead of throwing to let backend handle auth
2953
+ }
2954
+ }
2955
+
2956
+ // Load conversation history for a thread
2957
+ async loadHistory(threadId) {
2958
+ try {
2959
+ const response = await fetch("".concat(this.langgraphUrl, "/threads/").concat(threadId, "/history"), {
2960
+ method: "POST",
2961
+ headers: this.getHeaders(),
2962
+ body: JSON.stringify({
2963
+ limit: 10
2964
+ })
2965
+ });
2966
+ if (response.ok) {
2967
+ var _latestState$values;
2968
+ const history = await response.json();
2969
+ console.log("📜 Loaded history:", history);
2970
+
2971
+ // Get only the LATEST state (first item) which contains the complete conversation
2972
+ const latestState = history[0];
2973
+ if (!(latestState !== null && latestState !== void 0 && (_latestState$values = latestState.values) !== null && _latestState$values !== void 0 && _latestState$values.messages)) {
2974
+ console.log("No messages found in history");
2975
+ return;
2976
+ }
2977
+
2978
+ // Convert messages from the latest state only
2979
+ const historyMessages = [];
2980
+ latestState.values.messages.forEach((msg, msgIndex) => {
2981
+ if (msg.type === "human") {
2982
+ // Handle both text and audio content
2983
+ let content = "";
2984
+ let isAudio = false;
2985
+ if (Array.isArray(msg.content)) {
2986
+ const textContent = msg.content.find(c => c.type === "text");
2987
+ const audioContent = msg.content.find(c => c.type === "audio");
2988
+ if (audioContent) {
2989
+ content = "🎤 Audio message";
2990
+ isAudio = true;
2991
+ } else if (textContent) {
2992
+ content = textContent.text;
2993
+ }
2994
+ } else {
2995
+ content = msg.content;
2996
+ }
2997
+ historyMessages.push({
2998
+ id: "history-".concat(msgIndex, "-human"),
2999
+ content: content,
3000
+ sender: "user",
3001
+ timestamp: new Date().toISOString(),
3002
+ isAudio: isAudio
3003
+ });
3004
+ } else if (msg.type === "ai") {
3005
+ historyMessages.push({
3006
+ id: "history-".concat(msgIndex, "-ai"),
3007
+ content: msg.content,
3008
+ sender: "assistant",
3009
+ timestamp: new Date().toISOString()
3010
+ });
3011
+ }
3012
+ });
3013
+ if (historyMessages && historyMessages.length > 0) {
3014
+ console.log("\uD83D\uDCDD Loading ".concat(historyMessages.length, " messages from history"));
3015
+ // Add history messages to the messages array
3016
+ historyMessages.forEach(msg => {
3017
+ this._addMessageToArray(msg);
3018
+ });
3019
+ }
3020
+ }
3021
+ } catch (error) {
3022
+ console.error("❌ Failed to load history:", error);
3023
+ }
3024
+ }
3025
+
3026
+ // Initialize chat - fetch assistant ID and create thread
3027
+ async initializeChat() {
3028
+ try {
3029
+ console.log("🔄 Initializing chat...");
3030
+
3031
+ // Always attempt API calls, let backend handle authentication
3032
+ const currentToken = localStorage.getItem("DfsWeb.access-token");
3033
+ console.log("🔑 Access token status:", currentToken ? "Present" : "Empty - backend will handle");
3034
+
3035
+ // Always attempt to fetch assistant ID
3036
+ console.log("📞 Making API call to /assistants/search...");
3037
+ const fetchedAssistantId = await this.fetchAssistantId();
3038
+ if (!fetchedAssistantId) {
3039
+ console.log("❌ Failed to fetch assistant ID - backend may have rejected due to auth");
3040
+ this.isConnected = false;
3041
+ this.initialized = true;
3042
+ return;
3043
+ }
3044
+ console.log("✅ Assistant ID fetched successfully:", fetchedAssistantId);
3045
+ const storedUser = localStorage.getItem("DfsWeb.user-info");
3046
+ const user = storedUser ? JSON.parse(storedUser) : null;
3047
+
3048
+ // Always attempt to create thread
3049
+ console.log("📞 Making API call to /threads...");
3050
+ const response = await fetch("".concat(this.langgraphUrl, "/threads"), {
3051
+ method: "POST",
3052
+ headers: this.getHeaders(),
3053
+ body: JSON.stringify({
3054
+ metadata: {
3055
+ user_id: (user === null || user === void 0 ? void 0 : user.id) || null,
3056
+ user_uuid: (user === null || user === void 0 ? void 0 : user.uuid) || null
3057
+ }
3058
+ })
3059
+ });
3060
+ if (response.ok) {
3061
+ const thread = await response.json();
3062
+ this.threadId = thread.thread_id;
3063
+ this.isConnected = true;
3064
+ console.log("✅ Thread created:", thread.thread_id, "\n", thread);
3065
+
3066
+ // Load conversation history
3067
+ await this.loadHistory(thread.thread_id);
3068
+ } else {
3069
+ console.log("Thread created NOT");
3070
+ const errorText = await response.text();
3071
+ console.error("❌ Failed to create thread:", response.status, errorText);
3072
+ this.isConnected = false;
3073
+ }
3074
+ this.initialized = true;
3075
+ } catch (error) {
3076
+ console.error("❌ Thread creation error:", error);
3077
+ this.isConnected = false;
3078
+ this.initialized = true;
3079
+ }
3080
+ }
3081
+ }
150
3082
 
151
- export { chatWidget_default as default };
3083
+ export { ChatWidget as default };