File size: 25,850 Bytes
37da0c0
 
 
 
 
2190187
37da0c0
2190187
 
 
 
 
 
 
 
37da0c0
2190187
 
 
 
 
 
 
 
 
 
 
 
 
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37da0c0
 
 
 
 
 
 
 
2190187
 
 
37da0c0
 
 
 
 
 
 
 
2190187
37da0c0
2190187
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
2190187
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
2190187
37da0c0
 
2190187
 
 
 
37da0c0
 
 
 
 
2190187
37da0c0
 
 
2190187
 
37da0c0
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
 
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
37da0c0
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
 
37da0c0
 
 
 
 
2190187
37da0c0
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
37da0c0
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
 
37da0c0
 
 
 
 
2190187
37da0c0
 
 
 
 
 
 
2190187
 
37da0c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190187
37da0c0
 
 
 
 
 
2190187
37da0c0
 
 
2190187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37da0c0
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
// ----------------- ChatGPT API (Stream Mode) -----------------
// Define a constant for the model name so it is used in both API call and UI.
const MODEL_NAME = "gpt-4o-mini";

// Modified to scroll the current card to the bottom after updating the message.
function updateLastMessage(content, isStreaming = false) {
  const session = sessions[currentSessionIndex];
  const cursorHTML = `<span class="blinking-cursor"></span>`;
  session.messages[session.messages.length - 1].aiResponse = isStreaming ? content + cursorHTML : content;
  
  // Get the current scroll position of the last card before re-rendering
  const lastCardBefore = document.querySelector('.card:last-child');
  const prevScrollTop = lastCardBefore ? lastCardBefore.scrollTop : 0;
  
  // Re-render the conversation
  renderCurrentSession();
  
  // Use requestAnimationFrame to wait until the new DOM is laid out
  requestAnimationFrame(() => {
    const lastCardAfter = document.querySelector('.card:last-child');
    if (lastCardAfter) {
      if (isStreaming) {
        lastCardAfter.scrollTop = lastCardAfter.scrollHeight;
      } else {
        // Restore the previous scroll position
        lastCardAfter.scrollTop = prevScrollTop;
      }
    }
  });
}

// ----------------- Layout and Navigation -----------------
let isTraditionalLayout = false;
const toggleLayoutBtn = document.getElementById('toggleLayoutBtn');
const carouselWrapper = document.getElementById('carouselWrapper');
function updateLayout() {
  if (isTraditionalLayout) {
    carousel.classList.add('traditional');
    carouselWrapper.classList.add('traditional-mode');
    prevBtn.style.display = 'none';
    nextBtn.style.display = 'none';
    toggleLayoutBtn.innerHTML = `<img src="vertical.svg" alt="Icon" class="svg-icon">`;
  } else {
    carousel.classList.remove('traditional');
    carouselWrapper.classList.remove('traditional-mode');
    prevBtn.style.display = '';
    nextBtn.style.display = '';
    toggleLayoutBtn.innerHTML = `<img src="horizontal.svg" alt="Icon" class="svg-icon">`;
  }
  updateTurnLabel(sessionMessagesCount());
}
toggleLayoutBtn.addEventListener('click', function() {
  isTraditionalLayout = !isTraditionalLayout;
  updateLayout();
});

// This function will move hamburger + new chat button between nav-bar and the chat header
function updateHamburgerPosition() {
  const hamburgerBtn = document.getElementById('hamburgerBtn');
  const newSessionBtn = document.getElementById('newSessionBtn');
  const toggleLayoutBtn = document.getElementById('toggleLayoutBtn');
  const navBar = document.getElementById('navBar');
  const navHeader = navBar.querySelector('.nav-header');
  const headerLeft = document.getElementById('headerLeft');
  if (navBar.classList.contains('hidden')) {
    // Move both hamburger and new chat to header-left
    headerLeft.appendChild(hamburgerBtn);
    headerLeft.appendChild(newSessionBtn);
    headerLeft.appendChild(toggleLayoutBtn);    
  } else {
    // Move both back to navHeader
    navHeader.appendChild(hamburgerBtn);
    navHeader.appendChild(newSessionBtn);
    navHeader.appendChild(toggleLayoutBtn);
  }
}

