File size: 29,179 Bytes
e3c44fe
26671c2
 
 
 
 
 
 
e3c44fe
 
26671c2
 
e3c44fe
 
 
26671c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3c44fe
 
 
26671c2
 
e3c44fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26671c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3c44fe
26671c2
 
 
e3c44fe
 
 
 
 
 
 
 
006d494
26671c2
 
006d494
26671c2
e3c44fe
006d494
26671c2
 
006d494
26671c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
006d494
26671c2
 
006d494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26671c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
006d494
 
26671c2
 
 
 
 
 
 
006d494
26671c2
 
006d494
 
26671c2
 
006d494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26671c2
 
 
006d494
 
 
 
 
 
 
 
 
26671c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3c44fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26671c2
e3c44fe
 
26671c2
 
e3c44fe
 
 
 
 
 
 
26671c2
 
 
e3c44fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26671c2
e3c44fe
26671c2
 
e3c44fe
 
 
 
 
26671c2
 
e3c44fe
 
 
 
 
 
 
 
 
 
26671c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3c44fe
 
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818

// State management
const state = {
    currentTab: 'chat',
    messages: [],
    knowledge: JSON.parse(localStorage.getItem('nexusKnowledge')) || [],
    user: JSON.parse(localStorage.getItem('nexusUser')) || null,
    webSearchEnabled: true,
    currentFilter: 'all',
    registeredUsers: JSON.parse(localStorage.getItem('nexusRegisteredUsers')) || {}
};

// Make state globally accessible
window.state = state;
window.APIs = APIs;
// API configurations
const APIs = {
    search: {
        // Using DuckDuckGo HTML search as a free alternative
        duckduckgo: 'https://html.duckduckgo.com/html/?q='
    },
    facts: 'https://uselessfacts.jsph.pl/api/v2/facts/random',
    quotes: 'https://api.quotable.io/random'
};
// Initialize
document.addEventListener('DOMContentLoaded', () => {
    loadKnowledge();
    updateUI();
    setupEventListeners();
    feather.replace();
    
    // Execute any saved custom code
    executeCustomCode();
});

// Execute custom user code
function executeCustomCode() {
    const customCode = localStorage.getItem('nexusCustomCode');
    if (customCode && customCode.trim()) {
        try {
            console.log('📝 Executing custom code...');
            new Function('state', 'brainDB', 'APIs', customCode)(
                window.state, 
                window.brainDB, 
                window.APIs
            );
            console.log('✅ Custom code executed');
        } catch (error) {
            console.error('❌ Error in custom code:', error);
        }
    }
}
// Event Listeners
function setupEventListeners() {
    // Chat input enter key
    document.getElementById('chat-input')?.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    // Web search toggle
    document.getElementById('web-search-toggle')?.addEventListener('change', (e) => {
        state.webSearchEnabled = e.target.checked;
    });
}

// Tab switching
function switchTab(tab) {
    state.currentTab = tab;
    
    // Hide all tabs
    ['chat', 'learn', 'memory'].forEach(t => {
        document.getElementById(`tab-${t}`).classList.add('hidden');
        const nav = document.getElementById(`nav-${t}`);
        nav?.classList.remove('bg-primary/20', 'text-primary', 'border', 'border-primary/30');
        nav?.classList.add('text-gray-400');
    });
    
    // Show active tab
    document.getElementById(`tab-${tab}`).classList.remove('hidden');
    const activeNav = document.getElementById(`nav-${tab}`);
    activeNav?.classList.remove('text-gray-400');
    activeNav?.classList.add('bg-primary/20', 'text-primary', 'border', 'border-primary/30');
    
    // Refresh feather icons
    feather.replace();
}

// Quick question buttons
function quickQuestion(question) {
    document.getElementById('chat-input').value = question;
    sendMessage();
}

