'use client'; import { useState, useRef, useEffect } from 'react'; import { MessageCircle, X, Send, Loader2 } from 'lucide-react'; interface ChatBotProps { context: any; } export function ChatBot({ context }: ChatBotProps) { const [isOpen, setIsOpen] = useState(false); const [messages, setMessages] = useState<{role: string, content: string}[]>([]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const messagesEndRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages, isOpen]); const sendMessage = async (e: React.FormEvent) => { e.preventDefault(); if (!input.trim() || isLoading) return; const userMsg = input.trim(); setInput(''); const newMessages = [...messages, { role: 'user', content: userMsg }]; setMessages(newMessages); setIsLoading(true); try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: newMessages, context: context || { status: 'No live telemetry available' } }), }); if (!response.ok) { const err = await response.json(); throw new Error(err.error || 'Failed to fetch'); } if (!response.body) throw new Error('No response body'); const reader = response.body.getReader(); const decoder = new TextDecoder(); let assistantMsg = ''; setMessages([...newMessages, { role: 'assistant', content: '' }]); while (true) { const { value, done } = await reader.read(); if (done) break; const textChunk = decoder.decode(value, { stream: true }); assistantMsg += textChunk; setMessages((prev) => { const lastIndex = prev.length - 1; const updated = [...prev]; updated[lastIndex] = { role: 'assistant', content: assistantMsg }; return updated; }); } } catch (error: any) { console.error('Chat error:', error); setMessages((prev) => [...prev, { role: 'assistant', content: `Sorry, I encountered an error: ${error.message}` }]); } finally { setIsLoading(false); } }; return ( <> {/* Chat Button */} {/* Chat Window */}

🤖 Splashy

{messages.length === 0 && (

Hi! I can answer questions about the current water quality data.

Try asking: "Is the water potable?"

)} {messages.map((m, i) => (
{m.content}
))} {isLoading && messages[messages.length - 1]?.role === 'user' && (
)}
setInput(e.target.value)} placeholder="Ask about the telemetry..." className="flex-1 bg-gray-100 text-gray-800 px-4 py-2 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm" />
); }