// ----------------- Session Management -----------------
let sessions = [];
let currentSessionIndex = 0;
let currentCardIndex = 0;
function initSessions() {
  sessions.push({
    id: Date.now() + '-' + Math.random().toString(36).substr(2, 9),
    name: "Chat Session 1",
    title: "Chat Session 1",
    messages: [],
    summary: "# Chat Summary\n\nThis is the default summary for Chat Session 1.",
    settings: {
      temperature: 0.7,
      maxTokens: 1024,
      persona: "professional",
      model: "gpt-4o-mini" // <-- new property
    }
  });
  currentSessionIndex = 0;
  currentCardIndex = 0;
  renderSessionList();
  renderCurrentSession();
}
function renderSessionList() {
  const sessionList = document.getElementById('sessionList');
  sessionList.innerHTML = "";
  sessions.forEach((session, index) => {
    const li = document.createElement('li');
    const nameSpan = document.createElement('span');
    nameSpan.textContent = session.name;
    li.appendChild(nameSpan);
    const removeBtn = document.createElement('button');
    removeBtn.textContent = "𝘅";
    removeBtn.className = "remove-session";
    removeBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      removeSession(index);
    });
    li.appendChild(removeBtn);
    li.addEventListener('click', () => {
      currentSessionIndex = index;
      currentCardIndex = 0;
      renderSessionList();
      renderCurrentSession();
    });
    if (index === currentSessionIndex) li.classList.add('active');
    sessionList.appendChild(li);
  });
}
document.getElementById('newSessionBtn').addEventListener('click', () => {
    const newSession = {
        id: Date.now() + '-' + Math.random().toString(36).substr(2, 9),
        name: "Chat Session " + (sessions.length + 1),
        title: "Chat Session " + (sessions.length + 1),
        messages: [],
        summary: "# Chat Summary\n\nThis is the default summary for Chat Session " + (sessions.length + 1) + ".",
        settings: {
            temperature: 0.7,
            maxTokens: 1024,
            persona: "professional",
            model: "gpt-4o-mini" // <-- default model
        }
    };

  sessions.push(newSession);
  currentSessionIndex = sessions.length - 1;
  currentCardIndex = 0;
  renderSessionList();
  renderCurrentSession();
});
function removeSession(index) {
  sessions.splice(index, 1);
  if (sessions.length === 0) {
    initSessions();
  } else {
    if (currentSessionIndex >= sessions.length) {
      currentSessionIndex = sessions.length - 1;
    }
    currentCardIndex = 0;
  }
  renderSessionList();
  renderCurrentSession();
}
// ----------------- Carousel Rendering / Traditional Layout -----------------
const carousel = document.getElementById('carousel');
function renderCurrentSession() {
  const session = sessions[currentSessionIndex];
  carousel.innerHTML = "";
  session.messages.forEach(message => {
    const card = document.createElement('div');
    card.className = 'card';
    let attachmentHTML = "";
    if (message.attachments && message.attachments.length > 0) {
      attachmentHTML = `
        <div class="vertical-file-list">
          ${message.attachments.map(file => `<div class="file-item-vertical">${file.path}</div>`).join("")}
        </div>
      `;
    }
    // Order: User message then AI message, rendered in Markdown
    card.innerHTML = `
      <div class="conversation">
        <div class="message user">
          ${attachmentHTML}
          <div class="message-text markdown-body">${marked.parse(message.userText)}</div>
        </div>
        <div class="message ai">
          <div class="message-text markdown-body">${marked.parse(message.aiResponse)}</div>
          <div class="ai-status">${message.model || session.settings.model}</div>
        </div>
      </div>
    `;
    carousel.appendChild(card);
    processMessagesInContainer(card);
  });
  currentCardIndex = session.messages.length > 0 ? session.messages.length - 1 : 0;
  updateCarousel();
  updateLayout();
  document.getElementById('chatTitle').textContent = session.title;
}
function updateCarousel() {
  if (!isTraditionalLayout) {
    const cards = document.querySelectorAll('.card');
    carousel.style.transform = `translateX(-${currentCardIndex * 100}%)`;
  }
  updateTurnLabel(sessionMessagesCount());
}
function sessionMessagesCount() {
  return sessions[currentSessionIndex].messages.length;
}
function updateTurnLabel(totalCards) {
  const turnLabel = document.getElementById('turnLabel');
  if (isTraditionalLayout) {
    turnLabel.textContent = `Turn: ${totalCards} / ${totalCards}`;
  } else {
    turnLabel.textContent = totalCards ? `Turn: ${currentCardIndex + 1} / ${totalCards}` : "Turn: 0 / 0";
  }
}
// ----------------- Message Processing -----------------
function processMessage(messageEl) {
  if (messageEl.dataset.processed) return;
  const textEl = messageEl.querySelector('.message-text');
  // Only add "Read more" toggle for user messages if text is long.
  if (messageEl.classList.contains('user') && textEl.scrollHeight > 80) {
    const toggleBtn = document.createElement('button');
    toggleBtn.className = 'toggle-btn';
    toggleBtn.textContent = 'Read more';
    toggleBtn.addEventListener('click', function() {
      if (messageEl.classList.contains('expanded')) {
        messageEl.classList.remove('expanded');
        toggleBtn.textContent = 'Read more';
      } else {
        messageEl.classList.add('expanded');
        toggleBtn.textContent = 'Read less';
      }
    });
    messageEl.appendChild(toggleBtn);
  }
  messageEl.dataset.processed = 'true';
}
function processMessagesInContainer(container) {
  container.querySelectorAll('.message').forEach(processMessage);
}
// ----------------- Adding Conversation & Stream API Call -----------------
async function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      // Get the base64 string (remove the data URL prefix)
      const base64 = reader.result.split(',')[1];
      resolve({
        name: file.name,
        path: file.webkitRelativePath || file.path || file.name,
        size: file.size,
        type: file.type,
        content: base64
      });
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

