import { useState, useEffect } from 'react' import { createPortal } from 'react-dom' import { X, Send } from 'lucide-react' import { commentPost, getPosts } from '../utils/api' import { hapticFeedback } from '../utils/telegram' import { decodeHtmlEntities } from '../utils/htmlEntities' import './CommentsModal.css' export default function CommentsModal({ post, onClose, onUpdate }) { // ВСЕ хуки должны вызываться всегда, до любых условных возвратов const [comment, setComment] = useState('') const [loading, setLoading] = useState(false) const [comments, setComments] = useState([]) const [fullPost, setFullPost] = useState(null) const [loadingPost, setLoadingPost] = useState(false) // Загрузить полные данные поста с комментариями useEffect(() => { if (!post || !post._id) { // Если пост не передан, очищаем состояние setFullPost(null) setComments([]) return } // Сначала установим переданные данные setFullPost(post) const initialComments = (post.comments || []).filter(c => { return c && c.author && (typeof c.author === 'object') }) setComments(initialComments) // Затем загрузим полные данные для обновления const loadFullPost = async () => { try { setLoadingPost(true) // Загрузить посты с фильтром по автору поста для оптимизации const authorId = post?.author?._id || post?.author const response = authorId ? await getPosts({ userId: authorId, limit: 100 }) : await getPosts({ limit: 200 }) const foundPost = response.posts?.find(p => p._id === post._id) if (foundPost) { // Проверяем, что комментарии populate'ены с авторами const commentsWithAuthors = (foundPost.comments || []).filter(c => { return c && c.author && (typeof c.author === 'object') }) setComments(commentsWithAuthors) setFullPost(foundPost) } } catch (error) { console.error('[CommentsModal] Ошибка загрузки поста:', error) // Оставляем переданные данные } finally { setLoadingPost(false) } } loadFullPost() }, [post?._id]) // Только ID поста в зависимостях // Проверка на существование поста ПОСЛЕ хуков if (!post || !post._id) { return null } const displayPost = fullPost || post // Дополнительная проверка на наличие автора if (!displayPost.author) { console.warn('[CommentsModal] Пост без автора:', displayPost._id) return null } const handleSubmit = async () => { if (!comment.trim() || loading) return try { setLoading(true) hapticFeedback('light') const result = await commentPost(post._id, comment) console.log('[CommentsModal] Результат добавления комментария:', result) if (result && result.comments && Array.isArray(result.comments)) { // Фильтруем комментарии с авторами (проверяем, что author - объект) const commentsWithAuthors = result.comments.filter(c => { return c && c.author && (typeof c.author === 'object') }) console.log('[CommentsModal] Отфильтрованные комментарии:', commentsWithAuthors.length, 'из', result.comments.length) setComments(commentsWithAuthors) // Обновить полный пост if (fullPost) { setFullPost({ ...fullPost, comments: commentsWithAuthors }) } setComment('') hapticFeedback('success') // Обновить данные поста для синхронизации (но не блокируем UI) // Перезагружаем через useEffect, который сработает при изменении post._id // Но так как post._id не меняется, просто обновим локально if (onUpdate) { onUpdate() } } else { console.error('[CommentsModal] Неожиданный формат ответа:', result) hapticFeedback('error') } } catch (error) { console.error('[CommentsModal] Ошибка добавления комментария:', error) hapticFeedback('error') } finally { setLoading(false) } } const formatDate = (date) => { const d = new Date(date) const now = new Date() const diff = Math.floor((now - d) / 1000) // секунды if (diff < 60) return 'только что' if (diff < 3600) return `${Math.floor(diff / 60)} мин` if (diff < 86400) return `${Math.floor(diff / 3600)} ч` return d.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' }) } const handleOverlayClick = (e) => { // Закрывать только при клике на overlay, не на контент if (e.target === e.currentTarget) { onClose() } } return createPortal(
e.stopPropagation()} onTouchStart={(e) => e.stopPropagation()} onClick={handleOverlayClick} >
e.stopPropagation()}> {/* Хедер */}

Комментарии

{/* Пост */} {loadingPost ? (

Загрузка...

) : (
{displayPost.author?.username { e.target.src = '/default-avatar.png' }} />
{displayPost.author?.firstName || ''} {displayPost.author?.lastName || ''} {!displayPost.author?.firstName && !displayPost.author?.lastName && 'Пользователь'}
@{displayPost.author?.username || displayPost.author?.firstName || 'user'}
{displayPost.content && (
{decodeHtmlEntities(displayPost.content)}
)} {((displayPost.images && displayPost.images.length > 0) || displayPost.imageUrl) && (
Post
)}
)} {/* Список комментариев */}
{comments.length === 0 ? (

Пока нет комментариев

Будьте первым!
) : ( comments .filter(c => { // Фильтруем комментарии без автора или с неполным автором return c && c.author && (typeof c.author === 'object') && c.content }) .map((c, index) => { // Используем _id если есть, иначе index const commentId = c._id || c.id || `comment-${index}` // Проверяем, что автор полностью загружен if (!c.author || typeof c.author !== 'object') { console.warn('[CommentsModal] Комментарий без автора:', c) return null } return (
{c.author?.username { e.target.src = '/default-avatar.png' }} />
{c.author?.firstName || ''} {c.author?.lastName || ''} {!c.author?.firstName && !c.author?.lastName && 'Пользователь'} {formatDate(c.createdAt)}

{decodeHtmlEntities(c.content)}

) }) .filter(Boolean) // Убираем null значения )}
{/* Форма добавления комментария */}
setComment(e.target.value)} onKeyPress={e => e.key === 'Enter' && handleSubmit()} maxLength={500} />
) }