// Send message to AI
async function sendMessage() {
    const input = document.getElementById('chat-input');
    const message = input.value.trim();
    
    if (!message) return;
    
    // Clear input
    input.value = '';
    
    // Add user message
    addMessage('user', message);
    
    // Show typing indicator
    showTyping();
    
    // Generate response
    const response = await generateResponse(message);
    
    // Remove typing and add response
    hideTyping();
    addMessage('ai', response);
    
    // Save to history
    state.messages.push({ role: 'user', content: message });
    state.messages.push({ role: 'ai', content: response });
}

// Add message to chat
function addMessage(role, content, isHTML = false) {
    const container = document.getElementById('chat-messages');
    const div = document.createElement('div');
    div.className = 'flex gap-3 message-enter';
    
    const isUser = role === 'user';
    const avatarClass = isUser 
        ? 'bg-gray-600 order-2' 
        : 'bg-gradient-to-br from-primary to-secondary';
    const messageClass = isUser 
        ? 'bg-primary/20 rounded-2xl rounded-tr-sm ml-auto border border-primary/20' 
        : 'bg-dark/80 rounded-2xl rounded-tl-sm border border-white/5';
    
    const icon = isUser ? 'user' : 'bot';
    
    div.innerHTML = `
        <div class="w-10 h-10 rounded-xl ${avatarClass} flex items-center justify-center shrink-0 ${isUser ? '' : 'order-1'}">
            <i data-feather="${icon}" class="w-5 h-5 text-white"></i>
        </div>
        <div class="${messageClass} p-4 max-w-[80%] ${isUser ? 'order-1' : ''}">
            ${isHTML ? content : `<p class="text-gray-300">${escapeHtml(content)}</p>`}
        </div>
    `;
    
    container.appendChild(div);
    container.scrollTop = container.scrollHeight;
    feather.replace();
}

// Show typing indicator
function showTyping() {
    const container = document.getElementById('chat-messages');
    const div = document.createElement('div');
    div.id = 'typing-indicator';
    div.className = 'flex gap-3';
    div.innerHTML = `
        <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-secondary flex items-center justify-center shrink-0">
            <i data-feather="bot" class="w-5 h-5 text-white"></i>
        </div>
        <div class="bg-dark/80 rounded-2xl rounded-tl-sm p-4 border border-white/5 flex items-center gap-1">
            <span class="typing-dot"></span>
            <span class="typing-dot"></span>
            <span class="typing-dot"></span>
        </div>
    `;
    container.appendChild(div);
    container.scrollTop = container.scrollHeight;
}

// Hide typing indicator
function hideTyping() {
    const typing = document.getElementById('typing-indicator');
    if (typing) typing.remove();
}
// Generate AI response with Brain Database integration
async function generateResponse(message) {
    const lowerMsg = message.toLowerCase();
    
    // First, try brain database for natural conversation
    if (window.brainDB) {
        const brainResponse = window.brainDB.generateResponse(message, state.knowledge);
        // If it's a conversational response (not a fallback), use it
        if (brainResponse && !brainResponse.includes("interesting! Tell me more")) {
            return brainResponse;
        }
    }
// Check for knowledge-based responses
    const knowledgeResponse = findKnowledgeResponse(message);
    if (knowledgeResponse && isAskingAboutKnowledge(message)) {
        return formulateKnowledgeResponse(knowledgeResponse, message);
    }
// Teaching command detection
    if (lowerMsg.includes('what did i teach you') || lowerMsg.includes('what do you know about me') || lowerMsg.includes('what do you remember')) {
        return generateKnowledgeSummary();
    }
// Web search for factual queries
    if (state.webSearchEnabled && needsWebSearch(message)) {
        const searchResults = await performWebSearch(message);
        if (searchResults) {
            return formatSearchResults(searchResults, message);
        }
    }
    
    // Check for specific query types
    if (lowerMsg.includes('hello') || lowerMsg.includes('hi')) {
        return `Hello! I'm Nexus, your AI learning companion. I know ${state.knowledge.length} things about you so far. How can I help you today?`;
    }
    
    if (lowerMsg.includes('weather')) {
        const city = extractCity(message) || 'your location';
        return `I don't have real-time weather data, but I can help you find weather information. Try asking me to search for "weather in ${city}" with web search enabled, or teach me your preferred weather service!`;
    }
    
    if (lowerMsg.includes('time') || lowerMsg.includes('date')) {
        const now = new Date();
        return `Current time: ${now.toLocaleString()}. I remember this conversation, so if you teach me about your schedule or preferences, I can help you better!`;
    }
    
    if (lowerMsg.includes('joke')) {
        try {
            const fact = await fetchRandomFact();
            return `Here's something interesting: ${fact}`;
        } catch {
            return `Why did the AI go to school? To improve its learning algorithms! 🎓`;
        }
    }
    
    // Default intelligent response
    return generateContextualResponse(message);
}
// Find knowledge-based response
function findKnowledgeResponse(query) {
    const relevant = state.knowledge.filter(k => {
        const topicWords = k.topic.toLowerCase().split(/\s+/);
        const contentWords = k.content.toLowerCase().split(/\s+/);
        const queryWords = query.toLowerCase().split(/\s+/);
        
        return topicWords.some(tw => queryWords.some(qw => qw.includes(tw) || tw.includes(qw))) ||
               contentWords.some(cw => queryWords.some(qw => qw.includes(cw) || cw.includes(qw)));
    });
    
    if (relevant.length === 0) return null;
    
    // Sort by relevance (most words matched)
    relevant.sort((a, b) => {
        const aScore = scoreRelevance(a, query);
        const bScore = scoreRelevance(b, query);
        return bScore - aScore;
    });
    
    return relevant[0];
}