const attachedFiles = [];
async function addConversation(userText) {
  if (userText.trim() === '' && attachedFiles.length === 0) return;

  // Store message with attachments
  sessions[currentSessionIndex].messages.push({
    userText,
    aiResponse: "",
    attachments: await Promise.all(attachedFiles.map(fileToBase64)),
    model: sessions[currentSessionIndex].settings.model,
    sessionId: sessions[currentSessionIndex].id
  });

  // Clear attachments after sending
  clearFileAttachments();
  renderCurrentSession();

  const conversation = [];
  sessions[currentSessionIndex].messages.forEach(msg => {
    conversation.push({ role: "user", content: msg.userText, attachments: msg.attachments, sessionId: msg.sessionId });
    if (msg.aiResponse) {
      conversation.push({ role: "assistant", content: msg.aiResponse, sessionId: msg.sessionId });
    }
  });

  try {
    const aiResponse = await callLLMStream(conversation);
    sessions[currentSessionIndex].messages[sessions[currentSessionIndex].messages.length - 1].aiResponse = aiResponse;
    renderCurrentSession();
  } catch (err) {
    console.error(err);
    sessions[currentSessionIndex].messages[sessions[currentSessionIndex].messages.length - 1].aiResponse = "Error: " + err.message;
    renderCurrentSession();
  }
}

function clearFileAttachments() {
  attachedFiles.length = 0;
  updateFileAttachments();
}
// ----------------- Auto-resize Textarea -----------------
const chatInput = document.getElementById('chatInput');
chatInput.addEventListener('input', function() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight + 'px';
});
function resetTextarea() {
  chatInput.style.height = '36px';
}
// ----------------- Send Message -----------------
const sendBtn = document.getElementById('sendBtn');
sendBtn.addEventListener('click', async () => {
  const text = chatInput.value;
  if (text.trim() !== '') {
    await addConversation(text);
    chatInput.value = '';
    resetTextarea();
  }
});
chatInput.addEventListener('keydown', function(e) {
  if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
    e.preventDefault();
    sendBtn.click();
  }
});
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
prevBtn.addEventListener('click', () => {
  if (currentCardIndex > 0) {
    currentCardIndex--;
    updateCarousel();
  }
});
nextBtn.addEventListener('click', () => {
  const cards = document.querySelectorAll('.card');
  if (currentCardIndex < cards.length - 1) {
    currentCardIndex++;
    updateCarousel();
  }
});
// ----------------- File Attachment Handling -----------------
const attachBtn = document.getElementById('attachBtn');
const fileInput = document.getElementById('fileInput');
const fileAttachments = document.getElementById('fileAttachments');
attachBtn.addEventListener('click', () => {
  fileInput.click();
});
fileInput.addEventListener('change', () => {
  for (const file of fileInput.files) {
    attachedFiles.push(file);
    // Display the file path in the console
  }
  fileInput.value = "";
  updateFileAttachments();
});

