File size: 26,054 Bytes
7ddf739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
742
743
744
745
746
747
748
749
750
751
752
const state = {
  sessionId: null,
  sessions: [],
  messages: [],
  reminders: [],
  editingReminderId: null,
};

const DEFAULT_API_BASE = "http://127.0.0.1:8000";
let apiBase = window.location.protocol === "file:" ? DEFAULT_API_BASE : "";

const WELCOME_HTML = `
  <div class="welcome-icon">AI</div>
  <div>
    <div class="welcome-title">Your AI Workspace</div>
    <div class="welcome-sub">Manage tasks, set reminders, capture notes, and search past chats from one clean workspace.</div>
  </div>
  <div class="quick-prompts">
    <button class="quick-prompt-card" data-prompt="show my tasks" data-send="true"><strong>View Tasks</strong><span>See every pending task</span></button>
    <button class="quick-prompt-card" data-prompt="show reminders" data-send="true"><strong>Reminders</strong><span>Check upcoming alerts</span></button>
    <button class="quick-prompt-card" data-prompt="daily summary" data-send="true"><strong>Daily Summary</strong><span>Get a full workspace overview</span></button>
    <button class="quick-prompt-card" data-prompt="add task " data-send="false"><strong>Add Task</strong><span>Create a new to-do</span></button>
  </div>
`;

const chatMessages = document.getElementById("chatMessages");
const chatForm = document.getElementById("chatForm");
const messageInput = document.getElementById("messageInput");
const sessionList = document.getElementById("sessionList");
const mobileSessionList = document.getElementById("mobileSessionList");
const summaryCards = document.getElementById("summaryCards");
const searchInput = document.getElementById("searchInput");
const searchResults = document.getElementById("searchResults");
const helperPanel = document.getElementById("helperPanel");
const sideHelperContent = document.getElementById("sideHelperContent");
const messageTemplate = document.getElementById("messageTemplate");
const pageOverlay = document.getElementById("pageOverlay");

const reminderModal = document.getElementById("reminderModal");
const reminderForm = document.getElementById("reminderForm");
const reminderTitleInput = document.getElementById("reminderTitle");
const reminderNoteInput = document.getElementById("reminderNote");
const reminderDateInput = document.getElementById("reminderDate");
const reminderTimeInput = document.getElementById("reminderTime");
const reminderFormMessage = document.getElementById("reminderFormMessage");
const reminderList = document.getElementById("reminderList");
const saveReminderBtn = document.getElementById("saveReminderBtn");
const reminderModalTitle = document.getElementById("reminderModalTitle");

function updateOverlay() {
  const open = document.body.classList.contains("left-drawer-open")
    || document.body.classList.contains("right-drawer-open");
  pageOverlay.classList.toggle("hidden", !open);
}

function openDrawer(side) {
  document.body.classList.add(`${side}-drawer-open`);
  updateOverlay();
}

function closeDrawers() {
  document.body.classList.remove("left-drawer-open", "right-drawer-open");
  updateOverlay();
}

document.getElementById("openLeftDrawerBtn")?.addEventListener("click", () => openDrawer("left"));
document.getElementById("closeLeftDrawerBtn")?.addEventListener("click", closeDrawers);
document.getElementById("openRightDrawerBtn")?.addEventListener("click", () => openDrawer("right"));
document.getElementById("closeRightDrawerBtn")?.addEventListener("click", closeDrawers);
pageOverlay?.addEventListener("click", closeDrawers);

const tabDefs = { actions: "tab-actions", guide: "tab-guide", focus: "tab-focus" };

function setActiveTab(tabKey) {
  document.querySelectorAll(".panel-tab").forEach(button => {
    button.classList.toggle("active", button.dataset.tab === tabKey);
  });
  Object.entries(tabDefs).forEach(([key, id]) => {
    const element = document.getElementById(id);
    if (!element) return;
    element.style.display = key === tabKey ? (key === "actions" ? "grid" : "flex") : "none";
  });
}

document.querySelectorAll(".panel-tab").forEach(button => {
  button.addEventListener("click", () => setActiveTab(button.dataset.tab));
});

setActiveTab("actions");

function escapeHtml(text) {
  return String(text)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;");
}

