File size: 12,337 Bytes
822ed62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c3c60
822ed62
 
 
 
 
 
a8c3c60
 
822ed62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c3c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822ed62
 
 
 
 
a8c3c60
822ed62
 
 
 
 
 
 
 
 
a8c3c60
822ed62
 
a8c3c60
822ed62
a8c3c60
822ed62
 
 
 
 
 
a8c3c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
822ed62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8c3c60
 
 
822ed62
a8c3c60
822ed62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// App State
const state = {
    currentChatId: null,
    chats: [],
    isGenerating: false,
    theme: localStorage.getItem('theme') || 'system',
    sidebarOpen: false
};

// DOM Elements
const elements = {
    chatContainer: document.getElementById('chat-container'),
    messagesWrapper: document.getElementById('messages-wrapper'),
    messageInput: document.getElementById('message-input'),
    sendBtn: document.getElementById('send-btn'),
    welcomeScreen: document.getElementById('welcome-screen'),
    sidebar: document.getElementById('sidebar'),
    toggleSidebar: document.getElementById('toggle-sidebar'),
    themeToggle: document.getElementById('theme-toggle'),
    newChatBtn: document.getElementById('new-chat-btn'),
    suggestionBtns: document.querySelectorAll('.suggestion-btn'),
    attachBtn: document.getElementById('attach-btn')
};

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    initializeTheme();
    loadChats();
    setupEventListeners();
    setupTextareaAutoResize();
});

