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 (
Intelligent conversations, always at your service
Demo accounts:
Username: user1, Password: password123
Username: user2, Password: password456
{conversation.preview || 'New conversation'}
{currentUser?.name}
@{currentUser?.username}
{msg.text}
{formatTime(msg.created_at)}
Choose an existing conversation or create a new one to get started