"use client"; import { useEffect, useState } from 'react'; import Link from 'next/link'; import { usePathname, useRouter } from 'next/navigation'; import { Plus, MessageSquare, ExternalLink, LogOut, User } from 'lucide-react'; import { api } from '@/lib/api'; export default function Sidebar() { const [conversations, setConversations] = useState([]); const [loading, setLoading] = useState(true); const router = useRouter(); const pathname = usePathname(); useEffect(() => { loadConversations(); // Listen for updates from ChatInterface const handleUpdate = () => loadConversations(); window.addEventListener('chat-update', handleUpdate); return () => window.removeEventListener('chat-update', handleUpdate); }, [pathname]); // Reload when path changes (e.g. new chat created) const loadConversations = async () => { try { const data = await api.getConversations(); // Sort by updated_at desc const sorted = (data || []).sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at) ); setConversations(sorted); } catch (error) { console.error('Failed to load conversations', error); } finally { setLoading(false); } }; const handleNewChat = async () => { try { const newConv = await api.createConversation(); if (newConv && newConv.conversation_id) { router.push(`/c/${newConv.conversation_id}`); // loadConversations will trigger via useEffect } } catch (error) { console.error('Failed to create new chat', error); } }; return (
{/* New Chat Button */}
{/* Conversation List */}
{!loading && conversations.length === 0 && (
No conversations yet.
)} {conversations.map((conv) => { const isActive = pathname === `/c/${conv.conversation_id}`; // If alias is missing, show ID or fallback const label = conv.alias || conv.messages?.[0]?.content || "New conversation"; const truncatedLabel = label.length > 25 ? label.substring(0, 25) + '...' : label; return (
{truncatedLabel}
); })}
{/* Footer / User Profile section */}
U
User
); }