// Formulate natural knowledge responses
function formulateKnowledgeResponse(knowledge, query) {
    const content = knowledge.content;
    const topic = knowledge.topic;
    
    // Detect content type to choose appropriate phrasing
    const isMath = /[\d+\-*/=]/.test(content) && /[=+\-*/]/.test(content);
    const isFact = content.includes("is a") || content.includes("are a") || content.includes("was a");
    const isPreference = /like|love|prefer|favorite|hate|dislike/.test(content.toLowerCase());
    const isInstruction = /should|must|need to|have to/.test(content.toLowerCase());
    
    // Natural phrasing templates based on content type
    const mathTemplates = [
        `From my understanding, ${content}.`,
        `Based on what I've learned, ${content}.`,
        `I understand that ${content}.`,
        `Mathematically speaking, ${content}.`,
        `The way I see it: ${content}.`
    ];
    
    const factTemplates = [
        `I recall that ${content}.`,
        `According to my knowledge, ${content}.`,
        `I understand that ${content}.`,
        `From what I've gathered: ${content}.`,
        `I know that ${content}.`
    ];
    
    const preferenceTemplates = [
        `I remember that you ${content.toLowerCase().replace('i ', 'you ').replace('my ', 'your ')}.`,
        `Based on what you've shared, you ${content.toLowerCase().replace('i ', 'you ').replace('my ', 'your ')}.`,
        `I understand that ${content.toLowerCase().replace('i ', 'you ').replace('my ', 'your ')}.`,
        `From my memory: you ${content.toLowerCase().replace('i ', 'you ').replace('my ', 'your ')}.`
    ];
    
    const generalTemplates = [
        `Based on my knowledge, ${content}.`,
        `From what I've learned: ${content}.`,
        `I understand that ${content}.`,
        `According to what you've taught me: ${content}.`,
        `I recall that ${content}.`,
        `The way I understand it: ${content}.`,
        `I've learned that ${content}.`
    ];
    
    // Select template array based on content type
    let templates = generalTemplates;
    if (isMath) templates = mathTemplates;
    else if (isPreference) templates = preferenceTemplates;
    else if (isFact) templates = factTemplates;
    
    // Pick random template for variety
    const template = templates[Math.floor(Math.random() * templates.length)];
    
    // Add context clue for topic if relevant
    const queryAboutTopic = query.toLowerCase().includes(topic.toLowerCase());
    if (queryAboutTopic && !template.includes(topic)) {
        return `${template} (regarding ${topic})`;
    }
    
    return template;
}
// Score knowledge relevance
function scoreRelevance(knowledge, query) {
    const queryWords = query.toLowerCase().split(/\s+/);
    const topicWords = knowledge.topic.toLowerCase().split(/\s+/);
    const contentWords = knowledge.content.toLowerCase().split(/\s+/);
    
    let score = 0;
    queryWords.forEach(qw => {
        if (topicWords.some(tw => tw.includes(qw) || qw.includes(tw))) score += 2;
        if (contentWords.some(cw => cw.includes(qw) || qw.includes(cw))) score += 1;
    });
    
    return score;
}
// Check if asking about knowledge
function isAskingAboutKnowledge(message) {
    const questionWords = ['what', 'who', 'where', 'when', 'why', 'how', 'do you know', 'tell me about', 'remember', 'is it true', 'can you', 'does', 'is'];
    return questionWords.some(w => message.toLowerCase().includes(w)) || message.includes('?');
}
// Generate knowledge summary
function generateKnowledgeSummary() {
    if (state.knowledge.length === 0) {
        return "You haven't taught me anything yet! Go to the 'Teach Me' tab to share your knowledge with me.";
    }
    
    // Group by category and create natural summaries
    const byCategory = {};
    state.knowledge.forEach(k => {
        if (!byCategory[k.category]) byCategory[k.category] = [];
        byCategory[k.category].push(k);
    });
    
    // Create natural language summary
    const intros = [
        `I've absorbed ${state.knowledge.length} pieces of knowledge from our conversations.`,
        `So far, I've learned ${state.knowledge.length} things about you and your world.`,
        `My understanding has grown to include ${state.knowledge.length} facts you've shared.`
    ];
    
    let summary = intros[Math.floor(Math.random() * intros.length)] + "\n\n";
    
    Object.entries(byCategory).forEach(([cat, items]) => {
        if (cat && cat !== 'undefined' && cat !== 'general') {
            summary += `**Regarding ${cat.charAt(0).toUpperCase() + cat.slice(1)}**:\n`;
            items.forEach(item => {
                // Summarize naturally based on content length
                if (item.content.length < 50) {
                    summary += `• ${item.content}\n`;
                } else {
                    summary += `• ${item.topic}: ${item.content.substring(0, 50)}...\n`;
                }
            });
            summary += '\n';
        }
    });
    
    // Add uncategorized if any
    const general = byCategory['general'] || byCategory['undefined'] || [];
    if (general.length > 0) {
        summary += `**General knowledge**:\n`;
        general.forEach(item => {
            summary += `• ${item.content}\n`;
        });
    }
    
    return summary;
}
// Perform web search
async function performWebSearch(query) {
    try {
        // Using a search API simulation with timeout
        // In production, you'd use a real search API like SerpAPI, Google Custom Search, etc.
        
        // Simulate search delay
        await new Promise(r => setTimeout(r, 1000));
        
        // Generate contextual search response based on query
        const searchData = simulateSearchResults(query);
        return searchData;
    } catch (error) {
        console.error('Search error:', error);
        return null;
    }
}

