"use client"; import { useEffect, useState, useCallback, useRef } from "react"; import { fetchBeadsComments } from "@/lib/comments"; import type { FetchCommentsResult } from "@/lib/comments"; // Re-export types so existing imports from this module continue to work export type { BeadsComment, BeadsLike } from "@/lib/comments"; export interface UseBeadsCommentsResult { /** Map from node ID -> threaded comment trees (root comments with nested replies) */ commentsByNode: Map; /** Map from node ID -> total comment count (including replies) */ commentedNodeIds: Map; /** Flat list of ALL comments (including replies), newest-first, for the All Comments panel */ allComments: BeadsComment[]; isLoading: boolean; error: string | null; refetch: () => Promise; } // Need to import the concrete type for state usage import type { BeadsComment } from "@/lib/comments"; export function useBeadsComments(): UseBeadsCommentsResult { const [commentsByNode, setCommentsByNode] = useState< Map >(new Map()); const [commentedNodeIds, setCommentedNodeIds] = useState< Map >(new Map()); const [allComments, setAllComments] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); const cancelledRef = useRef(false); const fetchAndProcess = useCallback(async () => { try { setIsLoading(true); setError(null); const result: FetchCommentsResult = await fetchBeadsComments(); // Update state (only if not cancelled) if (!cancelledRef.current) { setCommentsByNode(result.commentsByNode); setCommentedNodeIds(result.commentedNodeIds); setAllComments(result.allComments); } } catch (err) { if (!cancelledRef.current) { const message = err instanceof Error ? err.message : "Failed to fetch comments"; console.error("Failed to fetch beads comments:", err); setError(message); } } finally { if (!cancelledRef.current) { setIsLoading(false); } } }, []); // Fetch on mount useEffect(() => { cancelledRef.current = false; fetchAndProcess(); return () => { cancelledRef.current = true; }; }, [fetchAndProcess]); return { commentsByNode, commentedNodeIds, allComments, isLoading, error, refetch: fetchAndProcess, }; }