import { useState, useEffect } from 'react' import { Send, Trash2, MessageCircle, Pencil, Check, X } from 'lucide-react' import { api, getInitials } from '../utils/api' import { useAuth } from '../contexts/AuthContext' import { useLanguage } from '../i18n/LanguageContext' function relativeTime(dateStr, t) { const now = Date.now() const then = new Date(dateStr).getTime() const diffMs = now - then const diffMin = Math.floor(diffMs / 60000) if (diffMin < 1) return t('comments.justNow') if (diffMin < 60) return t('comments.minutesAgo').replace('{n}', diffMin) const diffHours = Math.floor(diffMin / 60) if (diffHours < 24) return t('comments.hoursAgo').replace('{n}', diffHours) const diffDays = Math.floor(diffHours / 24) return t('comments.daysAgo').replace('{n}', diffDays) } export default function CommentsSection({ entityType, entityId }) { const { user } = useAuth() const { t } = useLanguage() const [comments, setComments] = useState([]) const [newComment, setNewComment] = useState('') const [sending, setSending] = useState(false) const [editingId, setEditingId] = useState(null) const [editContent, setEditContent] = useState('') useEffect(() => { if (entityType && entityId) loadComments() }, [entityType, entityId]) const loadComments = async () => { try { const data = await api.get(`/comments/${entityType}/${entityId}`) setComments(Array.isArray(data) ? data : []) } catch (err) { console.error('Failed to load comments:', err) } } const handleSend = async () => { if (!newComment.trim() || sending) return setSending(true) try { await api.post(`/comments/${entityType}/${entityId}`, { content: newComment.trim() }) setNewComment('') loadComments() } catch (err) { console.error('Failed to send comment:', err) } finally { setSending(false) } } const handleDelete = async (id) => { try { await api.delete(`/comments/${id}`) loadComments() } catch (err) { console.error('Failed to delete comment:', err) } } const startEdit = (comment) => { setEditingId(comment.id) setEditContent(comment.content) } const cancelEdit = () => { setEditingId(null) setEditContent('') } const saveEdit = async (id) => { if (!editContent.trim()) return try { await api.patch(`/comments/${id}`, { content: editContent.trim() }) setEditingId(null) setEditContent('') loadComments() } catch (err) { console.error('Failed to edit comment:', err) } } const canEdit = (comment) => { if (!user) return false return comment.user_id === user.id } const canDelete = (comment) => { if (!user) return false if (comment.user_id === user.id) return true return user.role === 'superadmin' || user.role === 'manager' } return (
{t('comments.noComments')}
)}{c.content}
)}