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 && (