// Simulate search results (in production, replace with real API)
function simulateSearchResults(query) {
    const lowerQ = query.toLowerCase();
    
    // Predefined responses for common queries
    const responses = {
        'ai news': {
            title: `Latest AI Developments - ${new Date().toLocaleDateString()}`,
            snippets: [
                "AI models continue to advance with multimodal capabilities",
                "New regulations being discussed for AI safety",
                "Open source AI models gaining traction in enterprise",
                "AI assistants becoming more personalized and contextual"
            ],
            source: 'Simulated Web Search'
        },
        'what can you do': {
            title: "Nexus AI Capabilities",
            snippets: [
                "Search the web for real-time information",
                "Learn and remember personal facts and preferences",
                "Answer questions using accumulated knowledge",
                "Maintain context across conversations"
            ],
            source: 'Nexus System'
        }
    };
    
    // Find matching response or generate generic
    for (const [key, value] of Object.entries(responses)) {
        if (lowerQ.includes(key)) return value;
    }
    
    // Generic response
    return {
        title: `Search results for "${query}"`,
        snippets: [
            `Found relevant information about ${query}`,
            "Multiple sources confirm this information",
            "Related topics include technology, science, and current events"
        ],
        source: 'Web Search'
    };
}

// Format search results
function formatSearchResults(results, originalQuery) {
    let html = `<div class="search-result"><p class="font-semibold text-white mb-2">${results.title}</p>`;
    results.snippets.forEach(s => {
        html += `<p class="text-gray-300 text-sm mb-1">• ${s}</p>`;
    });
    html += `<span class="search-source"><i data-feather="external-link" class="w-3 h-3"></i>Source: ${results.source}</span></div>`;
    html += `<p class="mt-3 text-gray-300">Would you like me to remember any of this information? Just tell me in the "Teach Me" tab!</p>`;
    
    return html;
}

