File size: 10,152 Bytes
b30c060
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// CyberGuard AI Assistant Main Script

document.addEventListener('DOMContentLoaded', function() {
    // DOM Elements
    const sidebar = document.getElementById('sidebar');
    const menuToggle = document.getElementById('menu-toggle');
    const chatContainer = document.querySelector('.chat-container');
    const userInput = document.getElementById('user-input');
    const sendButton = document.getElementById('send-btn');
    const chatMessages = document.getElementById('chat-messages');
    const typingIndicator = document.getElementById('typing-indicator');
    const infoButton = document.getElementById('info-btn');
    const infoModal = document.getElementById('info-modal');
    const closeModalButtons = document.querySelectorAll('.close-modal');
    const languageSelector = document.getElementById('language-selector');
    const languageDropdown = document.getElementById('language-dropdown');
    const currentLanguageSpan = document.getElementById('current-language');
    const languageOptions = document.querySelectorAll('.language-option');
    const exampleQueries = document.querySelectorAll('.example-query');
    const newChatButtons = document.querySelectorAll('#sidebar-new-chat-btn, #header-new-chat-btn');
    const conversationList = document.getElementById('conversation-list');

    // App State
    const state = {
        currentLanguage: CONFIG.app.defaultLanguage,
        conversations: [], // All conversations
        currentConversationId: null, // Current active conversation ID
        loading: false,
        systemContext: CONFIG.openai.system_message,
    };

    // Initialize the application
    function init() {
        loadConversations();
        createNewConversation();
        setupEventListeners();
        updateUIText();
    }

    // Setup Event Listeners
    function setupEventListeners() {
        // Menu toggle
        menuToggle.addEventListener('click', toggleSidebar);

        // Send message on button click
        sendButton.addEventListener('click', sendMessage);

        // Send message on Enter key (but allow Shift+Enter for new line)
        userInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!sendButton.disabled) {
                    sendMessage();
                }
            }
        });

        // Enable/disable send button based on input
        userInput.addEventListener('input', () => {
            sendButton.disabled = userInput.value.trim() === '';
            
            // Auto-resize textarea
            userInput.style.height = 'auto';
            userInput.style.height = (userInput.scrollHeight) + 'px';
        });

        // Info button
        infoButton.addEventListener('click', () => {
            infoModal.classList.add('active');
        });

        // Close modals
        closeModalButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.target.closest('.modal').classList.remove('active');
            });
        });

        // Language selector
        languageSelector.addEventListener('click', (e) => {
            e.stopPropagation();
            languageDropdown.classList.toggle('active');
        });

        // Close language dropdown when clicking outside
        document.addEventListener('click', () => {
            languageDropdown.classList.remove('active');
        });

        // Language selection
        languageOptions.forEach(option => {
            option.addEventListener('click', (e) => {
                const lang = e.target.getAttribute('data-lang');
                changeLanguage(lang);
                languageDropdown.classList.remove('active');
            });
        });

        // Example queries
        exampleQueries.forEach(query => {
            query.addEventListener('click', () => {
                const queryText = query.getAttribute('data-query');
                userInput.value = queryText;
                sendButton.disabled = false;
                userInput.focus();
                sendMessage();
            });
        });

        // New chat button
        newChatButtons.forEach(button => {
            button.addEventListener('click', () => {
                createNewConversation();
                if (window.innerWidth <= 768) {
                    toggleSidebar();
                }
            });
        });
    }

    // Toggle sidebar
    function toggleSidebar() {
        sidebar.classList.toggle('active');
        chatContainer.classList.toggle('sidebar-open');
    }

    // Send message to AI
    async function sendMessage() {
        if (userInput.value.trim() === '' || state.loading) return;

        const userMessage = userInput.value.trim();
        userInput.value = '';
        userInput.style.height = 'auto';
        sendButton.disabled = true;

        // Auto-detect language from user input
        detectAndUpdateLanguage(userMessage);

        // Add user message to UI
        const userMessageId = 'msg-' + Date.now();
        addMessageToUI('user', userMessage, userMessageId);
        
        // Scroll to bottom
        scrollToBottom();

        // Add to conversation history
        addMessageToConversation('user', userMessage);

        // Show typing indicator
        typingIndicator.classList.add('active');
        
        // Set loading state
        state.loading = true;

        try {
            // Get current conversation
            const conversation = state.conversations.find(c => c.id === state.currentConversationId);
            
            // Create messages array for API - including conversation history for context
            const messages = [
                { role: "system", content: state.systemContext },
                ...conversation.messages.map(msg => ({
                    role: msg.role,
                    content: msg.content
                }))
            ];

            // Call OpenAI API
            const response = await callOpenAI(messages);
            
            // Hide typing indicator
            typingIndicator.classList.remove('active');
            
            // Parse response
            if (response && response.choices && response.choices[0]) {
                const botResponse = response.choices[0].message.content;
                
                // Add bot message to UI with typing effect
                const botMessageId = 'msg-' + Date.now();
                addMessageToUI('bot', '', botMessageId);
                
                // Add bot message to conversation immediately but update UI with typing effect
                addMessageToConversation('assistant', botResponse);
                
                // Apply typing effect
                await typeMessage(botMessageId, botResponse);
                
                // Update the first message of the conversation as the title if this is a new conversation
                if (conversation.messages.length <= 2) {
                    updateConversationTitle(conversation.id, userMessage);
                }
                
                // Save conversations to local storage
                saveConversations();
                
                // Update sidebar
                updateConversationList();
            }
        } catch (error) {
            console.error('Error sending message:', error);
            
            // Add error message to UI
            addMessageToUI('bot', 'Sorry, I encountered an error. Please try again later.');
            
            // Hide typing indicator
            typingIndicator.classList.remove('active');
        }
        
        // Reset loading state
        state.loading = false;
        
        // Enable send button if there's text in the input
        sendButton.disabled = userInput.value.trim() === '';
        
        // Scroll to bottom
        scrollToBottom();
    }

    // Add message to UI
    function addMessageToUI(role, content, id = null) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}`;
        if (id) {
            messageDiv.id = id;
        }
        
        const avatar = document.createElement('div');
        avatar.className = 'message-avatar';
        
        if (role === 'user') {
            avatar.innerHTML = '<i class="fas fa-user"></i>';
        } else {
            avatar.innerHTML = '<i class="fas fa-robot"></i>';
        }
        
        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        
        // Format message content with Markdown-like syntax
        if (content) {
            // Handle code blocks
            content = content.replace(/```([\s\S]*?)```/g, function(match, p1) {
                return `<pre>${p1}</pre>`;
            });
            
            // Handle bold text
            content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            
            // Handle italic text
            content = content.replace(/\*(.*?)\*/g, '<em>$1</em>');
            
            // Handle line breaks
            content = content.replace(/\n/g, '<br>');
            
            messageContent.innerHTML = content;
        }
        
        const timestamp = document.createElement('div');
        timestamp.className = 'message-time';
        timestamp.textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        
        messageContent.appendChild(timestamp);
        messageDiv.appendChild(avatar);
        messageDiv.appendChild(messageContent);
        
        // Remove welcome container if present
        const welcomeContainer = document.querySelector('.welcome-container');
        if (welcomeContainer) {
            welcomeContainer.remove();
        }
        
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
    }

    // Type effect for bot messages
    async function typeMessage(messageId, content) {
        const messageContent = document.querySelector(`#${messageId} .message-content`);