File size: 20,276 Bytes
fa929f9
19ba7fe
 
a986b42
 
fa929f9
 
 
 
 
f6543dc
19ba7fe
 
 
 
f6543dc
19ba7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6543dc
 
 
 
 
 
19ba7fe
 
 
 
 
 
 
 
 
f6543dc
112f534
f6543dc
 
112f534
f6543dc
fa929f9
19ba7fe
 
 
fa929f9
19ba7fe
 
 
 
 
 
 
fa929f9
 
 
 
 
19ba7fe
 
 
 
 
fa929f9
 
19ba7fe
fa929f9
19ba7fe
fa929f9
 
 
 
 
 
19ba7fe
fa929f9
19ba7fe
 
 
 
 
 
 
 
 
 
 
 
75ffade
 
19ba7fe
75ffade
 
 
19ba7fe
 
 
 
 
 
75ffade
 
19ba7fe
75ffade
 
 
19ba7fe
 
 
 
7f3fa46
19ba7fe
 
 
 
 
 
 
 
 
 
 
 
 
a986b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ba7fe
a986b42
19ba7fe
 
 
a986b42
 
 
 
 
 
 
 
 
 
 
 
 
 
fa929f9
 
e948fb1
 
 
 
 
a986b42
 
fa929f9
e948fb1
 
a986b42
 
 
fa929f9
a986b42
 
 
fa929f9
 
 
 
 
 
e948fb1
fa929f9
 
 
e948fb1
fa929f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e948fb1
fa929f9
 
 
 
 
 
 
e948fb1
fa929f9
a986b42
e948fb1
a986b42
 
 
 
 
e948fb1
a986b42
 
 
 
 
 
19ba7fe
 
 
 
 
 
 
 
 
 
 
 
401a648
19ba7fe
401a648
 
 
 
 
 
 
 
 
 
 
 
19ba7fe
401a648
 
 
19ba7fe
 
 
401a648
 
 
 
 
 
 
19ba7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75ffade
 
 
19ba7fe
75ffade
 
 
 
7f3fa46
19ba7fe
 
 
7f3fa46
19ba7fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513

