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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
/**
 * UI Controller class
 * Handles all UI updates, toasts, indicators, and user interactions
 */
export class UIController {
    constructor() {
      this.elements = {
        systemPrompt: document.getElementById('systemPrompt'),
        voice: document.getElementById('voice'),
        modelSelect: document.getElementById('modelSelect'),
        enableGoogleSearch: document.getElementById('enableGoogleSearch'),
        allowInterruptions: document.getElementById('allowInterruptions'),
        startAudioBtn: document.getElementById('startAudioBtn'),
        startCameraBtn: document.getElementById('startCameraBtn'),
        startScreenBtn: document.getElementById('startScreenBtn'),
        stopButton: document.getElementById('stopButton'),
        switchCameraBtn: document.getElementById('switchCameraBtn'),
        messages: document.getElementById('messages'),
        videoContainer: document.getElementById('videoContainer'),
        statusBadge: document.getElementById('statusBadge'),
        textInput: document.getElementById('textInput'),
        sendTextBtn: document.getElementById('sendTextBtn'),
        themeToggle: document.getElementById('themeToggle'),
        toggleAdvanced: document.getElementById('toggleAdvanced'),
        advancedContent: document.getElementById('advancedContent'),
        advancedChevron: document.getElementById('advancedChevron'),
        modalityAudio: document.getElementById('modalityAudio'),
        modalityText: document.getElementById('modalityText'),
        toolExecutionMode: document.getElementById('toolExecutionMode'),
        toolsJson: document.getElementById('toolsJson'),
        btnAttach: document.getElementById('btnAttach'),
        fileInput: document.getElementById('fileInput'),
        fileUploadStatus: document.getElementById('fileUploadStatus'),
        connIndicator: document.getElementById('connIndicator'),
        micIndicator: document.getElementById('micIndicator'),
        audioOutIndicator: document.getElementById('audioOutIndicator'),
        videoIndicator: document.getElementById('videoIndicator'),
        toastContainer: document.getElementById('toastContainer'),
        sidebar: document.getElementById('sidebar'),
        toggleSidebar: document.getElementById('toggleSidebar'),
        toggleSidebarMobile: document.getElementById('toggleSidebarMobile'),
      };

      this.initTheme();
      this.initLayoutControls();
      this.initAdvancedPanel();
      this.loadSettings();
      this.initSettingsPersistence();
    }

    /**
     * Get user configuration from form inputs
     * @returns {Object} - Configuration object
     */
    getConfig() {
      const modalities = [];
      if (this.elements.modalityAudio.checked) modalities.push('AUDIO');
      if (this.elements.modalityText.checked) modalities.push('TEXT');

      let tools = [];
      try {
        const raw = this.elements.toolsJson.value.trim();
        if (raw) {
          const parsed = JSON.parse(raw);
          tools = Array.isArray(parsed) ? parsed : [parsed];
        }
      } catch (e) {
        // ignore invalid JSON
      }

      return {
        systemPrompt: this.elements.systemPrompt.value,
        voice: this.elements.voice.value,
        model: this.elements.modelSelect.value,
        googleSearch: this.elements.enableGoogleSearch.checked,
        allowInterruptions: this.elements.allowInterruptions.checked,
        responseModalities: modalities.length ? modalities : ['AUDIO'],
        toolExecutionMode: this.elements.toolExecutionMode.value,
        tools: tools,
      };
    }

    /**
     * Update UI elements based on streaming state.
     * Inputs (text/attach/send) stay always-on; only Stop toggles.
     * Mic icon highlights when any session is active.
     * @param {boolean} isStreaming - Whether streaming is active
     * @param {string|null} currentMode - 'audio', 'camera', or 'screen'
     */
    updateUIForStreaming(isStreaming, currentMode = null) {
      if (this.elements.stopButton) this.elements.stopButton.disabled = !isStreaming;

      if (this.elements.statusBadge) {
        if (isStreaming) {
          this.elements.statusBadge.textContent = "Connected";
          this.elements.statusBadge.className = "status-badge connected";
        } else {
          this.elements.statusBadge.textContent = "Disconnected";
          this.elements.statusBadge.className = "status-badge disconnected";
        }
      }

      if (this.elements.startAudioBtn) {
        this.elements.startAudioBtn.classList.toggle('active', isStreaming);
      }

      if (this.elements.startCameraBtn) {
        this.elements.startCameraBtn.classList.toggle('active', isStreaming && currentMode === 'camera');
      }

      if (this.elements.startScreenBtn) {
        this.elements.startScreenBtn.classList.toggle('active', isStreaming && currentMode === 'screen');
      }
    }

    setReconnectingState() {
      if (this.elements.statusBadge) {
        this.elements.statusBadge.textContent = "Reconnecting...";
        this.elements.statusBadge.className = "status-badge reconnecting";
      }
    }