function updateFileAttachments() {
  fileAttachments.innerHTML = "";
  attachedFiles.forEach((file, index) => {
    const fileDiv = document.createElement("div");
    fileDiv.className = "file-item";
    fileDiv.innerHTML = `<span>${file.name}</span> <button data-index="${index}">&times;</button>`;
    fileAttachments.appendChild(fileDiv);
  });
  document.querySelectorAll(".file-item button").forEach(btn => {
    btn.addEventListener("click", (e) => {
      const idx = e.target.getAttribute("data-index");
      attachedFiles.splice(idx, 1);
      updateFileAttachments();
    });
  });
}
// ----------------- Summary Overlay -----------------
const summaryOverlay = document.getElementById('summaryOverlay');
const closeSummaryBtn = document.getElementById('closeSummaryBtn');
const summaryContent = document.getElementById('summaryContent');
const downloadSummaryBtn = document.getElementById('downloadSummary');
closeSummaryBtn.addEventListener('click', () => {
  summaryOverlay.classList.remove('active');
});
downloadSummaryBtn.addEventListener('click', () => {
  const blob = new Blob([sessions[currentSessionIndex].summary], { type: "text/markdown" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "summary.md";
  a.click();
  URL.revokeObjectURL(url);
});
// ----------------- Settings Overlay -----------------
const settingsOverlay = document.getElementById('settingsOverlay');
const closeSettingsBtn = document.getElementById('closeSettingsBtn');
const temperatureInput = document.getElementById('temperature');
const temperatureValue = document.getElementById('temperatureValue');
const maxTokensInput = document.getElementById('maxTokens');
const personaSelect = document.getElementById('persona');
const saveSettingsBtn = document.getElementById('saveSettings');
closeSettingsBtn.addEventListener('click', () => {
  settingsOverlay.classList.remove('active');
});
temperatureInput.addEventListener('input', () => {
  temperatureValue.textContent = temperatureInput.value;
});
saveSettingsBtn.addEventListener('click', () => {
  sessions[currentSessionIndex].settings = {
    temperature: parseFloat(temperatureInput.value),
    maxTokens: parseInt(maxTokensInput.value),
    persona: personaSelect.value
  };
  console.log('Session settings saved:', sessions[currentSessionIndex].settings);
  settingsOverlay.classList.remove('active');
});
// ----------------- Title Editing -----------------
const editTitleBtn = document.getElementById('editTitleBtn');
editTitleBtn.addEventListener('click', () => {
  const currentTitle = sessions[currentSessionIndex].title;
  const newTitle = prompt("Enter new chat title:", currentTitle);
  if (newTitle !== null && newTitle.trim() !== "") {
    sessions[currentSessionIndex].title = newTitle.trim();
    document.getElementById('chatTitle').textContent = newTitle.trim();
  }
});
// ----------------- Auto-Dismiss Overlays -----------------
document.addEventListener('click', (e) => {
  if (summaryOverlay.classList.contains('active') && !summaryOverlay.contains(e.target)) {
    summaryOverlay.classList.remove('active');
  }
  if (settingsOverlay.classList.contains('active') && !settingsOverlay.contains(e.target)) {
    settingsOverlay.classList.remove('active');
  }
});
// ----------------- Global Keyboard Navigation -----------------
document.addEventListener('keydown', (e) => {
  if (document.activeElement !== chatInput) {
    if (e.key === 'ArrowLeft' && currentCardIndex > 0) {
      currentCardIndex--;
      updateCarousel();
    } else if (e.key === 'ArrowRight') {
      const cards = document.querySelectorAll('.card');
      if (currentCardIndex < cards.length - 1) {
        currentCardIndex++;
        updateCarousel();
      }
    }
  }
});
// ----------------- Hamburger Toggle -----------------
const hamburgerBtn = document.getElementById('hamburgerBtn');
const navBar = document.getElementById('navBar');
hamburgerBtn.addEventListener('click', (e) => {
  e.stopPropagation();
  navBar.classList.toggle('hidden');
  updateHamburgerPosition();
});

// ----------------- Custom Button Event Listeners -----------------
const customBtn1 = document.getElementById('customBtn1');
const customBtn2 = document.getElementById('customBtn2');

customBtn1.addEventListener('click', (e) => {
  e.stopPropagation();
  // Open the summary overlay for the current session
  document.getElementById('summaryContent').innerHTML = marked.parse(sessions[currentSessionIndex].summary);
  summaryOverlay.classList.add('active');
  settingsOverlay.classList.remove('active');
});

customBtn2.addEventListener('click', (e) => {
  e.stopPropagation();
  // Open the settings overlay for the current session and fill in the fields
  const settings = sessions[currentSessionIndex].settings;
  temperatureInput.value = settings.temperature;
  temperatureValue.textContent = settings.temperature;
  maxTokensInput.value = settings.maxTokens;
  personaSelect.value = settings.persona;
  settingsOverlay.classList.add('active');
  summaryOverlay.classList.remove('active');
});

// Get reference to the new select element
const modelSelect = document.getElementById('modelSelect');

function openSettingsForCurrentSession() {
  const settings = sessions[currentSessionIndex].settings;
  // Existing lines for temperature, maxTokens, persona...
  modelSelect.value = settings.model; // Populate the dropdown with the current model
}

// When opening the settings overlay:
customBtn2.addEventListener('click', (e) => {
  e.stopPropagation();
  // ...
  openSettingsForCurrentSession(); // load session settings into the UI
  settingsOverlay.classList.add('active');
  summaryOverlay.classList.remove('active');
});

// Saving:
saveSettingsBtn.addEventListener('click', () => {
  const sessionSettings = sessions[currentSessionIndex].settings;
  // Existing lines for temperature, maxTokens, persona...
  sessionSettings.model = modelSelect.value; // Save the selected model

  console.log('Session settings saved:', sessions[currentSessionIndex].settings);
  settingsOverlay.classList.remove('active');
});

async function callLLMStream(conversation) {
  const session = sessions[currentSessionIndex];
  const { model, temperature, maxTokens } = session.settings;

  if (model.startsWith("gpt-4o")) {
    // Call OpenAI endpoint
    return callOpenAIStream(session.id, conversation, model, temperature, maxTokens);
  } else if (model.startsWith("claude")) {
    // Call Anthropic endpoint
    return callAnthropicStream(session.id, conversation, model, temperature, maxTokens);
  } else if (model.startsWith("gemini")) {
    // Call Google endpoint
    return callGoogleStream(session.id, conversation, model, temperature, maxTokens);
  } else if (model.startsWith("huggingface")) {
    // Call Hugging Face endpoint
    return callHuggingFaceStream(session.id, conversation, model.replace("huggingface/", ""), temperature, maxTokens);
  } else {
    throw new Error("Unsupported model: " + model);
  }
}

async function callOpenAIStream(sessionId, conversation) {
  const response = await fetch("http://127.0.0.1:8000/openai_stream", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Session-ID": sessionId
      // Remove the Authorization header since the Python backend handles the API key.
    },
    body: JSON.stringify({
      conversation: conversation,
      temperature: sessions[currentSessionIndex].settings.temperature,
      max_tokens: sessions[currentSessionIndex].settings.maxTokens,
      model: MODEL_NAME,
    })
  });
  const reader = response.body.getReader();
  const decoder = new TextDecoder("utf-8");
  let done = false;
  let aiMessage = "";

  updateLastMessage(aiMessage, true);
  while (!done) {
    const { value, done: doneReading } = await reader.read();
    done = doneReading;
    const chunk = decoder.decode(value);
    const lines = chunk.split("\n").filter(line => line.trim().startsWith("data:"));
    for (const line of lines) {
      const dataStr = line.replace(/^data:\s*/, "");
      if (dataStr === "[DONE]") {
        done = true;
        break;
      }
      try {
        // Parse the JSON returned by the Python backend.
        const parsed = JSON.parse(dataStr);
        // Assuming the payload structure is the same as OpenAI's response.
        const delta = parsed.choices[0].delta.content;
        if (delta) {
          aiMessage += delta;
          updateLastMessage(aiMessage, true);
        }
      } catch (err) {
        console.error("Stream parsing error:", err);
      }
    }
  }
  updateLastMessage(aiMessage, false);
  return aiMessage;
}


