import React, { useState, useEffect, useRef } from 'react'; import { MessageCircle, User, Send, Plus, LogOut, Menu, X, Bot } from 'lucide-react'; const App = () => { const [isLoggedIn, setIsLoggedIn] = useState(false); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [currentUser, setCurrentUser] = useState(null); const [conversations, setConversations] = useState([]); const [activeConversation, setActiveConversation] = useState(null); const [message, setMessage] = useState(''); const [isMenuOpen, setIsMenuOpen] = useState(false); const [loading, setLoading] = useState(false); const messagesEndRef = useRef(null); // API base URL const API_BASE = 'http://localhost:5100/api'; // Auto scroll to bottom of messages useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [activeConversation?.messages]); // Fetch user conversations const fetchConversations = async (userId) => { try { const response = await fetch(`${API_BASE}/users/${userId}/conversations`); if (response.ok) { const data = await response.json(); setConversations(data); if (data.length > 0 && !activeConversation) { // Load the first conversation loadConversation(data[0].id); } } } catch (error) { console.error('Error fetching conversations:', error); } }; // Load conversation details const loadConversation = async (conversationId) => { try { const response = await fetch(`${API_BASE}/conversations/${conversationId}`); if (response.ok) { const data = await response.json(); setActiveConversation(data); } } catch (error) { console.error('Error loading conversation:', error); } }; // Login function const handleLogin = async (e) => { e.preventDefault(); setLoading(true); try { const response = await fetch(`${API_BASE}/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username, password }), }); if (response.ok) { const userData = await response.json(); setCurrentUser(userData); setIsLoggedIn(true); await fetchConversations(userData.id); } else { const errorData = await response.json(); alert(errorData.error || 'Login failed'); } } catch (error) { console.error('Login error:', error); alert('Network error. Please try again.'); } finally { setLoading(false); } }; // Logout function const handleLogout = () => { setIsLoggedIn(false); setCurrentUser(null); setUsername(''); setPassword(''); setConversations([]); setActiveConversation(null); setIsMenuOpen(false); }; // Create new conversation const createNewConversation = async () => { if (!currentUser) return; setLoading(true); try { const response = await fetch(`${API_BASE}/users/${currentUser.id}/conversations`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: 'New Conversation' }), }); if (response.ok) { const newConversation = await response.json(); setConversations(prev => [newConversation, ...prev]); await loadConversation(newConversation.id); } } catch (error) { console.error('Error creating conversation:', error); } finally { setLoading(false); setIsMenuOpen(false); } }; // Send message const sendMessage = async () => { if (!message.trim() || !activeConversation) return; setLoading(true); try { // Send user message const userMessageResponse = await fetch(`${API_BASE}/conversations/${activeConversation.id}/messages`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text: message, sender: 'user' }), }); if (userMessageResponse.ok) { const userMessage = await userMessageResponse.json(); // Update UI with user message const updatedConversation = { ...activeConversation, messages: [...activeConversation.messages, userMessage], title: activeConversation.messages.length === 1 ? message.slice(0, 20) + (message.length > 20 ? '...' : '') : activeConversation.title }; setActiveConversation(updatedConversation); setMessage(''); // Fetch updated conversation to get AI response await loadConversation(activeConversation.id); } } catch (error) { console.error('Error sending message:', error); } finally { setLoading(false); } }; // Format timestamp const formatTime = (timestamp) => { return new Date(timestamp).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }); }; // Login Page if (!isLoggedIn) { return (

AI Assistant

Intelligent conversations, always at your service

setUsername(e.target.value)} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all" placeholder="Enter username" required />
setPassword(e.target.value)} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all" placeholder="Enter password" required />

Demo accounts:

Username: user1, Password: password123

Username: user2, Password: password456

); } // Main App return (
{/* Header */}

AI Assistant

{/* Sidebar */} {isMenuOpen && (
setIsMenuOpen(false)} />

Conversations

{conversations.map((conversation) => (
{ loadConversation(conversation.id); setIsMenuOpen(false); }} className={`p-4 border-b border-gray-100 cursor-pointer hover:bg-gray-50 transition-colors ${ activeConversation?.id === conversation.id ? 'bg-indigo-50 border-l-4 border-l-indigo-500' : '' }`} >

{conversation.title}

{conversation.preview || 'New conversation'}

))}

{currentUser?.name}

@{currentUser?.username}

)} {/* Main Chat Area */}
{activeConversation ? ( <> {/* Chat Header */}

{activeConversation.title}

{/* Messages */}
{activeConversation.messages.map((msg) => (

{msg.text}

{formatTime(msg.created_at)}

))}
{/* Input Area */}
setMessage(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && !loading && sendMessage()} disabled={loading} className="flex-1 px-4 py-3 border border-gray-300 rounded-full focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all disabled:opacity-50" placeholder="Type a message..." />
) : (

Select or Create a Conversation

Choose an existing conversation or create a new one to get started

)}
); }; export default App;