import { useState, useEffect, useRef } from 'react'; import { Send, User, Bot } from 'lucide-react'; import { API_URL } from '../config'; interface Message { id: string; clientId: string; content: string; isFromStaff: boolean; createdAt: string; readAt: string | null; } export default function Messages() { const [messages, setMessages] = useState([]); const [clientId, setClientId] = useState(''); const [newMessage, setNewMessage] = useState(''); const [loading, setLoading] = useState(false); const messagesEndRef = useRef(null); const staffId = 'staff-1'; // In production, this would come from auth useEffect(() => { if (clientId) fetchMessages(); }, [clientId]); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); const fetchMessages = async () => { setLoading(true); try { const res = await fetch(`${API_URL}/messages/conversation/${clientId}?staffId=${staffId}`); const data = await res.json(); setMessages(data || []); } catch (err) { console.error('Failed to fetch messages:', err); } finally { setLoading(false); } }; const handleSend = async () => { if (!newMessage.trim() || !clientId) return; try { const res = await fetch(`${API_URL}/ws/send`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content: newMessage, clientId, staffId, }), }); if (res.ok) { setNewMessage(''); fetchMessages(); } } catch (err) { console.error('Failed to send message:', err); } }; const clients = [ { id: 'client-1', name: 'Alice Johnson' }, { id: 'client-2', name: 'Bob Smith' }, ]; return (

Conversations

{clients.map(client => ( ))}

{clients.find(c => c.id === clientId)?.name || 'Select a conversation'}

{loading ?
Loading...
: ( messages.map(msg => (
{msg.isFromStaff ? : }

{msg.content}

{new Date(msg.createdAt).toLocaleTimeString()}

)) )}
setNewMessage(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleSend()} placeholder="Type a message..." className="flex-1 border rounded-lg px-4 py-2" disabled={!clientId} />
); }