async function callAnthropicStream(sessionId, conversation, model, temperature, maxTokens) {
  model = model.toLowerCase().replace(/\s+/g, '-').replace(/\./g, '-');
  console.log(`Calling Anthropic API with model: ${model}`);
  
  const response = await fetch("http://127.0.0.1:8000/anthropic_stream", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Session-ID": sessionId
    },
    body: JSON.stringify({
      messages: conversation,
      temperature: temperature,
      max_tokens: maxTokens,
      model: model + "-latest",
    })
  });
  
  const reader = response.body.getReader();
  const decoder = new TextDecoder("utf-8");
  let done = false;
  let aiMessage = "";
  
  updateLastMessage(aiMessage, true);
  while (!done) {
    const { value, done: doneReading } = await reader.read();
    done = doneReading;
    const chunk = decoder.decode(value);
    const lines = chunk.split("\n").filter(line => line.trim().startsWith("data:"));
    
    for (const line of lines) {
      const dataStr = line.replace(/^data:\s*/, "");
      if (dataStr === "[DONE]") {
        done = true;
        break;
      }
      
      try {
        const parsed = JSON.parse(dataStr);
        const delta = parsed.choices[0].delta.content;
        if (delta) {
          aiMessage += delta;
          updateLastMessage(aiMessage, true);
        }
      } catch (err) {
        console.error("Anthropic stream parsing error:", err);
      }
    }
  }
  updateLastMessage(aiMessage, false);
  return aiMessage;

}

