'use client'; import React, { useState, useEffect, useRef } from 'react'; import { api } from '../../services/api'; export default function AIChatPanel({ sessionId }) { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const chatEndRef = useRef(null); useEffect(() => { if (sessionId) { loadHistory(); } }, [sessionId]); const loadHistory = async () => { try { const history = await api.getChatHistory(sessionId); if (Array.isArray(history)) setMessages(history); } catch (err) { console.error("Failed to load chat history:", err); } }; const handleSend = async (e) => { e.preventDefault(); if (!input.trim() || !sessionId || loading) return; const userMessage = { role: 'user', content: input }; setMessages((prev) => [...prev, userMessage]); const currentPrompt = input; setInput(''); setLoading(true); try { const res = await api.sendChatMessage(sessionId, 'user', currentPrompt); if (res && res.content) { setMessages((prev) => [...prev, { role: 'assistant', content: res.content }]); } } catch (err) { setMessages((prev) => [...prev, { role: 'assistant', content: "Error communicating with AI agent." }]); } finally { setLoading(false); chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); } }; return (