// Determine if web search is needed
function needsWebSearch(message) {
    const needsSearch = [
        /latest|news|current|today|recent/i,
        /weather|stock|price|score/i,
        /who is|what is|where is|when did/i
    ];
    
    // Skip if it's clearly about personal knowledge
    if (message.toLowerCase().includes('you know') || 
        message.toLowerCase().includes('i told you') ||
        message.toLowerCase().includes('about me')) {
        return false;
    }
    
    return needsSearch.some(pattern => pattern.test(message));
}

// Generate contextual response
function generateContextualResponse(message) {
    const responses = [
        `That's an interesting question about "${message.substring(0, 30)}${message.length > 30 ? '...' : ''}". `,
        `I'd be happy to help with that. `,
        `Let me think about "${message.substring(0, 25)}${message.length > 25 ? '...' : ''}"... `
    ];
    
    const base = responses[Math.floor(Math.random() * responses.length)];
    
    if (state.knowledge.length > 0) {
        return base + `Based on our conversations and what you've taught me, I can tell you that I'm continuously learning from you. Currently, I know ${state.knowledge.length} facts that help me understand you better. For specific details, I can search the web or you can teach me more!`;
    }
    
    return base + `I'm Nexus, your AI learning companion. I can search the web for current information, and you can teach me personal facts in the "Teach Me" tab. The more you share, the better I can assist you! What would you like to know or teach me?`;
}

// Fetch random fact
async function fetchRandomFact() {
    try {
        const response = await fetch('https://uselessfacts.jsph.pl/api/v2/facts/random');
        const data = await response.json();
        return data.text;
    } catch {
        throw new Error('Failed to fetch fact');
    }
}

// Extract city from message
function extractCity(message) {
    const match = message.match(/(?:in|at|for)\s+([A-Za-z\s]+?)(?:\?|$|\.)/i);
    return match ? match[1].trim() : null;
}

// Teach AI something new
function teachAI() {
    const topic = document.getElementById('learn-topic').value.trim();
    const content = document.getElementById('learn-content').value.trim();
    const category = document.getElementById('selected-category').value || 'general';
    
    if (!topic || !content) {
        alert('Please fill in both the topic and what I should learn!');
        return;
    }
    
    const knowledge = {
        id: Date.now(),
        topic,
        content,
        category,
        timestamp: new Date().toISOString()
    };
    
    state.knowledge.push(knowledge);
    saveKnowledge();
    
    // Show success
    const successDiv = document.getElementById('learn-success');
    successDiv.classList.remove('hidden');
    successDiv.classList.add('animate-fade-in');
    
    // Clear form
    document.getElementById('learn-topic').value = '';
    document.getElementById('learn-content').value = '';
    document.getElementById('selected-category').value = '';
    document.querySelectorAll('.category-btn').forEach(btn => btn.classList.remove('active'));
    
    // Update UI
    updateMemoryDisplay();
    updateLearnBadge();
    
    // Hide success after delay
    setTimeout(() => {
        successDiv.classList.add('hidden');
    }, 4000);
}

