// Shared JavaScript across all pages class ChatApp { constructor() { this.apiKey = localStorage.getItem('openai-api-key') || ''; this.messages = []; this.init(); } init() { this.bindEvents(); this.loadApiKey(); this.updateApiKeyDisplay(); } bindEvents() { document.getElementById('send-button').addEventListener('click', () => this.sendMessage()); document.getElementById('message-input').addEventListener('keypress', (e) => { if (e.key === 'Enter') this.sendMessage(); }); document.getElementById('save-api-key').addEventListener('click', () => this.saveApiKey()); } loadApiKey() { const savedKey = localStorage.getItem('openai-api-key'); if (savedKey) { this.apiKey = savedKey; document.getElementById('api-key-input').value = savedKey; } } saveApiKey() { const keyInput = document.getElementById('api-key-input'); if (keyInput.value.trim()) { this.apiKey = keyInput.value.trim(); localStorage.setItem('openai-api-key', this.apiKey); this.updateApiKeyDisplay(); this.showNotification('API key saved successfully!', 'success'); } else { this.showNotification('Please enter a valid API key', 'error'); } } updateApiKeyDisplay() { const keyInput = document.getElementById('api-key-input'); if (this.apiKey) { keyInput.placeholder = 'API key saved'; } else { keyInput.placeholder = 'Enter your OpenAI API key'; } } async sendMessage() { const input = document.getElementById('message-input'); const message = input.value.trim(); if (!message) return; if (!this.apiKey) { this.showNotification('Please enter your OpenAI API key first', 'error'); return; } // Add user message to UI this.addMessage(message, 'user'); input.value = ''; // Show typing indicator const typingIndicator = this.addTypingIndicator(); try { const response = await this.callOpenAI(message); // Remove typing indicator typingIndicator.remove(); // Add assistant response this.addMessage(response, 'assistant'); } catch (error) { // Remove typing indicator typingIndicator.remove(); this.addMessage('Sorry, I encountered an error. Please try again.', 'assistant'); console.error('Error:', error); } } addMessage(content, sender) { const messagesContainer = document.getElementById('messages'); const messageDiv = document.createElement('div'); messageDiv.className = `message ${sender}-message rounded-lg p-4 max-w-[80%] ${sender === 'user' ? 'ml-auto' : ''}`; if (sender === 'user') { messageDiv.innerHTML = `