"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 (