import { useEffect } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; import { supabase } from "@/integrations/supabase/client"; import { useAuth } from "@/hooks/useAuth"; import { useWorkspace, DocumentRow } from "@/store/workspace"; import { Button } from "@/components/ui/button"; import { Sparkles, Plus, FileText, Mic, Video, Youtube, FileType2, LogOut, Loader2 } from "lucide-react"; import { cn } from "@/lib/utils"; import { useToast } from "@/hooks/use-toast"; const sourceIcon = { pdf: FileType2, docx: FileType2, text: FileText, audio: Mic, video: Video, youtube: Youtube, } as const; export default function AppSidebar({ onNew, onNavigate }: { onNew: () => void; onNavigate?: () => void }) { const { user, signOut } = useAuth(); const { documents, setDocuments, upsertDocument, removeDocument } = useWorkspace(); const { docId } = useParams(); const navigate = useNavigate(); const { toast } = useToast(); useEffect(() => { if (!user) return; let mounted = true; (async () => { const { data, error } = await supabase .from("documents") .select("id,title,source_type,status,error_code,created_at") .order("created_at", { ascending: false }); if (error) { toast({ title: "Failed to load documents", description: error.message, variant: "destructive" }); return; } if (mounted && data) setDocuments(data as DocumentRow[]); })(); const channel = supabase .channel("documents-sidebar") .on( "postgres_changes", { event: "*", schema: "public", table: "documents", filter: `user_id=eq.${user.id}` }, (payload) => { if (payload.eventType === "DELETE") { removeDocument((payload.old as any).id); } else { const row = payload.new as any; upsertDocument({ id: row.id, title: row.title, source_type: row.source_type, status: row.status, error_code: row.error_code, created_at: row.created_at, }); } } ) .subscribe(); return () => { mounted = false; supabase.removeChannel(channel); }; }, [user, setDocuments, upsertDocument, removeDocument, toast]); return ( ); }