import React, { useState, useRef, useEffect } from 'react'; const AIChat = ({ userRole, stats, onConfirmBooking, onConfirmListing, showToast }) => { const [isOpen, setIsOpen] = useState(false); const [messages, setMessages] = useState([ { role: 'model', parts: [{ text: `Hi! I'm Commute Copilot ✨ — powered by NVIDIA NIM. I can help you ${userRole === 'Pool Host' ? 'list a new commute or find passengers' : 'find a ride or book one'}, answer carpool policy questions, or look up your personal stats. How can I assist?` }] } ]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const messagesEndRef = useRef(null); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, isOpen]); const handleSend = async () => { if (!input.trim()) return; const userMessage = { role: 'user', parts: [{ text: input }] }; setMessages(prev => [...prev, userMessage]); setInput(''); setIsLoading(true); try { const res = await fetch(`/api/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: input, context: { userRole, stats: stats || {} }, history: messages.filter(m => !m.isActionCard).slice(1) // Remove the initial greeting to satisfy Gemini API requirements }) }); const data = await res.json(); if (res.ok) { if (data.type === 'action') { // Model wants to use a tool setMessages(prev => [...prev, { role: 'model', parts: [{ text: data.text }] }, { role: 'model', isActionCard: true, action: data.action, params: data.params } ]); } else { setMessages(prev => [...prev, { role: 'model', parts: [{ text: data.text }] }]); } } else { setMessages(prev => [...prev, { role: 'model', parts: [{ text: data.error || 'Sorry, I encountered an error. Please try again.' }] }]); } } catch (err) { console.error(err); setMessages(prev => [...prev, { role: 'model', parts: [{ text: 'Network error communicating with the AI.' }] }]); } finally { setIsLoading(false); } }; const handleConfirmAction = (action, params) => { if (action === 'draft_booking' && onConfirmBooking) { onConfirmBooking(params); setIsOpen(false); } else if (action === 'draft_listing' && onConfirmListing) { onConfirmListing(params); setIsOpen(false); } else { if (showToast) showToast('This action is not supported in your current role.', 'warning'); } }; return ( <> {/* Floating Action Button */} {/* Chat Window */} {isOpen && (
{/* Header */}
✨ Commute Copilot NVIDIA
{/* Messages */}
{messages.map((msg, idx) => (
{msg.isActionCard ? (
{msg.action === 'draft_booking' ? '🚕 Ride Request Draft' : '🚗 Commute Listing Draft'}
From: {msg.params.origin}
To: {msg.params.destination}
Time: {msg.params.time} {msg.action === 'draft_listing' && ( <>
Seats: {msg.params.seats}
Cost: ₹{msg.params.price} )}
) : (
{msg.parts[0].text}
)}
))} {isLoading && (
Thinking...
)}
{/* Footer Input */}
setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleSend()} placeholder="Ask anything or request a ride..." className="flex-1 px-4 py-2.5 rounded-full border border-white/10 bg-surface-base/80 text-white text-xs outline-none focus:border-primary transition-colors placeholder:text-white/20" />
)} ); }; export default AIChat;