// Global Variables
let chatHistory = [];
let currentModel = 'Max';
let isCompactMode = false;
let isConnected = true;
let webSearchEnabled = false;
let isGenerating = false;
let currentTokenCount = 0;
const maxTokens = 4096;
let sidebarCollapsed = false;
// Initialize
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    setupEventListeners();
    initializeSidebarToggle();
});
function initializeApp() {
    // Load chat history from localStorage
    const savedHistory = localStorage.getItem('chatHistory');
    if (savedHistory) {
        chatHistory = JSON.parse(savedHistory);
        renderChatHistory();
    }
    
    // Check connection status
    checkConnectionStatus();
    
    // Initialize tooltips and other UI elements
    initializeTooltips();
}
function setupEventListeners() {
    // Keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + K for clear chat
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            clearChat();
        }
        
        // Escape to close modals
        if (e.key === 'Escape') {
            closeAllModals();
        }
        
        // Ctrl/Cmd + / for help
        if ((e.ctrlKey || e.metaKey) && e.key === '/') {
            e.preventDefault();
            showHelp();
        }
        
        // Ctrl/Cmd + B to toggle sidebar
        if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
            e.preventDefault();
            toggleSidebar();
        }
    });
    
    // Auto-resize textarea
    const messageInput = document.getElementById('messageInput');
    messageInput.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 120) + 'px';
    });
}
function initializeSidebarToggle() {
    console.log('Sidebar is fixed on the left side');
}
function toggleSidebar() {
    console.log('Sidebar is fixed on the left side');
}
function sendMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();
    
    if (!message || !isConnected || isGenerating) return;
    
    // Add user message
    addMessage(message, 'user');
    
    // Clear input
    input.value = '';
    input.style.height = 'auto';
    updateTokenCount('');
    
    // Set generating state
    isGenerating = true;
    handleInput(input);
    
    // Show typing indicator
    showTypingIndicator();
    
    // Simulate AI response
    const responseTime = currentModel === 'Max' ? 2000 : currentModel === 'Turbo' ? 1000 : 500;
    
    setTimeout(() => {
        isGenerating = false;
        hideTypingIndicator();
        handleInput(input);
        
        let response = generateAIResponse(message);
        if (webSearchEnabled) {
            response += '\n\n🔍 *Web araması sonucu: `https://example.com`*';
        }
        addMessage(response, 'ai');
    }, responseTime + Math.random() * 1000);
}
function addMessage(content, sender) {
    const chatContainer = document.getElementById('chatContainer');
    const timestamp = new Date().toLocaleTimeString('en-US', { 
        hour: '2-digit', 
        minute: '2-digit' 
    });
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `flex items-start space-x-3 message-slide-in ${sender === 'user' ? 'flex-row-reverse space-x-reverse' : ''}`;
    if (sender === 'user') {
        messageDiv.innerHTML = `
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-blue-600 to-blue-700 flex items-center justify-center flex-shrink-0 ring-1 ring-blue-600/30 group-hover:ring-blue-500/50 transition-all duration-200">
                <i data-feather="user" class="w-4.5 h-4.5 text-white"></i>
            </div>
            <div class="flex-1 max-w-4xl">
                <div class="bg-gradient-to-br from-zinc-800/80 to-zinc-900/80 backdrop-blur-sm rounded-2xl p-4 border border-zinc-700/50 hover:border-zinc-600/50 transition-all duration-200 shadow-sm shadow-zinc-900/20">
                    <p class="text-white text-sm leading-relaxed break-words">${content}</p>
                </div>
            </div>
        `;
    } else {
        const processedContent = marked.parse(content);
        messageDiv.innerHTML = `
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-zinc-800 to-zinc-900 flex items-center justify-center flex-shrink-0 ring-1 ring-zinc-800/50 group-hover:ring-zinc-700/50 transition-all duration-200">
                <i data-feather="cpu" class="w-4.5 h-4.5 text-zinc-300"></i>
            </div>
            <div class="flex-1 max-w-4xl">
                <div class="bg-gradient-to-br from-zinc-900/60 to-zinc-950/60 backdrop-blur-sm rounded-2xl p-4 border border-zinc-800/50 hover:border-zinc-700/50 transition-all duration-200 shadow-sm shadow-zinc-900/20">
                    <div class="markdown text-white text-sm leading-relaxed">${processedContent}</div>
                </div>
            </div>
        `;
    }
chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
    
    // Re-initialize feather icons for new elements
    feather.replace();
    
    // Save to history
    chatHistory.push({ content, sender, timestamp });
    saveChatHistory();
    
    // Update token count
    updateTokenCount();
}
function generateAIResponse(userMessage) {
    const modelResponses = {
        'Max': [
            "I understand you're asking about: \"" + userMessage + "\". Let me help you with that. Based on my analysis, this involves several key components that we should consider carefully.",
            "That's an interesting question! Here's my comprehensive take on it: " + userMessage + " deserves attention because it touches on important aspects of modern technology and its applications.",
            "Great question! " + userMessage + " is a topic I can elaborate on in depth. From my perspective with the Max model, there are multiple approaches and nuances we should explore.",
            "I appreciate you bringing this up. Regarding " + userMessage + ", I think we should explore the underlying principles and practical implications thoroughly.",
            "This is a fascinating topic! " + userMessage + " connects to broader concepts in technology and innovation. Let me share detailed insights that might help."
        ],
        'Turbo': [
            "Quick analysis on: \"" + userMessage + "\" - Here's what I think: It involves key components worth looking at.",
            "Regarding " + userMessage + " - That's an interesting point worth discussing. Let me break it down for you.",
            "Got it! " + userMessage + " - I can help with that. Here are the main approaches to consider.",
            "About " + userMessage + " - Let me give you a clear perspective on this topic.",
            "Interesting question about " + userMessage + "! Here are some quick insights for you."
        ],
        'Lite': [
            "About: \"" + userMessage + "\" - Here's a brief overview for you.",
            "Regarding " + userMessage + " - Here are the key points to consider.",
            "Quick take on " + userMessage + " - Here's what you need to know.",
            "Brief analysis: " + userMessage + " - Key insights below.",
            "Quick reply about " + userMessage + " - Here are the essentials."
        ],
        'Deep Research': [
            "Let me conduct a deep analysis of: \"" + userMessage + "\". This query warrants comprehensive examination from multiple theoretical and practical frameworks. Based on extensive knowledge synthesis, we can identify several critical dimensions: historical context, current state-of-the-art approaches, potential future developments, and cross-disciplinary implications. The underlying mechanisms deserve careful scrutiny as they relate to broader patterns in technology evolution and cognitive science principles.",
            "Your inquiry about " + userMessage + " represents a sophisticated topic that benefits from deep research methodology. Drawing upon interdisciplinary knowledge domains including computer science, cognitive psychology, and systems theory, I can provide a multifaceted analysis. This exploration should consider not only surface-level implications but also second and third-order effects on ecosystem dynamics, user behavior patterns, and long-term sustainability considerations.",
            "Excellent research question regarding " + userMessage + ". To properly address this, we must examine it through multiple analytical lenses including technical feasibility, economic viability, social impact assessment, and ethical considerations. The complexity of this domain suggests we should also investigate precedent cases, failure modes, success patterns, and emerging trends that might influence future trajectories."
        ]
    };
    
    const responses = modelResponses[currentModel] || modelResponses['Max'];
    return responses[Math.floor(Math.random() * responses.length)];
}

