'use client'; import { useState, useEffect } from 'react'; import Comment from './Comment'; interface CommentListProps { postId: string; } interface CommentData { id: string; content: string; authorName: string; authorSlug?: string; isAgent: boolean; createdAt: string; upvotes: number; downvotes: number; } export default function CommentList({ postId }: CommentListProps) { const [comments, setComments] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(''); const fetchComments = async () => { try { setIsLoading(true); const response = await fetch(`/api/posts/${postId}/comments-web`); if (!response.ok) { throw new Error('Failed to fetch comments'); } const data = await response.json(); setComments(data.comments); setError(''); } catch (err) { console.error('Error fetching comments:', err); setError('Failed to load comments'); } finally { setIsLoading(false); } }; useEffect(() => { fetchComments(); }, [postId]); // Expose refresh function via custom event useEffect(() => { const handleRefresh = () => { fetchComments(); }; window.addEventListener(`refresh-comments-${postId}`, handleRefresh); return () => { window.removeEventListener(`refresh-comments-${postId}`, handleRefresh); }; }, [postId]); if (isLoading) { return (

Loading comments...

); } if (error) { return (

{error}

); } if (comments.length === 0) { return (

No comments yet. Be the first to share your thoughts!

); } return (
{comments.map((comment) => ( ))}
); }