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