function toggleModelDropdown() {
    const menu = document.getElementById('modelDropdownMenu');
    const arrow = document.getElementById('modelDropdownArrow');
    
    if (menu.classList.contains('hidden')) {
        menu.classList.remove('hidden');
        arrow.style.transform = 'rotate(180deg)';
    } else {
        menu.classList.add('hidden');
        arrow.style.transform = 'rotate(0deg)';
    }
}
function selectModel(model) {
    currentModel = model;
    const selectedText = document.getElementById('selectedModelText');
    const indicator = document.getElementById('modelIndicator');
const modelConfig = {
        'Max': { color: 'white' },
        'Turbo': { color: 'zinc-400' },
        'Lite': { color: 'zinc-500' },
        'Deep Research': { color: 'zinc-300' }
    };
    
    selectedText.textContent = model;
    indicator.className = `w-2 h-2 bg-${modelConfig[model].color} rounded-full`;
// Close dropdown
    document.getElementById('modelDropdownMenu').classList.add('hidden');
    document.getElementById('modelDropdownArrow').style.transform = 'rotate(0deg)';
    
    // Update model status
    updateModelStatus(model);
}

function toggleWebSearch() {
    webSearchEnabled = !webSearchEnabled;
    const toggleCircle = document.getElementById('webSearchToggleCircle');
    const toggleButton = document.getElementById('webSearchToggle');
    if (webSearchEnabled) {
        toggleCircle.style.transform = 'translateX(16px)';
        toggleCircle.classList.add('bg-white');
        toggleCircle.classList.remove('bg-zinc-500');
    } else {
        toggleCircle.style.transform = 'translateX(0)';
        toggleCircle.classList.remove('bg-white');
        toggleCircle.classList.add('bg-zinc-500');
    }
}

function handleInput(textarea) {
    // Auto resize
    textarea.style.height = 'auto';
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
    
    // Update token count
    updateTokenCount(textarea.value);
    
    // Show/hide appropriate buttons
    const sendButton = document.getElementById('sendButton');
    const stopButton = document.getElementById('stopButton');
    
    if (isGenerating) {
        sendButton.classList.add('hidden');
        stopButton.classList.remove('hidden');
    } else {
        sendButton.classList.remove('hidden');
        stopButton.classList.add('hidden');
    }
}