// Theme Management
function initializeTheme() {
    if (state.theme === 'dark' || (state.theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.documentElement.classList.add('dark');
        document.getElementById('hljs-theme').href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css';
    } else {
        document.documentElement.classList.remove('dark');
        document.getElementById('hljs-theme').href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css';
    }
}

function toggleTheme() {
    if (document.documentElement.classList.contains('dark')) {
        document.documentElement.classList.remove('dark');
        state.theme = 'light';
        document.getElementById('hljs-theme').href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css';
    } else {
        document.documentElement.classList.add('dark');
        state.theme = 'dark';
        document.getElementById('hljs-theme').href = 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css';
    }
    localStorage.setItem('theme', state.theme);
    feather.replace();
}

// Chat Management
function loadChats() {
    const saved = localStorage.getItem('chats');
    if (saved) {
        state.chats = JSON.parse(saved);
        if (state.chats.length > 0 && !state.currentChatId) {
            loadChat(state.chats[0].id);
        }
    }
    
    if (!state.currentChatId) {
        createNewChat();
    }
    updateSidebar();
}

function saveChats() {
    localStorage.setItem('chats', JSON.stringify(state.chats));
    updateSidebar();
}

function createNewChat() {
    const id = Date.now().toString();
    const chat = {
        id,
        title: 'New Chat',
        messages: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    state.chats.unshift(chat);
    state.currentChatId = id;
    saveChats();
    renderMessages();
    elements.messageInput.focus();
}

function loadChat(id) {
    state.currentChatId = id;
    renderMessages();
    updateSidebar();
    
    // On mobile, close sidebar
    if (window.innerWidth < 1024) {
        elements.sidebar.shadowRoot.querySelector('aside').classList.add('-translate-x-full');
    }
}

function deleteChat(id, event) {
    event.stopPropagation();
    state.chats = state.chats.filter(c => c.id !== id);
    if (state.currentChatId === id) {
        if (state.chats.length > 0) {
            loadChat(state.chats[0].id);
        } else {
            createNewChat();
        }
    }
    saveChats();
}

function updateChatTitle(chatId, firstMessage) {
    const chat = state.chats.find(c => c.id === chatId);
    if (chat && chat.title === 'New Chat') {
        chat.title = firstMessage.slice(0, 30) + (firstMessage.length > 30 ? '...' : '');
        saveChats();
    }
}
// Message Handling
async function sendMessage(content = null) {
    const text = content || elements.messageInput.value.trim();
    if (!text || state.isGenerating) return;

    elements.messageInput.value = '';
    elements.messageInput.style.height = 'auto';
    elements.welcomeScreen?.classList.add('hidden');

    const userMessage = {
        id: Date.now().toString(),
        role: 'user',
        content: text,
        timestamp: new Date().toISOString()
    };

    const chat = state.chats.find(c => c.id === state.currentChatId);
    if (!chat) return;
    
    chat.messages.push(userMessage);
    chat.updatedAt = new Date().toISOString();
    updateChatTitle(state.currentChatId, text);
    saveChats();
    
    renderMessages();
    scrollToBottom();

    // Show typing indicator
    showTypingIndicator();

    try {
        state.isGenerating = true;
        updateSendButton();
        
        // Build conversation context from previous messages
        // Limit to last 10 messages to avoid token limits
        const recentMessages = chat.messages.slice(-10);
        const contextPrompt = buildContextPrompt(recentMessages);
        
        // Use Pollinations AI with context
        // The approach: include context in the system/instruction part of the prompt
        const response = await fetch('https://text.pollinations.ai/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                messages: [
                    {
                        role: "system",
                        content: "You are a helpful AI assistant. You have access to the conversation history and should maintain context throughout the conversation. Be concise but thorough in your responses."
                    },
                    ...recentMessages.slice(0, -1).map(m => ({
                        role: m.role,
                        content: m.content
                    })),
                    {
                        role: "user",
                        content: text
                    }
                ],
                model: "openai-large",
                seed: Math.floor(Math.random() * 1000),
                jsonMode: false
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.text();
        
        hideTypingIndicator();
        
        const assistantMessage = {
            id: (Date.now() + 1).toString(),
            role: 'assistant',
            content: data,
            timestamp: new Date().toISOString()
        };
        
        chat.messages.push(assistantMessage);
        chat.updatedAt = new Date().toISOString();
        saveChats();
        renderMessages();
        scrollToBottom();
        
    } catch (error) {
        console.error('Error:', error);
        hideTypingIndicator();
        showError('Failed to get response. Please try again. Error: ' + error.message);
    } finally {
        state.isGenerating = false;
        updateSendButton();
    }
}

function buildContextPrompt(messages) {
    // This function formats the conversation history for context
    // It's used as a fallback if the API doesn't support message arrays
    let context = "Previous conversation context:\n\n";
    
    for (let i = 0; i < messages.length - 1; i++) {
        const msg = messages[i];
        const role = msg.role === 'user' ? 'User' : 'Assistant';
        context += `${role}: ${msg.content}\n\n`;
    }
    
    const lastMessage = messages[messages.length - 1];
    context += `User: ${lastMessage.content}\n\nAssistant:`;
    
    return context;
}
// Rendering
function renderMessages() {
    const chat = state.chats.find(c => c.id === state.currentChatId);
    if (!chat) return;

    if (chat.messages.length === 0) {
        elements.welcomeScreen?.classList.remove('hidden');
        elements.messagesWrapper.innerHTML = '';
        elements.messagesWrapper.appendChild(elements.welcomeScreen);
        return;
    }

    elements.welcomeScreen?.classList.add('hidden');
    
    // Clear current messages (except welcome screen)
    Array.from(elements.messagesWrapper.children).forEach(child => {
        if (child.id !== 'welcome-screen') {
            child.remove();
        }
    });

    chat.messages.forEach((msg, index) => {
        const msgEl = document.createElement('chat-message');
        msgEl.setAttribute('content', msg.content);
        msgEl.setAttribute('role', msg.role);
        msgEl.setAttribute('timestamp', msg.timestamp);
        msgEl.classList.add('message-enter');
        msgEl.style.animationDelay = `${index * 0.1}s`;
        elements.messagesWrapper.appendChild(msgEl);
    });

    scrollToBottom();
}

function showTypingIndicator() {
    const indicator = document.createElement('typing-indicator');
    indicator.id = 'typing-indicator';
    elements.messagesWrapper.appendChild(indicator);
    scrollToBottom();
}

function hideTypingIndicator() {
    const indicator = document.getElementById('typing-indicator');
    indicator?.remove();
}

function showError(message) {
    const errorEl = document.createElement('div');
    errorEl.className = 'p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl text-red-600 dark:text-red-400 text-center message-enter';
    errorEl.textContent = message;
    elements.messagesWrapper.appendChild(errorEl);
    scrollToBottom();
}

function scrollToBottom() {
    elements.chatContainer.scrollTo({
        top: elements.chatContainer.scrollHeight,
        behavior: 'smooth'
    });
}

function updateSendButton() {
    elements.sendBtn.disabled = state.isGenerating;
    elements.sendBtn.innerHTML = state.isGenerating 
        ? '<div class="typing-dot w-2 h-2 bg-white rounded-full inline-block mx-0.5"></div><div class="typing-dot w-2 h-2 bg-white rounded-full inline-block mx-0.5"></div><div class="typing-dot w-2 h-2 bg-white rounded-full inline-block mx-0.5"></div>'
        : '<i data-feather="send" class="w-5 h-5"></i>';
    feather.replace();
}

function updateSidebar() {
    if (elements.sidebar) {
        elements.sidebar.setAttribute('chats', JSON.stringify(state.chats));
        elements.sidebar.setAttribute('active-chat', state.currentChatId);
    }
}

// Event Listeners
function setupEventListeners() {
    // Send button
    elements.sendBtn.addEventListener('click', () => sendMessage());
    
    // Enter key (Shift+Enter for new line)
    elements.messageInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    // Suggestion buttons
    elements.suggestionBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const text = btn.querySelector('.text-sm').textContent;
            elements.messageInput.value = text;
            sendMessage();
        });
    });

    // Theme toggle
    elements.themeToggle.addEventListener('click', toggleTheme);

    // New chat
    elements.newChatBtn.addEventListener('click', createNewChat);
    // Sidebar toggle (mobile)
    elements.toggleSidebar?.addEventListener('click', () => {
        if (elements.sidebar) {
            elements.sidebar.toggle();
        }
    });
// Attach button (placeholder)
    elements.attachBtn.addEventListener('click', () => {
        alert('File upload coming soon!');
    });

    // Handle sidebar events
    elements.sidebar?.addEventListener('chat-selected', (e) => {
        loadChat(e.detail.chatId);
    });
    
    elements.sidebar?.addEventListener('chat-deleted', (e) => {
        deleteChat(e.detail.chatId, e.detail.event);
    });

    elements.sidebar?.addEventListener('new-chat', () => {
        createNewChat();
    });
}

// Textarea Auto-resize
function setupTextareaAutoResize() {
    const textarea = elements.messageInput;
    
    textarea.addEventListener('input', () => {
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 128) + 'px';
    });
}

// Expose to window for components
window.appState = state;
window.loadChat = loadChat;
window.deleteChat = deleteChat;
window.createNewChat = createNewChat;