function renderMarkdown(text) {
  let html = escapeHtml(text);
  html = html.replace(/^### (.*)$/gm, "<h3>$1</h3>");
  html = html.replace(/^## (.*)$/gm, "<h2>$1</h2>");
  html = html.replace(/^# (.*)$/gm, "<h1>$1</h1>");
  html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
  html = html.replace(/\*(.+?)\*/g, "<em>$1</em>");
  html = html.replace(/`([^`]+)`/g, "<code>$1</code>");
  html = html.replace(/^- (.*)$/gm, "<li>$1</li>");
  html = html.replace(/(<li>.*<\/li>)/gs, "<ul>$1</ul>");
  html = html.replace(/\n/g, "<br>");
  return html;
}

async function rawRequest(base, url, options = {}) {
  const mergedOptions = { ...options };
  const method = (mergedOptions.method || "GET").toUpperCase();
  const headers = new Headers(mergedOptions.headers || {});

  if (mergedOptions.body && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  if (!mergedOptions.body && method === "GET" && headers.has("Content-Type")) {
    headers.delete("Content-Type");
  }

  mergedOptions.headers = headers;
  return fetch(`${base}${url}`, mergedOptions);
}

async function resolveApiBase() {
  const candidates = [];
  if (window.location.protocol !== "file:") {
    candidates.push("");
  }
  if (!candidates.includes(DEFAULT_API_BASE)) {
    candidates.push(DEFAULT_API_BASE);
  }

  for (const candidate of candidates) {
    try {
      const response = await rawRequest(candidate, "/health");
      if (response.ok) {
        apiBase = candidate;
        return;
      }
    } catch (error) {
      continue;
    }
  }

  throw new Error(`Could not reach the backend. Start the app with run.bat and open ${DEFAULT_API_BASE} .`);
}

async function api(url, options = {}) {
  if (apiBase === "" && window.location.protocol !== "file:" && window.location.port !== "8000") {
    await resolveApiBase();
  }

  let response;
  try {
    response = await rawRequest(apiBase, url, options);
  } catch (error) {
    if (apiBase !== DEFAULT_API_BASE) {
      apiBase = DEFAULT_API_BASE;
      response = await rawRequest(apiBase, url, options).catch(() => null);
    }
    if (!response) {
      throw new Error(`Could not reach the backend. Start the app with run.bat and open ${DEFAULT_API_BASE} .`);
    }
  }

  if (!response.ok && apiBase !== DEFAULT_API_BASE && window.location.port !== "8000") {
    try {
      const fallback = await rawRequest(DEFAULT_API_BASE, url, options);
      if (fallback.ok) {
        apiBase = DEFAULT_API_BASE;
        return fallback.json();
      }
    } catch (error) {
      // Ignore and surface the original response below.
    }
  }

  if (!response.ok) {
    const error = await response.json().catch(() => null);
    const detail = error?.detail || `${response.status} ${response.statusText}` || "Request failed";
    throw new Error(detail);
  }
  return response.json();
}

function autoResize() {
  messageInput.style.height = "auto";
  messageInput.style.height = `${Math.min(messageInput.scrollHeight, 120)}px`;
}

function scrollToBottom() {
  chatMessages.scrollTop = chatMessages.scrollHeight;
}

function setHelperContent(title, content) {
  helperPanel.classList.remove("hidden");
  helperPanel.innerHTML = `<strong style="color:var(--text-accent);font-size:12px;">${escapeHtml(title)}</strong><pre style="margin-top:6px;">${escapeHtml(content)}</pre>`;
  if (sideHelperContent) {
    sideHelperContent.textContent = `${title}\n\n${content}`;
  }
  setActiveTab("focus");
}

function placePrompt(prompt, autoSend = false) {
  messageInput.value = prompt;
  autoResize();
  messageInput.focus();
  messageInput.setSelectionRange(prompt.length, prompt.length);
  if (autoSend && prompt.trim()) chatForm.requestSubmit();
}

function ensureWelcomeState() {
  const existing = document.getElementById("welcomeState");
  if (existing) return existing;
  const node = document.createElement("div");
  node.id = "welcomeState";
  node.className = "welcome-state";
  node.innerHTML = WELCOME_HTML;
  chatMessages.appendChild(node);
  bindPromptButtons();
  return node;
}

function addMessage(message, saveable = true) {
  const currentWelcome = document.getElementById("welcomeState");
  if (currentWelcome) currentWelcome.style.display = "none";

  const node = messageTemplate.content.firstElementChild.cloneNode(true);
  node.classList.add(message.role);

  const avatar = node.querySelector(".msg-avatar");
  avatar.classList.add(message.role === "user" ? "user" : "ai");
  avatar.textContent = message.role === "user" ? "U" : "AI";

  const bubble = node.querySelector(".bubble");
  bubble.innerHTML = renderMarkdown(message.content);

  const actions = node.querySelector(".message-actions");
  if (message.role === "assistant") {
    const copyBtn = document.createElement("button");
    copyBtn.className = "msg-action-btn";
    copyBtn.innerHTML = `<svg width="11" height="11" viewBox="0 0 20 20" fill="currentColor"><path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"/><path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"/></svg> Copy`;
    copyBtn.addEventListener("click", async () => {
      await navigator.clipboard.writeText(message.content);
      copyBtn.textContent = "Saved";
      setTimeout(() => {
        copyBtn.innerHTML = `<svg width="11" height="11" viewBox="0 0 20 20" fill="currentColor"><path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"/><path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"/></svg> Copy`;
      }, 1500);
    });
    actions.appendChild(copyBtn);
  }

  if (saveable && Number.isInteger(message.id) && state.sessionId) {
    const saveBtn = document.createElement("button");
    saveBtn.className = "msg-action-btn";
    saveBtn.innerHTML = `<svg width="11" height="11" viewBox="0 0 20 20" fill="currentColor"><path d="M5 4a2 2 0 012-2h6a2 2 0 012 2v14l-5-2.5L5 18V4z"/></svg> Save`;
    saveBtn.addEventListener("click", async () => {
      await api(`/api/history/sessions/${state.sessionId}/messages/${message.id}/save`, { method: "POST" });
      saveBtn.textContent = "Saved";
    });
    actions.appendChild(saveBtn);
  }

  chatMessages.appendChild(node);
  scrollToBottom();
}

function renderMessages(messages) {
  chatMessages.innerHTML = "";
  if (!messages.length) {
    ensureWelcomeState().style.display = "flex";
    return;
  }
  messages.forEach(message => addMessage(message));
}

function typingBubble() {
  const currentWelcome = document.getElementById("welcomeState");
  if (currentWelcome) currentWelcome.style.display = "none";

  const node = messageTemplate.content.firstElementChild.cloneNode(true);
  node.classList.add("assistant", "typing");

  const avatar = node.querySelector(".msg-avatar");
  avatar.classList.add("ai");
  avatar.textContent = "AI";

  const bubble = node.querySelector(".bubble");
  bubble.innerHTML = `<div class="typing-dots"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div>`;

  chatMessages.appendChild(node);
  scrollToBottom();
  return node;
}

function renderSessions() {
  [sessionList, mobileSessionList].forEach(list => {
    if (!list) return;
    list.innerHTML = "";
    state.sessions.forEach(session => {
      const item = document.createElement("button");
      item.className = `session-item${session.id === state.sessionId ? " active" : ""}`;
      item.innerHTML = `<strong>${escapeHtml(session.title)}</strong><small>${new Date(session.updated_at).toLocaleDateString()} | ${session.message_count} msgs</small>`;
      item.addEventListener("click", () => {
        loadSession(session.id);
        closeDrawers();
      });
      list.appendChild(item);
    });
  });
}

async function loadSessions() {
  state.sessions = await api("/api/history/sessions");
  renderSessions();
}

async function loadSession(sessionId) {
  try {
    const session = await api(`/api/history/sessions/${sessionId}`);
    state.sessionId = session.id;
    state.messages = session.messages || [];
    renderMessages(state.messages);
    renderSessions();
  } catch (error) {
    if (!String(error.message).includes("Session not found")) throw error;
    await loadSessions();
    if (state.sessions.length) {
      await loadSession(state.sessions[0].id);
      return;
    }
    state.sessionId = null;
    state.messages = [];
    renderMessages([]);
  }
}

async function createNewSession() {
  const session = await api("/api/history/sessions", { method: "POST" });
  state.sessionId = session.id;
  state.messages = [];
  renderMessages([]);
  await loadSessions();
}

async function refreshSummary() {
  const summary = await api("/api/history/summary");

  summaryCards.innerHTML = `
    <div class="summary-card"><strong>${summary.pending_tasks}</strong><small>Pending tasks</small></div>
    <div class="summary-card"><strong>${summary.active_reminders}</strong><small>Reminders</small></div>
    <div class="summary-card"><strong>${summary.notes}</strong><small>Notes</small></div>
    <div class="summary-card"><strong>${summary.due_reminders}</strong><small>Due now</small></div>
  `;

  const setText = (id, value) => {
    const element = document.getElementById(id);
    if (element) element.textContent = value;
  };

  setText("statTasks", summary.pending_tasks);
  setText("statReminders", summary.active_reminders);
  setText("statNotes", summary.notes);
  setText("statDue", summary.due_reminders);

  const setBadge = (id, value) => {
    const element = document.getElementById(id);
    if (!element) return;
    element.textContent = value;
    element.style.display = value > 0 ? "" : "none";
  };

  setBadge("taskBadge", summary.pending_tasks);
  setBadge("reminderBadge", summary.active_reminders);
  setBadge("notesBadge", summary.notes);
  setBadge("mobileTaskBadge", summary.pending_tasks);
}

function showReminderMessage(message, type = "success") {
  reminderFormMessage.textContent = message;
  reminderFormMessage.className = `form-status ${type}`;
}

function clearReminderMessage() {
  reminderFormMessage.textContent = "";
  reminderFormMessage.className = "form-status hidden";
}

function resetReminderForm() {
  state.editingReminderId = null;
  reminderForm.reset();
  reminderModalTitle.textContent = "Create reminder";
  saveReminderBtn.textContent = "Save Reminder";
  clearReminderMessage();
}

function populateReminderForm(reminder) {
  state.editingReminderId = reminder.id;
  reminderTitleInput.value = reminder.title || "";
  reminderNoteInput.value = reminder.note || "";
  reminderDateInput.value = reminder.date || "";
  reminderTimeInput.value = reminder.time || "";
  reminderModalTitle.textContent = "Edit reminder";
  saveReminderBtn.textContent = "Update Reminder";
  clearReminderMessage();
}

function openReminderModal(reminder = null) {
  if (reminder) {
    populateReminderForm(reminder);
  } else if (!state.editingReminderId) {
    resetReminderForm();
  }
  reminderModal.classList.remove("hidden");
  reminderModal.setAttribute("aria-hidden", "false");
  document.body.style.overflow = "hidden";
  reminderTitleInput.focus();
}

function closeReminderModal() {
  reminderModal.classList.add("hidden");
  reminderModal.setAttribute("aria-hidden", "true");
  document.body.style.overflow = "";
  resetReminderForm();
}

function formatReminderMeta(reminder) {
  return `${reminder.display_date} at ${reminder.display_time}`;
}

function renderReminderList() {
  if (!state.reminders.length) {
    reminderList.innerHTML = `<div class="reminder-empty">No reminders yet. Add your first reminder above.</div>`;
    return;
  }

  reminderList.innerHTML = state.reminders.map(reminder => `
    <article class="reminder-item" data-reminder-id="${reminder.id}">
      <div class="reminder-main">
        <div class="reminder-topline">
          <div class="reminder-title">${escapeHtml(reminder.title)}</div>
          <span class="status-pill ${escapeHtml(reminder.status)}">${escapeHtml(reminder.status)}</span>
        </div>
        ${reminder.note ? `<div class="reminder-note">${escapeHtml(reminder.note)}</div>` : ""}
        <div class="reminder-meta">
          <span>${escapeHtml(formatReminderMeta(reminder))}</span>
          <span>${reminder.completed ? "Completed" : "Active"}</span>
        </div>
      </div>
      <div class="reminder-actions">
        ${reminder.completed ? "" : `<button type="button" class="action-chip" data-action="done">Mark as Done</button>`}
        <button type="button" class="action-chip" data-action="edit">Edit</button>
        ${reminder.completed ? "" : `<button type="button" class="action-chip" data-action="postpone">Postpone</button>`}
        <button type="button" class="action-chip danger" data-action="delete">Delete</button>
      </div>
    </article>
  `).join("");
}

async function loadReminders() {
  state.reminders = await api("/api/reminders");
  renderReminderList();
}

async function saveReminder(event) {
  event.preventDefault();
  clearReminderMessage();

  const title = reminderTitleInput.value.trim();
  const note = reminderNoteInput.value.trim();
  const date = reminderDateInput.value;
  const time = reminderTimeInput.value;

  if (!title) {
    showReminderMessage("Task title is required.", "error");
    return;
  }
  if (!date || !time) {
    showReminderMessage("Please select both date and time.", "error");
    return;
  }

  saveReminderBtn.disabled = true;
  saveReminderBtn.textContent = state.editingReminderId ? "Updating..." : "Saving...";

  try {
    const payload = { title, note, date, time };
    if (state.editingReminderId) {
      await api(`/api/reminders/${state.editingReminderId}`, {
        method: "PUT",
        body: JSON.stringify(payload),
      });
      showReminderMessage("Reminder updated successfully", "success");
    } else {
      await api("/api/reminders", {
        method: "POST",
        body: JSON.stringify(payload),
      });
      showReminderMessage("Reminder added successfully", "success");
    }

    await loadReminders();
    await refreshSummary();
    if (!state.editingReminderId) {
      reminderForm.reset();
    } else {
      state.editingReminderId = null;
      reminderModalTitle.textContent = "Create reminder";
      saveReminderBtn.textContent = "Save Reminder";
    }
  } catch (error) {
    showReminderMessage(error.message, "error");
  } finally {
    saveReminderBtn.disabled = false;
    saveReminderBtn.textContent = state.editingReminderId ? "Update Reminder" : "Save Reminder";
  }
}

async function handleReminderAction(event) {
  const actionButton = event.target.closest("[data-action]");
  if (!actionButton) return;

  const reminderNode = actionButton.closest("[data-reminder-id]");
  if (!reminderNode) return;

  const reminderId = Number(reminderNode.dataset.reminderId);
  const reminder = state.reminders.find(item => item.id === reminderId);
  if (!reminder) return;

  try {
    if (actionButton.dataset.action === "edit") {
      openReminderModal(reminder);
      return;
    }

    if (actionButton.dataset.action === "done") {
      await api(`/api/reminders/${reminderId}/complete`, { method: "PATCH" });
      showReminderMessage("Reminder marked as done", "success");
    } else if (actionButton.dataset.action === "delete") {
      await api(`/api/reminders/${reminderId}`, { method: "DELETE" });
      showReminderMessage("Reminder deleted successfully", "success");
    } else if (actionButton.dataset.action === "postpone") {
      await api(`/api/reminders/${reminderId}/postpone`, { method: "PATCH" });
      showReminderMessage("Reminder postponed by 1 day", "success");
    }

    await loadReminders();
    await refreshSummary();
  } catch (error) {
    showReminderMessage(error.message, "error");
  }
}

async function submitMessage(event) {
  event.preventDefault();
  const text = messageInput.value.trim();
  if (!text) return;

  if (!state.sessionId) await createNewSession();

  addMessage({ role: "user", content: text }, false);
  messageInput.value = "";
  autoResize();

  const loader = typingBubble();
  try {
    const response = await api("/api/chat", {
      method: "POST",
      body: JSON.stringify({ session_id: state.sessionId, message: text }),
    });
    loader.remove();
    state.sessionId = response.session_id;
    await loadSession(state.sessionId);
    await loadSessions();
    await loadReminders();
    await refreshSummary();
  } catch (error) {
    loader.remove();
    addMessage({ role: "assistant", content: `[!] ${error.message}` }, false);
  }
}

async function clearCurrentChat() {
  if (!state.sessionId) {
    renderMessages([]);
    return;
  }
  await api(`/api/history/sessions/${state.sessionId}`, { method: "DELETE" });
  state.sessionId = null;
  state.messages = [];
  renderMessages([]);
  await loadSessions();
  await refreshSummary();
}

async function searchChats() {
  const query = searchInput.value.trim();
  if (!query) {
    searchResults.style.display = "none";
    searchResults.innerHTML = "";
    return;
  }

  const results = await api(`/api/history/search?query=${encodeURIComponent(query)}`);
  searchResults.style.display = "block";
  searchResults.innerHTML = results.length
    ? results.map(item => `
        <button class="search-item" type="button" data-session-id="${escapeHtml(item.session_id)}">
          <strong>${escapeHtml(item.session_title)}</strong>
          <small>${escapeHtml(item.role)}</small>
          <p>${escapeHtml(item.content.slice(0, 120))}</p>
        </button>`).join("")
    : `<div class="search-item"><small>No matches found.</small></div>`;

  searchResults.querySelectorAll("[data-session-id]").forEach(button => {
    button.addEventListener("click", async () => {
      await loadSession(button.dataset.sessionId);
      searchResults.style.display = "none";
    });
  });

  if (sideHelperContent) {
    sideHelperContent.textContent = results.length
      ? results.map(item => `${item.session_title}: ${item.content}`).join("\n\n")
      : "No matching chat history found.";
  }
}

document.addEventListener("click", event => {
  if (!searchInput.contains(event.target) && !searchResults.contains(event.target)) {
    searchResults.style.display = "none";
  }
});

async function showSavedMessages() {
  const saved = await api("/api/history/saved");
  if (!saved.length) {
    setHelperContent("Saved messages", "No saved messages yet.");
    return;
  }
  const content = saved.slice(0, 12).map(item => `[${item.role}] ${item.content}`).join("\n\n");
  setHelperContent("Saved messages", content);
}

function showCommands() {
  const content = [
    "add task complete DSA homework",
    "show my tasks",
    "complete task 2",
    "delete task 2",
    "remind me tomorrow 7 PM to revise CN",
    "show reminders",
    "add note remember to apply for internship",
    "save this as note",
    "show notes",
    "search chats internship",
    "daily summary",
  ].join("\n");
  setHelperContent("Example commands", content);
}

function bindPromptButtons() {
  document.querySelectorAll("[data-prompt]").forEach(button => {
    if (button.dataset.promptBound === "true") return;
    button.dataset.promptBound = "true";
    button.addEventListener("click", () => {
      const prompt = button.dataset.prompt || "";
      const sendSetting = button.dataset.send;
      const autoSend = sendSetting === "true" || (!prompt.endsWith(" ") && sendSetting !== "false");
      placePrompt(prompt, autoSend);
      closeDrawers();
    });
  });
}

document.addEventListener("keydown", event => {
  if (event.key === "Escape") {
    if (!reminderModal.classList.contains("hidden")) {
      closeReminderModal();
      return;
    }
    closeDrawers();
  }
});

messageInput.addEventListener("input", autoResize);
chatForm.addEventListener("submit", submitMessage);
reminderForm.addEventListener("submit", saveReminder);
reminderList.addEventListener("click", handleReminderAction);

document.getElementById("newChatBtn")?.addEventListener("click", createNewSession);
document.getElementById("mobileNewChatBtn")?.addEventListener("click", async () => {
  await createNewSession();
  closeDrawers();
});
document.getElementById("clearChatBtn")?.addEventListener("click", clearCurrentChat);
document.getElementById("refreshSummaryBtn")?.addEventListener("click", event => {
  event.stopPropagation();
  refreshSummary();
});
document.getElementById("showSavedBtn")?.addEventListener("click", showSavedMessages);
document.getElementById("showCommandsBtn")?.addEventListener("click", showCommands);

document.getElementById("openReminderModalBtn")?.addEventListener("click", async () => {
  await loadReminders();
  openReminderModal();
});
document.getElementById("closeReminderModalBtn")?.addEventListener("click", closeReminderModal);
document.getElementById("cancelReminderBtn")?.addEventListener("click", closeReminderModal);
reminderModal.querySelectorAll("[data-reminder-close]").forEach(node => {
  node.addEventListener("click", closeReminderModal);
});

searchInput.addEventListener("input", () => {
  if (!searchInput.value.trim()) {
    searchResults.style.display = "none";
    searchResults.innerHTML = "";
    return;
  }
  searchChats();
});

searchInput.addEventListener("keydown", event => {
  if (event.key === "Enter") {
    event.preventDefault();
    searchChats();
  }
});

async function bootstrap() {
  bindPromptButtons();
  ensureWelcomeState();
  autoResize();
  await resolveApiBase();
  await loadSessions();
  await loadReminders();
  await refreshSummary();
  if (state.sessions.length) {
    await loadSession(state.sessions[0].id);
  }
}

bootstrap().catch(error => {
  setHelperContent("Startup issue", error.message);
  ensureWelcomeState().style.display = "flex";
});