    /**
     * Show video preview container
     */
    showVideoPreview() {
      if (this.elements.videoContainer) {
        this.elements.videoContainer.classList.remove('hidden');
      }
    }

    /**
     * Hide video preview container
     */
    hideVideoPreview() {
      if (this.elements.videoContainer) {
        this.elements.videoContainer.classList.add('hidden');
      }
    }

    /**
     * Append a system log message to the conversation area
     * @param {string} message - Message text to display
     */
    appendMessage(message) {
      const messageDiv = document.createElement('div');
      messageDiv.className = 'message';
      messageDiv.textContent = message;

      if (this.elements.messages) {
        this.elements.messages.appendChild(messageDiv);
        this.elements.messages.scrollTop = this.elements.messages.scrollHeight;
      }
    }

    /**
     * Show an error message
     * @param {string} errorText - Error message to display
     */
    showError(errorText) {
      this.showToast(errorText, 'error');
      console.error(errorText);
    }

    /**
     * Show a success/info message
     * @param {string} message - Message text to display
     */
    showInfo(message) {
      this.showToast(message, 'success');
      console.log(message);
    }

    showWarning(message) {
      this.showToast(message, 'warning');
      console.warn(message);
    }

    showToast(message, type = 'info') {
      if (!this.elements.toastContainer) return;
      const toast = document.createElement('div');
      toast.className = `toast ${type}`;
      toast.textContent = message;
      this.elements.toastContainer.appendChild(toast);
      setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(20px)';
        toast.style.transition = 'all 0.3s ease';
        setTimeout(() => toast.remove(), 300);
      }, 4000);
    }

    /**
     * Clear all messages from the conversation area
     */
    clearMessages() {
      if (this.elements.messages) {
        this.elements.messages.innerHTML = '';
      }
    }

    /**
     * Set loading state for buttons
     * @param {boolean} isLoading - Whether loading is active
     */
    setLoading(isLoading) {
      const buttons = [this.elements.startAudioBtn, this.elements.startCameraBtn, this.elements.startScreenBtn];
      buttons.forEach(btn => {
        if (btn) {
          btn.disabled = isLoading;
          if (isLoading) {
            btn.dataset.originalText = btn.textContent;
            btn.textContent = btn.textContent.replace('Start', 'Starting...');
          } else if (btn.dataset.originalText) {
            btn.textContent = btn.dataset.originalText;
          }
        }
      });
    }

    /**
     * Update camera switch button visibility
     * @param {boolean} visible - Whether the button should be visible
     */
    setCameraSwitchVisible(visible) {
      if (this.elements.switchCameraBtn) {
        this.elements.switchCameraBtn.style.display = visible ? 'inline-flex' : 'none';
      }
    }

    /**
     * Initialize theme from localStorage
     */
    initTheme() {
      const savedTheme = localStorage.getItem('theme');
      if (savedTheme === 'light') {
        document.body.classList.add('light-theme');
        if (this.elements.themeToggle) {
          this.elements.themeToggle.textContent = '☀️';
        }
      }
      if (this.elements.themeToggle) {
        this.elements.themeToggle.addEventListener('click', () => this.toggleTheme());
      }
    }

    /**
     * Toggle between light and dark theme
     */
    toggleTheme() {
      document.body.classList.toggle('light-theme');
      const isLight = document.body.classList.contains('light-theme');
      localStorage.setItem('theme', isLight ? 'light' : 'dark');
      if (this.elements.themeToggle) {
        this.elements.themeToggle.textContent = isLight ? '☀️' : '🌙';
      }
    }

    initLayoutControls() {
      const sidebar = this.elements.sidebar;
      const toggleSidebar = this.elements.toggleSidebar;
      const toggleSidebarMobile = this.elements.toggleSidebarMobile;
      const messagesContainer = this.elements.messages;

      if (window.innerWidth <= 768 && sidebar) {
        sidebar.classList.add('collapsed');
      }

      if (toggleSidebar && sidebar) {
        toggleSidebar.addEventListener('click', (e) => {
          e.stopPropagation();
          sidebar.classList.toggle('collapsed');
        });
      }

      if (toggleSidebarMobile && sidebar) {
        toggleSidebarMobile.addEventListener('click', () => {
          sidebar.classList.add('collapsed');
        });
      }

      if (messagesContainer) {
        messagesContainer.addEventListener('click', () => {
          if (window.innerWidth <= 768 && !sidebar.classList.contains('collapsed')) {
            sidebar.classList.add('collapsed');
          }
        });
      }
    }

    initAdvancedPanel() {
      const toggle = this.elements.toggleAdvanced;
      const content = this.elements.advancedContent;
      const panel = toggle?.closest('.advanced-panel');
      if (!toggle || !content) return;

      toggle.addEventListener('click', () => {
        content.classList.toggle('hidden');
        if (panel) panel.classList.toggle('open');
      });
    }

    /**
     * Load persisted settings from localStorage
     */
    loadSettings() {
      try {
        const raw = localStorage.getItem('gemini_live_settings');
        if (!raw) return;
        const settings = JSON.parse(raw);

        if (settings.systemPrompt !== undefined && this.elements.systemPrompt) {
          this.elements.systemPrompt.value = settings.systemPrompt;
        }
        if (settings.voice !== undefined && this.elements.voice) {
          this.elements.voice.value = settings.voice;
        }
        if (settings.model !== undefined && this.elements.modelSelect) {
          this.elements.modelSelect.value = settings.model;
        }
        if (settings.googleSearch !== undefined && this.elements.enableGoogleSearch) {
          this.elements.enableGoogleSearch.checked = settings.googleSearch;
        }
        if (settings.allowInterruptions !== undefined && this.elements.allowInterruptions) {
          this.elements.allowInterruptions.checked = settings.allowInterruptions;
        }
        if (settings.modalityAudio !== undefined && this.elements.modalityAudio) {
          this.elements.modalityAudio.checked = settings.modalityAudio;
        }
        if (settings.modalityText !== undefined && this.elements.modalityText) {
          this.elements.modalityText.checked = settings.modalityText;
        }
        if (settings.toolExecutionMode !== undefined && this.elements.toolExecutionMode) {
          this.elements.toolExecutionMode.value = settings.toolExecutionMode;
        }
        if (settings.toolsJson !== undefined && this.elements.toolsJson) {
          this.elements.toolsJson.value = settings.toolsJson;
        }
      } catch (e) {
        console.warn('Failed to load settings:', e);
      }
    }

    /**
     * Persist current settings to localStorage
     */
    saveSettings() {
      try {
        const settings = {
          systemPrompt: this.elements.systemPrompt ? this.elements.systemPrompt.value : '',
          voice: this.elements.voice ? this.elements.voice.value : '',
          model: this.elements.modelSelect ? this.elements.modelSelect.value : '',
          googleSearch: this.elements.enableGoogleSearch ? this.elements.enableGoogleSearch.checked : false,
          allowInterruptions: this.elements.allowInterruptions ? this.elements.allowInterruptions.checked : false,
          modalityAudio: this.elements.modalityAudio ? this.elements.modalityAudio.checked : true,
          modalityText: this.elements.modalityText ? this.elements.modalityText.checked : true,
          toolExecutionMode: this.elements.toolExecutionMode ? this.elements.toolExecutionMode.value : '',
          toolsJson: this.elements.toolsJson ? this.elements.toolsJson.value : '',
        };
        localStorage.setItem('gemini_live_settings', JSON.stringify(settings));
      } catch (e) {
        console.warn('Failed to save settings:', e);
      }
    }

    /**
     * Attach auto-save listeners to all setting inputs
     */
    initSettingsPersistence() {
      const inputs = [
        this.elements.systemPrompt,
        this.elements.voice,
        this.elements.modelSelect,
        this.elements.enableGoogleSearch,
        this.elements.allowInterruptions,
        this.elements.modalityAudio,
        this.elements.modalityText,
        this.elements.toolExecutionMode,
        this.elements.toolsJson,
      ];

      const save = () => this.saveSettings();
      const debouncedSave = this._debounce(save, 500);

      inputs.forEach(el => {
        if (!el) return;
        el.addEventListener('change', save);
        if (el.tagName === 'TEXTAREA' || el.type === 'text') {
          el.addEventListener('input', debouncedSave);
        }
      });
    }

    _debounce(fn, ms) {
      let timer;
      return () => {
        clearTimeout(timer);
        timer = setTimeout(fn, ms);
      };
    }

    setIndicatorState(name, active, pulsing = false) {
      const el = this.elements[`${name}Indicator`];
      if (!el) return;
      el.classList.toggle('active', active);
      el.classList.toggle('pulse', pulsing);
    }

    resetIndicators() {
      ['conn', 'mic', 'audioOut', 'video'].forEach(name => {
        this.setIndicatorState(name, false, false);
      });
    }

    setFileUploadStatus(text, isError = false) {
      if (!this.elements.fileUploadStatus) return;
      this.elements.fileUploadStatus.textContent = text;
      this.elements.fileUploadStatus.classList.remove('hidden', 'error');
      if (isError) this.elements.fileUploadStatus.classList.add('error');
    }

    clearFileUploadStatus() {
      if (!this.elements.fileUploadStatus) return;
      this.elements.fileUploadStatus.classList.add('hidden');
      this.elements.fileUploadStatus.classList.remove('error');
    }
}