async function callGoogleStream(sessionId, conversation, model, temperature, maxTokens) {
  // Convert conversation messages to Gemini's "contents" format.
  model = model.toLowerCase().replace(/\s+/g, '-');
  console.log(model);  
  const response = await fetch("http://127.0.0.1:8000/gemini_stream", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Session-ID": sessionId
    },
    body: JSON.stringify({
      messages: conversation,
      temperature: temperature,
      max_tokens: maxTokens,
      model: model,
    })
  });
  
  const reader = response.body.getReader();
  const decoder = new TextDecoder("utf-8");
  let done = false;
  let aiMessage = "";

  updateLastMessage(aiMessage, true);
  while (!done) {
    const { value, done: doneReading } = await reader.read();
    done = doneReading;
    const chunk = decoder.decode(value);
    const lines = chunk.split("\n").filter(line => line.trim().startsWith("data:"));
    
    for (const line of lines) {
      const dataStr = line.replace(/^data:\s*/, "");
      if (dataStr === "[DONE]") {
        done = true;
        break;
      }
      
      try {
        const parsed = JSON.parse(dataStr);
        const delta = parsed.choices[0].delta.content;
        if (delta) {
          aiMessage += delta;
          updateLastMessage(aiMessage, true);
        }
      } catch (err) {
        console.error("Gemini stream parsing error:", err);
      }
    }
  }
  updateLastMessage(aiMessage, false);
  return aiMessage;
}

async function callHuggingFaceStream(sessionId, conversation, model, temperature, maxTokens) {
  console.log(`Calling Hugging Face API with model: ${model}`);
  const response = await fetch("http://127.0.0.1:8000/huggingface_stream", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Session-ID": sessionId
    },
    body: JSON.stringify({
      messages: conversation,
      temperature: temperature,
      max_tokens: maxTokens,
      model: model,
    })
  }); 

  const reader = response.body.getReader();
  const decoder = new TextDecoder("utf-8");
  let done = false;
  let aiMessage = ""; 

  updateLastMessage(aiMessage, true);
  while (!done) {
    const { value, done: doneReading } = await reader.read();
    done = doneReading;
    const chunk = decoder.decode(value);
    const lines = chunk.split("\n").filter(line => line.trim().startsWith("data:"));  

    for (const line of lines) {
      const dataStr = line.replace(/^data:\s*/, "");
      if (dataStr === "[DONE]") {
        done = true;
        break;
      } 

      try {
        const parsed = JSON.parse(dataStr);
        const delta = parsed.choices[0].delta.content;
        if (delta) {
          aiMessage += delta;
          updateLastMessage(aiMessage, true);
        }
      } catch (err) {
        console.error("Hugging Face stream parsing error:", err);
      }
    }
  }
  updateLastMessage(aiMessage, false);
  return aiMessage;
}

// ----------------- Initialization -----------------
initSessions();
updateHamburgerPosition();