// 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 = `
${isHTML ? content : `

${escapeHtml(content)}

`}
`; 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 = `
`; 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 = `

${results.title}

`; results.snippets.forEach(s => { html += `

β€’ ${s}

`; }); html += `Source: ${results.source}
`; html += `

Would you like me to remember any of this information? Just tell me in the "Teach Me" tab!

`; 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 = `

No knowledge in this category yet.

`; feather.replace(); return; } list.innerHTML = filtered.map(item => `
${item.category || 'general'}

${escapeHtml(item.topic)}

${escapeHtml(item.content)}

${new Date(item.timestamp).toLocaleDateString()}

`).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 = `

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?

`; 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;