// Select category
function selectCategory(category) {
    document.getElementById('selected-category').value = category;
    document.querySelectorAll('.category-btn').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.category === category);
    });
}

// Filter memory
function filterMemory(filter) {
    state.currentFilter = filter;
    
    document.querySelectorAll('.memory-filter').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.filter === filter);
        if (btn.dataset.filter === filter) {
            btn.classList.remove('text-gray-400', 'hover:bg-white/5');
            btn.classList.add('bg-primary/20', 'text-primary');
        } else {
            btn.classList.add('text-gray-400', 'hover:bg-white/5');
            btn.classList.remove('bg-primary/20', 'text-primary');
        }
    });
    
    updateMemoryDisplay();
}

// Update memory display
function updateMemoryDisplay() {
    const list = document.getElementById('memory-list');
    const count = document.getElementById('memory-count');
    
    const filtered = state.currentFilter === 'all' 
        ? state.knowledge 
        : state.knowledge.filter(k => k.category === state.currentFilter);
    
    count.textContent = state.knowledge.length;
    
    if (filtered.length === 0) {
        list.innerHTML = `
            <div class="text-center py-12 text-gray-500">
                <i data-feather="inbox" class="w-12 h-12 mx-auto mb-3 opacity-50"></i>
                <p>No knowledge in this category yet.</p>
            </div>
        `;
        feather.replace();
        return;
    }
    
    list.innerHTML = filtered.map(item => `
        <div class="memory-card bg-dark/50 rounded-xl p-4 border border-white/10">
            <div class="flex items-start justify-between mb-2">
                <div>
                    <span class="text-xs uppercase tracking-wide text-secondary font-medium">${item.category || 'general'}</span>
                    <h3 class="font-semibold text-white">${escapeHtml(item.topic)}</h3>
                </div>
                <button onclick="deleteKnowledge(${item.id})" class="text-gray-500 hover:text-red-400 transition-colors">
                    <i data-feather="trash-2" class="w-4 h-4"></i>
                </button>
            </div>
            <p class="text-gray-400 text-sm">${escapeHtml(item.content)}</p>
            <p class="text-gray-600 text-xs mt-2">${new Date(item.timestamp).toLocaleDateString()}</p>
        </div>
    `).join('');
    
    feather.replace();
}

// Delete knowledge
function deleteKnowledge(id) {
    if (!confirm('Forget this information?')) return;
    
    state.knowledge = state.knowledge.filter(k => k.id !== id);
    saveKnowledge();
    updateMemoryDisplay();
    updateLearnBadge();
}

// Update learn badge
function updateLearnBadge() {
    const badge = document.getElementById('learn-badge');
    if (state.knowledge.length > 0) {
        badge.classList.remove('hidden');
        badge.textContent = state.knowledge.length;
    } else {
        badge.classList.add('hidden');
    }
}

// Save knowledge to localStorage
function saveKnowledge() {
    localStorage.setItem('nexusKnowledge', JSON.stringify(state.knowledge));
}

// Load knowledge
function loadKnowledge() {
    updateMemoryDisplay();
    updateLearnBadge();
}

// Clear chat
function clearChat() {
    if (!confirm('Clear this conversation?')) return;
    
    document.getElementById('chat-messages').innerHTML = `
        <div class="flex gap-3">
            <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-secondary flex items-center justify-center shrink-0">
                <i data-feather="bot" class="w-5 h-5 text-white"></i>
            </div>
            <div class="bg-dark/80 rounded-2xl rounded-tl-sm p-4 max-w-[80%] border border-white/5">
                <p class="text-gray-300">Hello! I'm Nexus, your AI learning companion. I can search the web for answers and use what you've taught me to help you better. What would you like to know?</p>
            </div>
        </div>
    `;
    state.messages = [];
    feather.replace();
}

