import { useState, useEffect, useRef } from 'react'; import ChatMessage from './ChatMessage'; import ChatInput from './ChatInput'; import { motion } from 'framer-motion'; export default function ChatWindow() { const [messages, setMessages] = useState([]); const [isLoading, setIsLoading] = useState(false); const messagesEndRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages]); const handleSendMessage = async (text) => { const userMessage = { text, timestamp: new Date().toISOString(), isUser: true, }; setMessages(prev => [...prev, userMessage]); setIsLoading(true); try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: text }), }); if (!response.ok) throw new Error('Failed to get response'); const data = await response.json(); const botMessage = { text: data.response, timestamp: new Date().toISOString(), isUser: false, }; setMessages(prev => [...prev, botMessage]); } catch (error) { console.error('Error:', error); const errorMessage = { text: "Sorry, I'm having trouble responding right now. Please try again later.", timestamp: new Date().toISOString(), isUser: false, }; setMessages(prev => [...prev, errorMessage]); } finally { setIsLoading(false); } }; return (
Start chatting with your virtual companion. She's here to listen and talk about anything!