import { useState } from 'react' import { useNavigate } from 'react-router-dom' import { Heart, MessageCircle, MoreVertical, ChevronLeft, ChevronRight, Download, Send, X, ZoomIn, Share2 } from 'lucide-react' import { likePost, deletePost, sendPhotoToTelegram } from '../utils/api' import { hapticFeedback, showConfirm, openTelegramLink } from '../utils/telegram' import './PostCard.css' const TAG_COLORS = { furry: '#FF8A33', anime: '#4A90E2', other: '#A0A0A0' } const TAG_NAMES = { furry: 'Furry', anime: 'Anime', other: 'Other' } export default function PostCard({ post, currentUser, onUpdate }) { const navigate = useNavigate() const [liked, setLiked] = useState(post.likes?.includes(currentUser.id) || false) const [likesCount, setLikesCount] = useState(post.likes?.length || 0) const [currentImageIndex, setCurrentImageIndex] = useState(0) const [showFullView, setShowFullView] = useState(false) // Проверка на существование автора if (!post.author) { console.warn('[PostCard] Post without author:', post._id) return null // Не показываем посты без автора } // Поддержка и старого поля imageUrl и нового images // Фильтруем старые URL из Telegram API const allImages = post.images && post.images.length > 0 ? post.images : (post.imageUrl ? [post.imageUrl] : []) const images = allImages.filter(img => { // Игнорируем старые URL из Telegram API if (img && typeof img === 'string' && img.includes('api.telegram.org/file/bot')) { console.warn('[PostCard] Skipping old Telegram URL:', img) return false } return true }) const handleLike = async () => { try { hapticFeedback('light') const result = await likePost(post._id) setLiked(result.liked) setLikesCount(result.likes) if (result.liked) { hapticFeedback('success') } } catch (error) { console.error('Ошибка лайка:', error) } } const handleDelete = async () => { const confirmed = await showConfirm('Удалить этот пост?') if (confirmed) { try { await deletePost(post._id) hapticFeedback('success') onUpdate() } catch (error) { console.error('Ошибка удаления:', error) } } } const formatDate = (date) => { const d = new Date(date) return d.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' }) } const goToProfile = () => { if (post.author?._id) { navigate(`/user/${post.author._id}`) } } const openFullView = () => { if (images.length > 0) { setShowFullView(true) hapticFeedback('light') } } const handleNext = () => { if (currentImageIndex < images.length - 1) { setCurrentImageIndex(currentImageIndex + 1) hapticFeedback('light') } } const handlePrev = () => { if (currentImageIndex > 0) { setCurrentImageIndex(currentImageIndex - 1) hapticFeedback('light') } } const handleDownloadImage = async () => { try { hapticFeedback('light') const imageUrl = images[currentImageIndex] await sendPhotoToTelegram(imageUrl) hapticFeedback('success') } catch (error) { console.error('Ошибка отправки фото:', error) hapticFeedback('error') } } const handleRepost = () => { try { hapticFeedback('light') // Получить имя бота из переменных окружения или использовать дефолтное const botName = import.meta.env.VITE_TELEGRAM_BOT_NAME || 'NakamaSpaceBot' // Создать deeplink для открытия поста в миниапп const deeplink = `https://t.me/${botName}?startapp=post_${post._id}` // Открыть нативное окно "Поделиться" в Telegram const shareUrl = `https://t.me/share/url?url=${encodeURIComponent(deeplink)}&text=${encodeURIComponent('Смотри пост в Nakama!')}` openTelegramLink(shareUrl) hapticFeedback('success') } catch (error) { console.error('Ошибка репоста:', error) hapticFeedback('error') } } return (
{/* Хедер поста */}
{post.author?.username { e.target.src = '/default-avatar.png' }} />
{post.author?.firstName || ''} {post.author?.lastName || ''} {!post.author?.firstName && !post.author?.lastName && 'Пользователь'}
@{post.author?.username || post.author?.firstName || 'user'} · {formatDate(post.createdAt)}
{/* Контент */} {post.content && (
{post.content}
)} {/* Изображения */} {images.length > 0 && (
{`Image {images.length > 1 && ( <> {currentImageIndex > 0 && ( )} {currentImageIndex < images.length - 1 && ( )}
{images.map((_, index) => ( { e.stopPropagation(); setCurrentImageIndex(index); }} /> ))}
)} {/* Индикатор что можно открыть fullview */}
)} {/* Теги */}
{post.tags.map((tag, index) => ( {TAG_NAMES[tag]} ))} {post.isNSFW && ( NSFW )}
{/* Действия */}
{images.length > 0 && ( )}
{/* Fullview модал */} {showFullView && (
setShowFullView(false)}>
{currentImageIndex + 1} / {images.length}
e.stopPropagation()}> {`Full {images.length > 1 && ( <> {currentImageIndex > 0 && ( )} {currentImageIndex < images.length - 1 && ( )} )}
{images.length > 1 && (
{images.map((_, index) => ( { e.stopPropagation(); setCurrentImageIndex(index); }} /> ))}
)}
)}
) }