import React, { useRef, useState } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Alert, } from 'react-native'; import { useRouter } from 'expo-router'; import { Image } from 'expo-image'; import { Colors } from '../../constants/Colors'; import { postService } from '../../services/postService'; import { userService } from '../../services/userService'; import { logger } from '../../utils/logger'; import { useAuthStore } from '../../store/authStore'; import { useHaptics } from '../../hooks/useHaptics'; import { useToast } from '../../hooks/useToast'; import { timeAgo } from '../../utils/timeAgo'; import PostOptionsModal from '../common/PostOptionsModal'; import ReportModal from '../common/ReportModal'; import CodeBlock from '../common/CodeBlock'; import RichContent from '../common/RichContent'; import LikeBounceAnimation, { LikeBounceAnimationHandle, } from '../common/LikeBounceAnimation'; import CountWheel from '../common/CountWheel'; import { useLightbox } from '../common/Lightbox'; const DOUBLE_PRESS_DELAY = 300; interface Post { id: string; userId: string; content?: string; mediaType: string; mediaUrl?: string; codeSnippet?: string; language?: string; user: { id: string; username: string; avatar?: string; }; likesCount: number; commentsCount: number; isLiked: boolean; createdAt: string; } interface PostCardProps { post: Post; onLike?: () => void; onPress?: () => void; showFullContent?: boolean; /** * Called when the viewer hides this post ("Not interested") or blocks its * author. The parent can drop the post from its feed list; if omitted the * card hides itself locally. */ onHide?: (postId: string) => void; } export default function PostCard({ post, onLike, showFullContent = false, onHide }: PostCardProps) { const router = useRouter(); const { user } = useAuthStore(); const haptics = useHaptics(); const openLightbox = useLightbox(); const { showToast, ToastComponent } = useToast(); const [isLiked, setIsLiked] = useState(post.isLiked); const [likesCount, setLikesCount] = useState(post.likesCount); // Stays false until the viewer toggles the like at least once, so the count // wheel never animates on first mount (matching Bluesky's behaviour). const [hasToggledLike, setHasToggledLike] = useState(false); const [loading, setLoading] = useState(false); const [showOptionsModal, setShowOptionsModal] = useState(false); const [showReportModal, setShowReportModal] = useState(false); const [hidden, setHidden] = useState(false); const [isBlocked, setIsBlocked] = useState(false); const [blocking, setBlocking] = useState(false); const likeBounceRef = useRef(null); const lastTapRef = useRef(0); const isOwner = user?.id === post.user.id; // Hide this post from the viewer's feed ("Not interested"). Purely // client-side: the parent feed can prune it, otherwise we self-hide. const handleHidePost = () => { haptics('Light'); if (onHide) { onHide(post.id); } else { setHidden(true); } showToast('Post hidden', 'success'); }; const handleBlockUser = () => { if (blocking) return; const action = isBlocked ? 'Unblock' : 'Block'; Alert.alert( `${action} @${post.user.username}?`, isBlocked ? 'They will be able to see your content and interact with you again.' : "You won't see their posts and they won't be able to interact with you.", [ { text: 'Cancel', style: 'cancel' }, { text: action, style: isBlocked ? 'default' : 'destructive', onPress: async () => { setBlocking(true); try { if (isBlocked) { await userService.unblockUser(post.user.id); setIsBlocked(false); showToast(`Unblocked @${post.user.username}`, 'success'); } else { await userService.blockUser(post.user.id); setIsBlocked(true); showToast(`Blocked @${post.user.username}`, 'success'); // A blocked author's post should leave the feed immediately. if (onHide) { onHide(post.id); } else { setHidden(true); } } } catch (error) { logger.error('Block user error:', error); showToast(`Failed to ${action.toLowerCase()} user`, 'error'); } finally { setBlocking(false); } }, }, ], ); }; // mode: 'toggle' for the like button, 'like-only' for double-tap (which never // unlikes, matching Instagram/TikTok behaviour). const handleLike = async (mode: 'toggle' | 'like-only' = 'toggle') => { if (loading) return; if (mode === 'like-only' && isLiked) return; haptics('Medium'); // Optimistic update - update UI immediately const previousIsLiked = isLiked; const previousLikesCount = likesCount; setHasToggledLike(true); setIsLiked(!isLiked); setLikesCount(prev => !previousIsLiked ? prev + 1 : prev - 1); setLoading(true); try { const response = await postService.likePost(post.id); // Sync with server response (in case of race conditions) setIsLiked(response.liked); setLikesCount(response.likesCount || (response.liked ? previousLikesCount + 1 : previousLikesCount - 1)); onLike?.(); } catch (error) { // Rollback on failure setIsLiked(previousIsLiked); setLikesCount(previousLikesCount); logger.error('Like error:', error); } finally { setLoading(false); } }; const handleImagePress = () => { const now = Date.now(); if (now - lastTapRef.current < DOUBLE_PRESS_DELAY) { lastTapRef.current = 0; likeBounceRef.current?.animate(); void handleLike('like-only'); return; } lastTapRef.current = now; if (!showFullContent) { router.push(`/post/${post.id}`); } }; const handleImageLongPress = () => { if (!post.mediaUrl) return; haptics('Light'); openLightbox([{ uri: post.mediaUrl, alt: post.content || undefined }], 0); }; if (hidden) { return null; } return ( {ToastComponent} {/* Card Header */} router.push(`/profile/${post.user.id}`)} > {post.user.avatar ? ( ) : ( {post.user.username[0].toUpperCase()} )} {post.user.username} {timeAgo(post.createdAt)} setShowOptionsModal(true)}> ⋯ {/* Project Visual */} {post.mediaType === 'image' && post.mediaUrl && ( )} {post.mediaType === 'code' && post.codeSnippet && ( 3} /> )} {/* Action Bar */} handleLike('toggle')} disabled={loading} accessibilityRole="button" accessibilityLabel={isLiked ? 'Unlike post' : 'Like post'} > {isLiked ? '❤️' : '🤍'} router.push(`/post/${post.id}`)} > 💬 router.push(`/post/${post.id}/share`)} > 📤 🔖 {/* Engagement & Info */} {likesCount > 0 ? ( <> ( {count.toLocaleString()} )} /> {' '} {likesCount === 1 ? 'like' : 'likes'} ) : ( 0 likes )} {post.content && ( {post.user.username} )} {post.commentsCount > 0 && ( router.push(`/post/${post.id}`)}> View all {post.commentsCount} {post.commentsCount === 1 ? 'comment' : 'comments'} )} {/* Chips/Tags */} {post.language && ( {post.language} )} {/* Options Modal */} setShowOptionsModal(false)} onReport={() => setShowReportModal(true)} onShare={() => router.push(`/post/${post.id}/share`)} onHidePost={handleHidePost} onBlockUser={handleBlockUser} authorUsername={post.user.username} isBlocked={isBlocked} isOwner={isOwner} /> {/* Report Modal */} setShowReportModal(false)} targetType="POST" targetId={post.id} targetName={post.content ? post.content.substring(0, 50) + (post.content.length > 50 ? '...' : '') : undefined} /> ); } const styles = StyleSheet.create({ container: { width: '100%', borderBottomWidth: 1, borderBottomColor: Colors.border, paddingVertical: 16, }, header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 16, paddingBottom: 12, }, headerLeft: { flexDirection: 'row', alignItems: 'center', gap: 12, }, avatar: { width: 40, height: 40, borderRadius: 20, }, avatarPlaceholder: { width: 40, height: 40, borderRadius: 20, backgroundColor: Colors.primary, justifyContent: 'center', alignItems: 'center', }, avatarText: { color: Colors.text, fontWeight: 'bold', fontSize: 16, }, headerTextWrap: { flexShrink: 1, }, username: { color: Colors.text, fontWeight: 'bold', fontSize: 14, }, timestamp: { color: Colors.textSecondary, fontSize: 12, marginTop: 1, }, moreButton: { width: 32, height: 32, alignItems: 'center', justifyContent: 'center', borderRadius: 16, }, moreIcon: { fontSize: 24, color: Colors.text, }, media: { width: '100%', aspectRatio: 16 / 9, backgroundColor: Colors.surface, }, codeWrapper: { marginHorizontal: 16, }, actionBar: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 16, paddingTop: 12, }, actionBarLeft: { flexDirection: 'row', alignItems: 'center', gap: 8, }, actionButton: { width: 40, height: 40, alignItems: 'center', justifyContent: 'center', borderRadius: 20, }, actionIcon: { fontSize: 24, }, engagement: { paddingHorizontal: 16, paddingTop: 4, paddingBottom: 8, }, likesRow: { flexDirection: 'row', alignItems: 'center', marginBottom: 8, }, likesText: { color: Colors.text, fontSize: 14, fontWeight: 'bold', }, captionContainer: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-start', marginBottom: 8, }, captionText: { color: Colors.text, fontSize: 14, lineHeight: 20, }, captionUsername: { color: Colors.text, fontWeight: 'bold', fontSize: 14, lineHeight: 20, }, commentsLink: { color: Colors.textSecondary, fontSize: 14, marginTop: 8, }, chipsContainer: { flexDirection: 'row', gap: 8, paddingHorizontal: 16, paddingTop: 4, overflow: 'hidden', }, chip: { height: 28, alignItems: 'center', justifyContent: 'center', borderRadius: 14, backgroundColor: `${Colors.primary}33`, // 20% opacity paddingHorizontal: 12, }, chipText: { color: Colors.primary, fontSize: 12, fontWeight: '500', }, });