'use client'; import React, { useState, useRef, useEffect } from 'react'; import { StopCircle, CornerDownRight, Settings2, Menu } from 'lucide-react'; import { ChatMessage, MessageProps } from './ChatMessage'; import { Sidebar } from './Sidebar'; import { AnimatePresence } from 'framer-motion'; import { ApiService } from '@/lib/api'; export default function Chat() { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const [sessionId, setSessionId] = useState(null); const [isEnhanced, setIsEnhanced] = useState(true); const [isSidebarOpen, setIsSidebarOpen] = useState(true); const [sessionHistory, setSessionHistory] = useState>([]); const messagesEndRef = useRef(null); const textareaRef = useRef(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages, isLoading]); // Load session history from localstorage useEffect(() => { const stored = localStorage.getItem('nebula_history'); if (stored) { try { setSessionHistory(JSON.parse(stored)); } catch { console.error("Could not parse history"); } } }, []); const saveSessionToHistory = (id: string, preview: string) => { setSessionHistory(prev => { const filtered = prev.filter(s => s.id !== id); const newList = [{ id, preview, timestamp: Date.now() }, ...filtered]; localStorage.setItem('nebula_history', JSON.stringify(newList)); return newList; }); }; const loadSession = async (id: string) => { setIsLoading(true); setSessionId(id); localStorage.setItem('nebula_session_id', id); try { const history = await ApiService.getHistory(id); const formattedHistory: MessageProps[] = []; history.forEach((h: { user_message: string; ai_response: string }, i: number) => { formattedHistory.push({ id: `user-${i}`, role: 'user', content: h.user_message }); formattedHistory.push({ id: `bot-${i}`, role: 'bot', content: h.ai_response }); }); if (formattedHistory.length === 0) { formattedHistory.push({ id: 'welcome', role: 'bot', content: 'Hello! I am Nexus AI. How can I help you today?' }); } setMessages(formattedHistory); } catch (e) { console.error(e); } finally { setIsLoading(false); if (window.innerWidth < 768) setIsSidebarOpen(false); // Close sidebar on mobile after select } }; const handleNewChat = async () => { setIsLoading(true); try { const newId = await ApiService.createSession(); setSessionId(newId); localStorage.setItem('nebula_session_id', newId as string); setMessages([{ id: 'welcome', role: 'bot', content: 'Hello! I am Nexus AI. How can I help you today?', isNew: true }]); if (window.innerWidth < 768) setIsSidebarOpen(false); } catch (e) { console.error(e); } finally { setIsLoading(false); } }; useEffect(() => { const initSession = async () => { let storedSessionId = localStorage.getItem('nebula_session_id'); if (!storedSessionId) { try { storedSessionId = await ApiService.createSession() as string; localStorage.setItem('nebula_session_id', storedSessionId); } catch { console.error("Failed to init session."); return; } } loadSession(storedSessionId as string); }; initSession(); }, []); const handleInput = (e: React.ChangeEvent) => { setInput(e.target.value); if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 200)}px`; } }; const handleSend = async () => { if (!input.trim() || isLoading || !sessionId) return; const userMsg: MessageProps = { id: Date.now().toString(), role: 'user', content: input.trim(), }; const currentInputText = input.trim(); saveSessionToHistory(sessionId, currentInputText.substring(0, 40)); setMessages((prev) => [...prev, userMsg]); setInput(''); setIsLoading(true); if (textareaRef.current) { textareaRef.current.style.height = 'auto'; } try { const reply = await ApiService.sendMessage(currentInputText, sessionId, isEnhanced); const botMsg: MessageProps = { id: (Date.now() + 1).toString(), role: 'bot', content: reply, isNew: true, }; setMessages((prev) => [...prev, botMsg]); } catch (error) { console.error('Error sending message:', error); const errorMsg: MessageProps = { id: (Date.now() + 1).toString(), role: 'bot', content: 'Error sending message. Please try again.', isNew: true }; setMessages((prev) => [...prev, errorMsg]); } finally { setIsLoading(false); } }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; return (
{/* Header Navbar */}
{!isSidebarOpen && ( )}

Nexus AI

{/* Main Scrollable Chat Area */}
{messages.length === 1 && (

Hello, how can I help?

)} {messages.map((message) => ( ))} {isLoading && (
)}
{/* Bottom Floating Input Area */}