// Authentication functions
function openAuthModal(mode = 'login') {
    const modal = document.getElementById('auth-modal');
    modal.classList.remove('hidden');
    modal.querySelector('custom-auth-modal').setAttribute('mode', mode);
}

function closeAuthModal() {
    document.getElementById('auth-modal').classList.add('hidden');
}
function login(email, password) {
    // Check if user exists
    const users = JSON.parse(localStorage.getItem('nexusRegisteredUsers') || '{}');
    const user = users[email.toLowerCase()];
    
    if (!user) {
        alert('Account not found. Please sign up first.');
        // Switch to signup mode
        const modal = document.querySelector('custom-auth-modal');
        if (modal) modal.setMode('signup');
        return;
    }
    
    // Verify password (in production, use bcrypt)
    if (user.password !== hashPassword(password)) {
        alert('Incorrect password. Please try again.');
        return;
    }
    
    // Successful login
    state.user = { 
        email: email.toLowerCase(), 
        name: user.name,
        loginTime: new Date().toISOString()
    };
    localStorage.setItem('nexusUser', JSON.stringify(state.user));
    localStorage.setItem('nexusLastLogin', new Date().toISOString());
    
    updateUI();
    closeAuthModal();
    
    // Welcome back message if returning
    if (state.knowledge.length > 0) {
        setTimeout(() => {
            addMessage('ai', `Welcome back, ${user.name}! I remember everything you taught me—${state.knowledge.length} facts so far. Ready to continue learning together?`);
        }, 500);
    }
}

function signup(name, email, password) {
    const emailLower = email.toLowerCase();
    
    // Get existing users
    let users = JSON.parse(localStorage.getItem('nexusRegisteredUsers') || '{}');
    
    // Check if email already exists
    if (users[emailLower]) {
        alert('An account with this email already exists. Please log in instead.');
        // Switch to login mode
        const modal = document.querySelector('custom-auth-modal');
        if (modal) modal.setMode('login');
        return;
    }
    
    // Validate password strength
    if (password.length < 6) {
        alert('Password must be at least 6 characters long.');
        return;
    }
    
    // Create new user
    users[emailLower] = {
        name: name,
        email: emailLower,
        password: hashPassword(password), // Simple hash
        createdAt: new Date().toISOString(),
        lastLogin: new Date().toISOString()
    };
    
    localStorage.setItem('nexusRegisteredUsers', JSON.stringify(users));
    
    // Auto login
    state.user = { 
        email: emailLower, 
        name: name,
        loginTime: new Date().toISOString()
    };
    localStorage.setItem('nexusUser', JSON.stringify(state.user));
    
    updateUI();
    closeAuthModal();
    
    // Welcome message
    setTimeout(() => {
        addMessage('ai', `Welcome to ChromaMind Nexus, ${name}! 🎉 I'm excited to learn with you. Feel free to start a conversation, teach me something new, or try the code editor to customize me!`);
    }, 500);
}

// Simple password hashing (in production, use bcrypt)
function hashPassword(password) {
    let hash = 0;
    for (let i = 0; i < password.length; i++) {
        const char = password.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash;
    }
    return 'hash_' + Math.abs(hash).toString(16);
}
function logout() {
    state.user = null;
    localStorage.removeItem('nexusUser');
    updateUI();
}

function updateUI() {
    // Update navbar with user state
    const navbar = document.querySelector('custom-navbar');
    if (navbar && state.user) {
        navbar.setAttribute('user', JSON.stringify(state.user));
    }
}

// Utility functions
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
// Global scope helpers for onclick handlers
window.switchTab = switchTab;
window.quickQuestion = quickQuestion;
window.sendMessage = sendMessage;
window.teachAI = teachAI;
window.selectCategory = selectCategory;
window.filterMemory = filterMemory;
window.deleteKnowledge = deleteKnowledge;
window.clearChat = clearChat;
window.openAuthModal = openAuthModal;
window.closeAuthModal = closeAuthModal;
window.login = login;
window.signup = signup;
window.logout = logout;
window.executeCustomCode = executeCustomCode;