function updateTokenCount(text) {
    if (!text) text = '';
    // Rough estimation: average 1 token per 4 characters
    currentTokenCount = Math.ceil(text.length / 4);
    
    const tokenCountElement = document.getElementById('tokenCount');
    const progressBar = document.getElementById('tokenProgressBar');
    
    tokenCountElement.textContent = `${currentTokenCount} / ${maxTokens} tokens`;
    
    const percentage = Math.min((currentTokenCount / maxTokens) * 100, 100);
    progressBar.style.width = percentage + '%';
    
    // Change color based on percentage
    if (percentage > 80) {
        progressBar.className = 'absolute top-0 left-0 h-full bg-gradient-to-r from-red-500 to-orange-500 rounded-full transition-all duration-300';
    } else if (percentage > 60) {
        progressBar.className = 'absolute top-0 left-0 h-full bg-gradient-to-r from-yellow-500 to-orange-500 rounded-full transition-all duration-300';
    } else {
        progressBar.className = 'absolute top-0 left-0 h-full bg-gradient-to-r from-white to-zinc-400 rounded-full transition-all duration-300';
    }
}

function attachFile() {
    const input = document.createElement('input');
    input.type = 'file';
    input.onchange = e => {
        const file = e.target.files[0];
        if (file) {
            addMessage(`📎 ${file.name} eklendi`, 'user');
            // Handle file upload logic here
        }
    };
    input.click();
}
function showVoiceInput() {
    alert('Voice input coming soon!');
}
function stopGeneration() {
    isGenerating = false;
    hideTypingIndicator();
    handleInput(document.getElementById('messageInput'));
}
function showSettings() {
    alert('Settings page coming soon!');
}
function updateModelStatus(model) {
const responseTimes = {
        'Max': '~1.2s',
        'Turbo': '~0.8s',
        'Lite': '~0.5s',
        'Deep Research': '~2.1s'
    };
const responseElements = document.querySelectorAll('.text-green-400');
    responseElements.forEach(el => {
        if (el.textContent.includes('~')) {
            el.textContent = responseTimes[model];
        }
    });
}
function handleKeyPress(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
}

function autoResize(textarea) {
    textarea.style.height = 'auto';
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
}
function showTypingIndicator() {
    const typingIndicator = document.getElementById('typingIndicator');
    const chatContainer = document.getElementById('chatContainer');
    
    // Remove any existing typing indicator
    if (typingIndicator.parentNode === chatContainer) {
        typingIndicator.remove();
    }
    
    // Add the typing indicator at the end of chat container
    chatContainer.appendChild(typingIndicator);
    typingIndicator.classList.remove('hidden');
    typingIndicator.classList.add('message-slide-in');
    
    // Scroll to bottom to show the indicator
    chatContainer.scrollTop = chatContainer.scrollHeight;
    
    // Re-initialize feather icons for the typing indicator
    feather.replace();
}

function hideTypingIndicator() {
    const typingIndicator = document.getElementById('typingIndicator');
    typingIndicator.classList.add('hidden');
    
    // Remove the typing indicator from DOM when hidden
    if (typingIndicator.parentNode) {
        typingIndicator.remove();
    }
}
function toggleChatMode() {
    isCompactMode = !isCompactMode;
    const chatContainer = document.getElementById('chatContainer');
    const messages = chatContainer.querySelectorAll('.flex');
    
    if (isCompactMode) {
        chatContainer.classList.add('compact');
        messages.forEach(msg => {
            msg.style.marginBottom = '0.5rem';
        });
    } else {
        chatContainer.classList.remove('compact');
        messages.forEach(msg => {
            msg.style.marginBottom = '1rem';
        });
    }
    
    localStorage.setItem('chatMode', isCompactMode ? 'compact' : 'spacious');
}
function clearChat() {
    if (confirm('Are you sure you want to clear the entire chat history?')) {
        const chatContainer = document.getElementById('chatContainer');
        chatContainer.innerHTML = `
            <div class="flex items-start gap-3 message-slide-in group">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-zinc-800 to-zinc-900 flex items-center justify-center flex-shrink-0 ring-1 ring-zinc-800/50 group-hover:ring-zinc-700/50 transition-all duration-200">
                    <i data-feather="cpu" class="w-4.5 h-4.5 text-zinc-300"></i>
                </div>
                <div class="flex-1 max-w-4xl">
                    <div class="bg-gradient-to-br from-zinc-900/60 to-zinc-950/60 backdrop-blur-sm rounded-2xl p-4 border border-zinc-800/50 hover:border-zinc-700/50 transition-all duration-200 shadow-sm shadow-zinc-900/20">
                        <p class="text-white text-sm leading-relaxed">Hello!</p>
                        <p class="text-zinc-400 text-sm mt-2 leading-relaxed">How can I help you today?</p>
                    </div>
                </div>
            </div>
        `;
chatHistory = [];
        saveChatHistory();
        feather.replace();
    }
}

