File size: 9,496 Bytes
ec1988c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// DOM Elements
const chatMessages = document.getElementById('chatMessages');
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const languageSelect = document.getElementById('languageSelect');

// Initialize chat
document.addEventListener('DOMContentLoaded', () => {
    loadChatHistory();
    setupEventListeners();
});

// Set up event listeners
function setupEventListeners() {
    // Send button click
    sendButton.addEventListener('click', sendMessage);
    
    // Enter key press
    userInput.addEventListener('keypress', handleKeyPress);
    
    // Input focus
    userInput.addEventListener('focus', () => {
        userInput.style.borderColor = '#00205b';
    });
    
    // Input blur
    userInput.addEventListener('blur', () => {
        userInput.style.borderColor = '#dee2e6';
    });
}

// Handle keyboard input
function handleKeyPress(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
}

// Send message to backend
async function sendMessage() {
    const message = userInput.value.trim();
    const language = languageSelect.value;
    
    if (!message) {
        return;
    }
    
    // Add user message to chat
    addMessage(message, 'user', language);
    
    // Clear input
    userInput.value = '';
    
    // Show loading
    showLoading(true);
    
    try {
        // Send to backend
        const response = await fetch('/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message,
                language: language
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // Add bot response to chat
        if (data.response) {
            addMessage(data.response, 'bot', language, data.type);
        } else if (data.error) {
            addMessage(`Error: ${data.error}`, 'bot', language, 'error');
        }
        
    } catch (error) {
        console.error('Error sending message:', error);
        addMessage('Sorry, I encountered an error. Please try again.', 'bot', language, 'error');
    } finally {
        showLoading(false);
        // Scroll to bottom
        scrollToBottom();
    }
}

// Add message to chat UI
function addMessage(text, sender, lang, type = '') {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}-message`;
    
    const now = new Date();
    const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    
    // Format message content (preserve HTML links)
    let formattedText = text;
    if (sender === 'bot') {
        // Add type indicator
        const typeBadge = type ? getTypeBadge(type) : '';
        formattedText = `${typeBadge}${text}`;
    }
    
    messageDiv.innerHTML = `
        <div class="message-content">
            <strong>${sender === 'user' ? 'You' : 'SASTRA Bot'}:</strong> ${formattedText}
        </div>
        <div class="message-time text-muted">
            ${timeString}${getLanguageName(lang)}
        </div>
    `;
    
    chatMessages.appendChild(messageDiv);
    scrollToBottom();
    
    // Save to local storage
    saveChatToLocal();
}

// Get type badge for message
function getTypeBadge(type) {
    const badges = {
        'keyword': '<span class="badge bg-warning me-2">Keyword</span>',
        'rag': '<span class="badge bg-info me-2">RAG</span>',
        'llm': '<span class="badge bg-primary me-2">LLM</span>',
        'error': '<span class="badge bg-danger me-2">Error</span>'
    };
    return badges[type] || '';
}

// Get language name from code
function getLanguageName(code) {
    const languages = {
        'en': 'English',
        'ta': 'Tamil',
        'te': 'Telugu',
        'kn': 'Kannada',
        'hi': 'Hindi'
    };
    return languages[code] || code;
}

// Show/hide loading spinner
function showLoading(show) {
    if (show) {
        // Create loading message
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'message bot-message';
        loadingDiv.id = 'loadingMessage';
        loadingDiv.innerHTML = `
            <div class="message-content">
                <strong>SASTRA Bot:</strong> 
                <div class="spinner-border spinner-border-sm text-primary ms-2" role="status">
                    <span class="visually-hidden">Thinking...</span>
                </div>
                Thinking...
            </div>
        `;
        chatMessages.appendChild(loadingDiv);
        scrollToBottom();
    } else {
        const loadingMessage = document.getElementById('loadingMessage');
        if (loadingMessage) {
            loadingMessage.remove();
        }
    }
}

// Scroll chat to bottom
function scrollToBottom() {
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// Clear chat history
function clearChat() {
    if (confirm('Are you sure you want to clear the chat history?')) {
        chatMessages.innerHTML = `
            <div class="message bot-message">
                <div class="message-content">
                    <strong>SASTRA Bot:</strong> Chat cleared! How can I help you today?
                </div>
                <div class="message-time text-muted">
                    Just now
                </div>
            </div>
        `;
        localStorage.removeItem('chatHistory');
    }
}

// Quick question button handler
function quickQuestion(button) {
    const question = button.textContent.trim();
    userInput.value = question;
    sendMessage();
}

// Load chat history from local storage
function loadChatHistory() {
    try {
        const saved = localStorage.getItem('chatHistory');
        if (saved) {
            const history = JSON.parse(saved);
            // Keep only last 20 messages
            const recentHistory = history.slice(-20);
            
            recentHistory.forEach(msg => {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${msg.sender}-message`;
                messageDiv.innerHTML = `
                    <div class="message-content">
                        <strong>${msg.sender === 'user' ? 'You' : 'SASTRA Bot'}:</strong> ${msg.text}
                    </div>
                    <div class="message-time text-muted">
                        ${msg.time}${getLanguageName(msg.lang)}
                    </div>
                `;
                chatMessages.appendChild(messageDiv);
            });
            
            scrollToBottom();
        }
    } catch (error) {
        console.error('Error loading chat history:', error);
    }
}

// Save chat to local storage
function saveChatToLocal() {
    try {
        const messages = chatMessages.querySelectorAll('.message');
        const history = [];
        
        messages.forEach(msg => {
            const sender = msg.classList.contains('user-message') ? 'user' : 'bot';
            const content = msg.querySelector('.message-content');
            const time = msg.querySelector('.message-time').textContent.split('•')[0].trim();
            const lang = msg.querySelector('.message-time').textContent.split('•')[1].trim();
            
            // Extract text from content (remove HTML tags for storage)
            const text = content.textContent.replace(/SASTRA Bot:|You:/, '').trim();
            
            history.push({
                sender: sender,
                text: text,
                time: time,
                lang: getLanguageCode(lang)
            });
        });
        
        localStorage.setItem('chatHistory', JSON.stringify(history));
    } catch (error) {
        console.error('Error saving chat history:', error);
    }
}

// Get language code from name
function getLanguageCode(name) {
    const languages = {
        'English': 'en',
        'Tamil': 'ta',
        'Telugu': 'te',
        'Kannada': 'kn',
        'Hindi': 'hi'
    };
    return languages[name] || 'en';
}

// Auto-resize textarea (if using textarea instead of input)
function autoResizeTextarea(textarea) {
    textarea.style.height = 'auto';
    textarea.style.height = Math.min(textarea.scrollHeight, 100) + 'px';
}

// Add sample questions
const sampleQuestions = [
    "What are the admission requirements for B.Tech?",
    "How to apply for scholarships?",
    "Tell me about hostel facilities",
    "What is the placement percentage?",
    "List of courses offered",
    "Contact information for admissions office"
];

// Utility function to format links in text
function formatLinks(text) {
    const urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, url => `<a href="${url}" target="_blank" class="chat-link">${url}</a>`);
}

// Utility function to escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Initialize chat interface on page load
window.onload = function() {
    // Set focus to input
    userInput.focus();
    
    // Add some sample questions if chat is empty
    if (chatMessages.children.length <= 1) {
        // Welcome message already exists
        console.log('Chat initialized');
    }
};