File size: 23,768 Bytes
9e7d4f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { state } from './state.js';
import * as api from './api.js';
import * as ui from './ui.js';
import * as audio from './audio.js';
import * as profiles from './profiles.js';
import * as session from './session.js';
import * as auth from './auth.js';

// DOM Elements specific to top-level app logic
const startButton = document.getElementById("startButton");
const voiceModeBtn = document.getElementById("voiceModeBtn");
const textModeBtn = document.getElementById("textModeBtn");
const voiceInput = document.getElementById("voiceInput");
const textInput = document.getElementById("textInput");
const chatInput = document.getElementById("chatInput");
const sendBtn = document.getElementById("sendBtn");
const micBtn = document.getElementById("micBtn");

/**
 * Binds all global events to the DOM (button clicks, form submits, keypresses).
 */
function bindEvents() {
  // Handle browser back/forward buttons
  window.addEventListener("popstate", (event) => {
    if (event.state && event.state.screen) {
      ui.switchScreen(event.state.screen, false);
    } else {
      const path = window.location.pathname;
      if (path === "/dashboard" || path === "/session") {
        if (!state.patientId) {
          profiles.fetchPatients();
        } else {
          ui.switchScreen(path === "/dashboard" ? "dashboardScreen" : "mainApp", false);
        }
      } else {
        ui.switchScreen("loadingScreen", false);
      }
    }
  });

  // Global Unauthorized Handler
  window.addEventListener("unauthorized", () => {
    ui.switchScreen("authScreen", false);
  });

  // --- Auth Events ---
  const loginFormContainer = document.getElementById("loginFormContainer");
  const signupFormContainer = document.getElementById("signupFormContainer");
  const forgotPwdFormContainer = document.getElementById("forgotPwdFormContainer");
  const otpStepContainer = document.getElementById("otpStepContainer");
  const newPwdStepContainer = document.getElementById("newPwdStepContainer");
  const signupOtpStepContainer = document.getElementById("signupOtpStepContainer");

  // Track verified OTP state in memory (not persisted — refresh = back to login)
  let _otpVerifiedEmail = null;

  function showAuthPanel(panelId) {
    // Only hide/show panels that exist
    const panels = [loginFormContainer, signupFormContainer, forgotPwdFormContainer, otpStepContainer, newPwdStepContainer, signupOtpStepContainer];
    panels.forEach(p => { 
      if(p) { 
        p.classList.add('hidden'); 
        p.classList.remove('block'); 
      } 
    });
    const target = document.getElementById(panelId);
    if (target) {
      target.classList.remove('hidden');
      target.classList.add('block');
    } else {
      console.error("Auth panel not found:", panelId);
    }
  }

  document.getElementById("showSignupBtn")?.addEventListener("click", () => showAuthPanel("signupFormContainer"));
  document.getElementById("showForgotPwdBtn")?.addEventListener("click", () => showAuthPanel("forgotPwdFormContainer"));
  document.getElementById("backToLoginBtn1")?.addEventListener("click", () => showAuthPanel("loginFormContainer"));
  document.getElementById("backToLoginBtn2")?.addEventListener("click", () => showAuthPanel("loginFormContainer"));
  document.getElementById("backToForgotBtn")?.addEventListener("click", () => showAuthPanel("forgotPwdFormContainer"));
  document.getElementById("backToSignupBtn")?.addEventListener("click", () => showAuthPanel("signupFormContainer"));

  // Populate Nationality Dropdown
  const countries = [
    "India", "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", 
    "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", 
    "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", 
    "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", 
    "Burundi", "Côte d'Ivoire", "Cabo Verde", "Cambodia", "Cameroon", "Canada", "Central African Republic", 
    "Chad", "Chile", "China", "Colombia", "Comoros", "Congo (Congo-Brazzaville)", "Costa Rica", 
    "Croatia", "Cuba", "Cyprus", "Czechia (Czech Republic)", "Democratic Republic of the Congo", 
    "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", 
    "Equatorial Guinea", "Eritrea", "Estonia", "Eswatini", "Ethiopia", "Fiji", "Finland", 
    "France", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada", 
    "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Holy See", "Honduras", 
    "Hungary", "Iceland", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", 
    "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos", 
    "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", 
    "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", 
    "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Morocco", 
    "Mozambique", "Myanmar (formerly Burma)", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", 
    "Nicaragua", "Niger", "Nigeria", "North Korea", "North Macedonia", "Norway", "Oman", "Pakistan", 
    "Palau", "Palestine State", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", 
    "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", 
    "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", 
    "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", 
    "Solomon Islands", "Somalia", "South Africa", "South Korea", "South Sudan", "Spain", "Sri Lanka", 
    "Sudan", "Suriname", "Sweden", "Switzerland", "Syria", "Tajikistan", "Tanzania", "Thailand", 
    "Timor-Leste", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", 
    "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", 
    "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe"
  ];
  
  const signupNationality = document.getElementById("signupNationality");
  const nationalityDropdown = document.getElementById("nationalityDropdown");
  
  if (signupNationality && nationalityDropdown) {
    function renderCountries(filterText = "") {
      nationalityDropdown.innerHTML = "";
      const filtered = countries.filter(c => c.toLowerCase().includes(filterText.toLowerCase()));
      filtered.forEach(country => {
        const div = document.createElement("div");
        div.className = "p-2 hover:bg-moss/20 cursor-pointer text-sm text-ink";
        div.textContent = country;
        div.onmousedown = (e) => {
          e.preventDefault(); // prevent blur
          signupNationality.value = country;
          nationalityDropdown.classList.add("hidden");
        };
        nationalityDropdown.appendChild(div);
      });
      if (filtered.length === 0) {
        const div = document.createElement("div");
        div.className = "p-2 text-sm text-clay italic";
        div.textContent = "No matches";
        nationalityDropdown.appendChild(div);
      }
    }

    signupNationality.addEventListener("focus", () => {
      renderCountries(signupNationality.value);
      nationalityDropdown.classList.remove("hidden");
    });

    signupNationality.addEventListener("input", (e) => {
      renderCountries(e.target.value);
      nationalityDropdown.classList.remove("hidden");
    });

    signupNationality.addEventListener("blur", () => {
      nationalityDropdown.classList.add("hidden");
    });
  }

  // Helper function to strip spaces from OTP input
  function setupOtpInputStripper(fieldId) {
    const field = document.getElementById(fieldId);
    if (field) {
      field.addEventListener('input', (e) => {
        // Remove all spaces from the input value
        e.target.value = e.target.value.replace(/\s/g, '');
      });
    }
  }

  // Setup OTP input strippers for all OTP fields (signup, forgot password, delete account)
  setupOtpInputStripper("signupOtpCode");
  setupOtpInputStripper("resetOtpCode");
  setupOtpInputStripper("deleteAccountOtpCode");

  document.getElementById("loginBtn")?.addEventListener("click", async () => {
    const user = document.getElementById("loginUsername").value.trim();
    const pass = document.getElementById("loginPassword").value;
    if (!user || !pass) return ui.showAlert("Login Error", "Please enter both username/email and password");
    
    try {
      document.getElementById("loginBtn").textContent = "Logging In...";
      await auth.login(user, pass);
      document.getElementById("loginBtn").textContent = "Log In";
      await profiles.fetchPatients();
    } catch (e) {
      ui.showAlert("Login Failed", e.message);
      document.getElementById("loginBtn").textContent = "Log In";
    }
  });

  document.getElementById("signupCompleteBtn")?.addEventListener("click", async () => {
    const payload = {
      name: document.getElementById("signupName").value.trim(),
      username: document.getElementById("signupUsername").value.trim(),
      email: document.getElementById("signupEmail").value.trim(),
      password: document.getElementById("signupPassword").value,
      gender: document.getElementById("signupGender").value,
      age: parseInt(document.getElementById("signupAge").value) || null,
      nationality: document.getElementById("signupNationality").value,
      primary_concern: document.getElementById("signupConcern").value,
      emergency_contact_name: document.getElementById("signupEmergencyName").value.trim() || null,
      emergency_contact_phone: document.getElementById("signupEmergencyPhone").value.trim() || null
    };

    if (!payload.name || !payload.username || !payload.email || !payload.password || !payload.gender || !payload.nationality || !payload.primary_concern) {
      return ui.showAlert("Signup Error", "Please fill out all required fields (*).");
    }
    
    if (payload.password.length < 8) {
      return ui.showAlert("Signup Error", "Password must be at least 8 characters long.");
    }
    
    if (payload.age !== null && (payload.age < 5 || payload.age > 99)) {
      return ui.showAlert("Signup Error", "Age must be between 5 and 99.");
    }

    try {
      document.getElementById("signupCompleteBtn").textContent = "Creating Account...";
      document.getElementById("signupCompleteBtn").disabled = true;
      
      await auth.signup(payload);
      
      ui.showAlert("Success", "Account created successfully!");
      showAuthPanel("loginFormContainer");
      
      await profiles.fetchPatients();
    } catch (e) {
      ui.showAlert("Signup Failed", e.message);
    } finally {
      document.getElementById("signupCompleteBtn").textContent = "Create Account";
      document.getElementById("signupCompleteBtn").disabled = false;
    }
  });

  document.getElementById("submitResetBtn")?.addEventListener("click", async () => {
    const email = document.getElementById("forgotPwdEmail").value.trim();
    if (!email) return ui.showAlert("Reset Password", "Please enter your email.");
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) return ui.showAlert("Reset Password", "Please enter a valid email address.");

    const newPass = document.getElementById("resetNewPassword").value;
    if (!newPass || newPass.length < 8) return ui.showAlert("Reset Password", "New password must be at least 8 characters long.");
    try {
      document.getElementById("submitResetBtn").textContent = "Updating...";
      document.getElementById("submitResetBtn").disabled = true;
      await auth.resetPassword(email, newPass);
      ui.showAlert("Success", "Password reset successfully! Please log in.");
      showAuthPanel("loginFormContainer");
    } catch (e) {
      ui.showAlert("Reset Failed", e.message);
    } finally {
      document.getElementById("submitResetBtn").textContent = "Update Password";
      document.getElementById("submitResetBtn").disabled = false;
    }
  });

  // --- Profiles & Dashboard Events ---

  const patientDropdown = document.getElementById("patientDropdown");
  if (patientDropdown) patientDropdown.onchange = profiles.toggleSelectButton;

  const dashboardLogoutBtn = document.getElementById("dashboardLogoutBtn");
  if (dashboardLogoutBtn) {
    dashboardLogoutBtn.onclick = () => {
      auth.logout();
      ui.switchScreen("authScreen");
    };
  }

  const dashboardResetBtn = document.getElementById("dashboardResetBtn");
  if (dashboardResetBtn) {
    dashboardResetBtn.onclick = () => {
      ui.showConfirm(
        "Reset Profile?",
        "Are you sure you want to reset this profile? All sessions, messages, and analysis will be permanently deleted. The patient record will remain.",
        async () => {
          try {
            await api.resetPatientProfile(state.patientId);
          } catch (e) {
            console.error("Error resetting profile:", e);
          }
          document.getElementById("dashboardSessionsList").innerHTML = `<p class="text-clay text-sm italic">No previous sessions found.</p>`;
          document.getElementById("dashboardDomains").innerHTML = `
            <h3 class="font-utility uppercase text-clay text-sm border-b border-ink/30 pb-2">Clinical Profile</h3>
            <p class="text-clay text-sm italic mt-4">Profile has been reset.</p>
          `;
        }
      );
    };
  }

  const dashboardDeleteBtn = document.getElementById("dashboardDeleteBtn");
  if (dashboardDeleteBtn) {
    dashboardDeleteBtn.onclick = () => {
      document.getElementById("deleteAccountConfirmModal").style.display = "flex";
    };
  }

  const deleteAccountCancelBtn = document.getElementById("deleteAccountCancelBtn");
  if (deleteAccountCancelBtn) {
    deleteAccountCancelBtn.onclick = () => {
      document.getElementById("deleteAccountConfirmModal").style.display = "none";
    };
  }

  const deleteAccountConfirmBtn = document.getElementById("deleteAccountConfirmBtn");
  if (deleteAccountConfirmBtn) {
    deleteAccountConfirmBtn.onclick = async () => {
      try {
        deleteAccountConfirmBtn.textContent = "Deleting...";
        deleteAccountConfirmBtn.disabled = true;
        
        await auth.deleteAccount();
        
        document.getElementById("deleteAccountConfirmModal").style.display = "none";
        auth.logout();
        ui.switchScreen("authScreen");
        
      } catch (e) {
        console.error("Error deleting account:", e);
        ui.showAlert("Error", e.message);
      } finally {
        deleteAccountConfirmBtn.textContent = "DELETE";
        deleteAccountConfirmBtn.disabled = false;
      }
    };
  }
  const dashboardStartBtn = document.getElementById("dashboardStartBtn");
  if (dashboardStartBtn) {
    dashboardStartBtn.onclick = async () => {
      ui.switchScreen("loadingScreen", false);
      startButton.textContent = "Checking Session...";
      startButton.disabled = true;

      try {
        const active = await api.getActiveSession(state.patientId);
        if (active && active.session_id) {
          ui.switchScreen("dashboardScreen");
          const modal = document.getElementById("continueSessionModal");
          modal.style.display = "flex";

          document.getElementById("continueSessionBtn").onclick = async () => {
            modal.style.display = "none";
            ui.switchScreen("loadingScreen", false);
            startButton.textContent = "Resuming Session...";
            await session.continueActualSession(active.session_id);
          };

          document.getElementById("endAndStartNewBtn").onclick = async () => {
            modal.style.display = "none";
            ui.switchScreen("loadingScreen", false);
            startButton.textContent = "Loading Session...";
            state.setSessionId(null);
            await api.endSessionReq(active.session_id, state.patientId);
            await session.startActualSession(state.patientId);
          };
        } else {
          startButton.textContent = "Loading Session...";
          await session.startActualSession(state.patientId);
        }
      } catch (e) {
        console.error(e);
        startButton.textContent = "Loading Session...";
        await session.startActualSession(state.patientId);
      }
    };
  }

  const selectProfileBtn = document.getElementById("selectProfileBtn");
  if (selectProfileBtn) {
    selectProfileBtn.onclick = async () => {
      state.setPatientId(patientDropdown.value);
      await profiles.showDashboard(state.patientId);
    };
  }

  const createProfileBtn = document.getElementById("createProfileBtn");
  if (createProfileBtn) {
    createProfileBtn.onclick = async () => {
      const nameInput = document.getElementById("newPatientName");
      const ageInput = document.getElementById("newPatientAge");
      const genderInput = document.getElementById("newPatientGender");
      const occupationInput = document.getElementById("newPatientOccupation");
      const concernInput = document.getElementById("newPatientConcern");
      
      const name = nameInput.value.trim();
      const age = ageInput.value;
      const gender = genderInput ? genderInput.value : null;
      const occupation = occupationInput ? occupationInput.value.trim() : null;

      if (!name || !age || !gender || !occupation) {
        ui.showAlert("Missing Information", "Please fill out all 4 required fields (Name, Age, Gender, and Occupation) to create a new profile.");
        return;
      }
      
      const parsedAge = parseInt(age);
      if (isNaN(parsedAge) || parsedAge < 5 || parsedAge > 99) {
        ui.showAlert("Invalid Age", "Age must be between 5 and 99.");
        return;
      }

      try {
        const data = {
          name: name,
          age: parseInt(age),
          gender: gender,
          occupation: occupation,
          primary_concern: concernInput ? concernInput.value.trim() : null
        };
        const pData = await api.createPatientProfile(data);
        state.setPatientId(pData.patient_id);
        await profiles.showDashboard(state.patientId);
      } catch (e) {
        console.error("Failed to create profile:", e);
        ui.showAlert("Error", "Failed to create patient profile. Please try again.");
      }
    };
  }

  if (startButton) {
    startButton.onclick = async () => {
      const text = startButton.textContent.trim();
      if (text.includes("Start Consultation")) {
        if (!auth.isAuthenticated()) {
          ui.switchScreen("authScreen", false);
          return;
        }
        
        startButton.textContent = "Loading...";
        startButton.disabled = true;
        try {
          await profiles.fetchPatients();
        } catch(e) {
          console.error(e);
          ui.showAlert("Error", "Failed to load dashboard. Check console.");
        } finally {
          startButton.textContent = "Start Consultation";
          startButton.disabled = false;
        }
      } else if (text.includes("Retry")) {
        startButton.textContent = "Initializing...";
        startButton.disabled = true;
        session.initializeSession();
      }
    };
  }

  // --- Session UI Events (Toggle Text/Voice, etc) ---

  if (voiceModeBtn) {
    voiceModeBtn.onclick = (e) => {
      state.isVoiceMode = true;
      voiceModeBtn.classList.add("active");
      textModeBtn.classList.remove("active");
      voiceInput.style.display = "flex";
      textInput.style.display = "none";
      
      // Auto-enable audio output when switching to voice mode
      if (!state.isAudioOutputEnabled) {
        session.setAudioOutput(true);
      }
      e.currentTarget.blur();
    };
  }

  if (textModeBtn) {
    textModeBtn.onclick = (e) => {
      state.isVoiceMode = false;
      textModeBtn.classList.add("active");
      voiceModeBtn.classList.remove("active");
      voiceInput.style.display = "none";
      textInput.style.display = "block";
      chatInput.focus();
    };
  }

  const voiceSelect = document.getElementById("voiceSelect");
  if (voiceSelect) {
    voiceSelect.addEventListener('change', (e) => e.target.blur());
  }

  const audioOutputToggleMobile = document.getElementById("audioOutputToggleMobile");
  if (audioOutputToggleMobile) {
    audioOutputToggleMobile.addEventListener('change', (e) => {
      session.setAudioOutput(e.target.checked);
      e.target.blur();
    });
  }

  const audioOutputToggleDesktop = document.getElementById("audioOutputToggleDesktop");
  if (audioOutputToggleDesktop) {
    audioOutputToggleDesktop.addEventListener('click', (e) => {
      session.setAudioOutput(!state.isAudioOutputEnabled);
      e.currentTarget.blur();
    });
  }

  if (sendBtn) {
    sendBtn.onclick = () => {
      const message = chatInput.value.trim();
      if (message) {
        chatInput.value = "";
        session.primeTTS(); // Renew activation synchronously
        session.sendTextMessage(message);
      }
    };
  }

  if (chatInput) {
    chatInput.onkeypress = (e) => {
      if (e.key === 'Enter') sendBtn.onclick();
    };
  }

  // --- Audio Recording Events ---

  if (micBtn) {
    micBtn.addEventListener('pointerdown', (e) => {
      e.preventDefault();
      if (!state.isVoiceMode || state.isAISpeaking) return;
      if (!state.isListening && !state.isRecordingPending) {
        micBtn.style.transform = 'scale(0.95)';
        audio.startRecording(session.sendTextMessage);
      }
    });

    const stopMicAction = (e) => {
      e.preventDefault();
      if (state.isVoiceMode && (state.isListening || state.isRecordingPending)) {
        micBtn.style.transform = 'none';
        session.primeTTS(); // Renew activation synchronously
        audio.stopRecording();
      }
    };

    micBtn.addEventListener('pointerup', stopMicAction);
    micBtn.addEventListener('pointercancel', stopMicAction);
    micBtn.addEventListener('pointerleave', stopMicAction);
  }

  // Spacebar hold-to-record (capture phase to intercept before browser synthetic clicks)
  window.addEventListener('keydown', (e) => {
    if (e.code !== 'Space' || e.repeat) return;
    if (!state.isVoiceMode) return;
    if (['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName)) return;
    
    e.preventDefault();
    e.stopPropagation();
    
    if (state.isAISpeaking) return;
    if (!state.isListening && !state.isRecordingPending) {
      audio.startRecording(session.sendTextMessage);
    }
  }, { capture: true });

  window.addEventListener('keyup', (e) => {
    if (e.code !== 'Space') return;
    if (!state.isVoiceMode) return;
    if (['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName)) return;
    
    e.preventDefault();
    e.stopPropagation();
    
    session.primeTTS(); // Renew activation synchronously
    audio.stopRecording();
  }, { capture: true });

  const endSessionBtn = document.getElementById("endSessionBtn");
  if (endSessionBtn) {
    endSessionBtn.onclick = async () => {
      if (!state.sessionId) return;

      if (window.speechSynthesis.speaking) window.speechSynthesis.cancel();
      ui.setStatusText("Ending session...");

      try {
        await api.endSessionReq(state.sessionId, state.patientId);
        state.setSessionId(null);
        window.location.href = "/";
      } catch (err) {
        console.error("Failed to end session:", err);
        state.setSessionId(null);
        window.location.href = "/";
      }
    };
  }
}

// Bootstrap application
api.pingHealth().catch(() => console.log("Wakeup ping sent."));
audio.loadVoices();
bindEvents();
window.onload = () => session.initializeSession();