function exportChat() {
    const chatText = chatHistory.map(msg => 
        `[${msg.timestamp}] ${msg.sender === 'user' ? 'You' : 'AI'}: ${msg.content}`
    ).join('\n\n');
    
    const blob = new Blob([chatText], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `neural-nexus-chat-${new Date().toISOString().split('T')[0]}.txt`;
    a.click();
    window.URL.revokeObjectURL(url);
}

function saveChatHistory() {
    localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
}

function renderChatHistory() {
    chatHistory.forEach(msg => {
        addMessage(msg.content, msg.sender);
    });
}

function updateTokenCount() {
    const tokens = chatHistory.reduce((total, msg) => 
        total + msg.content.split(' ').length, 0
    );
    
    const percentage = Math.min((tokens / 10000) * 100, 100);
    const progressBar = document.querySelector('.bg-gradient-to-r');
    if (progressBar) {
        progressBar.style.width = percentage + '%';
    }
    
    const tokenText = document.querySelector('.text-xs.text-zinc-500');
    if (tokenText) {
        tokenText.textContent = `${tokens.toLocaleString()} / 10,000 tokens`;
    }
}

function checkConnectionStatus() {
    // Simulate connection check
    fetch('https://api.openai.com/v1/models')
        .then(() => {
            isConnected = true;
            updateConnectionStatus(true);
        })
        .catch(() => {
            isConnected = false;
            updateConnectionStatus(false);
        });
}

function updateConnectionStatus(connected) {
    const statusElements = document.querySelectorAll('[data-connection-status]');
    statusElements.forEach(el => {
        el.textContent = connected ? 'Online' : 'Offline';
        el.className = connected ? 'text-green-400' : 'text-red-400';
    });
}

function initializeTooltips() {
    // Add hover tooltips for icons
    const tooltipElements = document.querySelectorAll('[data-tooltip]');
    tooltipElements.forEach(el => {
        el.addEventListener('mouseenter', function(e) {
            const tooltip = document.createElement('div');
            tooltip.className = 'absolute bg-zinc-800 text-white text-xs rounded px-2 py-1 z-50';
            tooltip.textContent = this.dataset.tooltip;
            tooltip.style.top = (e.clientY - 30) + 'px';
            tooltip.style.left = e.clientX + 'px';
            document.body.appendChild(tooltip);
            
            this.addEventListener('mouseleave', function() {
                tooltip.remove();
            }, { once: true });
        });
    });
}

function closeAllModals() {
    // Close any open modals or dropdowns
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => modal.classList.add('hidden'));
}

function showHelp() {
    const helpContent = `
Available Commands:
/help - Show this help message
/clear - Clear chat history
/export - Export chat as text file
/compact - Toggle compact mode

Keyboard Shortcuts:
Ctrl+K - Clear chat
Ctrl+/ - Show help
Tab - Auto-complete
    `;
    
    addMessage(helpContent, 'ai');
}

// Simulate real-time updates
setInterval(() => {
    // Update random metrics
    const responseTime = (0.5 + Math.random() * 0.8).toFixed(1);
    const responseElements = document.querySelectorAll('.text-green-400');
    responseElements.forEach(el => {
        if (el.textContent.includes('~')) {
            el.textContent = `~${responseTime}s`;
        }
    });
}, 5000);