"use client"; import { useState, useRef, useCallback, useEffect } from "react"; import { MoreHorizontal, Trash2, Loader2 } from "lucide-react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import { useTRPC } from "@/trpc/client"; import { useActivePet } from "@/context/ActivePetContext"; import { Dialog, DialogContent } from "@/components/ui/dialog"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Button } from "@/components/ui/button"; import { MentionTextarea } from "@/components/ui/mention-textarea"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, type CarouselApi, } from "@/components/ui/carousel"; import Link from "next/link"; import { getAvatarUrl } from "@/lib/avatar-url"; import { getMediaUrl } from "@/lib/media-url"; import { parseCaption } from "@/lib/parse-caption"; import { formatRelativeCompact } from "@/lib/format-relative-time"; import { PawButton } from "@/components/feed/PawButton"; import { PawBackButton } from "@/components/feed/PawBackButton"; import { PawRing } from "@/components/stories/PawRing"; import { VideoCard } from "@/components/video/VideoCard"; import type { PostCardPost } from "@/components/feed/PostCard"; import { useTranslations } from "next-intl"; interface PostDetailDialogProps { post: PostCardPost | null; open: boolean; onClose: () => void; onDeleted?: (postId: string) => void; } export function PostDetailDialog({ post, open, onClose, onDeleted }: PostDetailDialogProps) { const t = useTranslations("PostCard"); const tc = useTranslations("Comments"); const trt = useTranslations("RelativeTime"); const trpc = useTRPC(); const { activePetId } = useActivePet(); const queryClient = useQueryClient(); const [carouselApi, setCarouselApi] = useState(); const [currentSlide, setCurrentSlide] = useState(1); const [isEditingCaption, setIsEditingCaption] = useState(false); const [editCaptionValue, setEditCaptionValue] = useState(""); const [currentCaption, setCurrentCaption] = useState(null); const [showDeleteDialog, setShowDeleteDialog] = useState(false); const [body, setBody] = useState(""); const [pendingBody, setPendingBody] = useState(null); const commentsEndRef = useRef(null); useEffect(() => { if (!post) return; setCurrentCaption(post.caption); setEditCaptionValue(post.caption ?? ""); setIsEditingCaption(false); setBody(""); setCurrentSlide(1); }, [post?.id]); useEffect(() => { if (!carouselApi) return; setCurrentSlide(carouselApi.selectedScrollSnap() + 1); carouselApi.on("select", () => setCurrentSlide(carouselApi.selectedScrollSnap() + 1)); }, [carouselApi]); const { data: commentsData, isLoading: commentsLoading } = useQuery({ ...trpc.comments.listByPost.queryOptions({ postId: post?.id ?? "", limit: 50 }), enabled: !!post?.id && open, }); const updateCaptionMutation = useMutation( trpc.posts.updateCaption.mutationOptions({ onSuccess: (updated) => { setCurrentCaption(updated.caption); setIsEditingCaption(false); toast.success(t("captionUpdated")); }, onError: () => toast.error(t("captionUpdateError")), }) ); const deleteMutation = useMutation( trpc.posts.delete.mutationOptions({ onSuccess: () => { setShowDeleteDialog(false); toast.success(t("postDeleted")); onClose(); if (post) onDeleted?.(post.id); }, onError: () => toast.error(t("deleteError")), }) ); const createCommentMutation = useMutation( trpc.comments.create.mutationOptions({ onSuccess: () => { setPendingBody(null); if (post?.id) { void queryClient.invalidateQueries({ queryKey: trpc.comments.listByPost.queryOptions({ postId: post.id, limit: 50 }).queryKey, }); } setTimeout(() => commentsEndRef.current?.scrollIntoView({ behavior: "smooth" }), 150); }, onError: () => { setBody((prev) => prev || (pendingBody ?? "")); setPendingBody(null); toast.error(tc("postError")); }, }) ); const deleteCommentMutation = useMutation( trpc.comments.delete.mutationOptions({ onSuccess: () => { if (post?.id) { void queryClient.invalidateQueries({ queryKey: trpc.comments.listByPost.queryOptions({ postId: post.id, limit: 50 }).queryKey, }); } }, onError: () => toast.error(tc("deleteError")), }) ); const handleSubmitComment = useCallback(() => { if (!body.trim() || !post || !activePetId) return; const trimmed = body.trim(); setPendingBody(trimmed); setBody(""); createCommentMutation.mutate({ postId: post.id, petId: activePetId, body: trimmed }); setTimeout(() => commentsEndRef.current?.scrollIntoView({ behavior: "smooth" }), 50); }, [body, post, activePetId, createCommentMutation]); const handleCommentKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); handleSubmitComment(); } }, [handleSubmitComment] ); const formatRelativeTime = (date: Date | string) => formatRelativeCompact(date, trt); if (!post) return null; const { pet, images } = post; const isCarousel = images.length > 1; const isOwnPost = activePetId === pet.id; const avatarUrl = getAvatarUrl(pet.avatarKey); const comments = commentsData?.comments ?? []; // Extracted so it renders identically in the mobile bar and the desktop right-panel const headerInner = ( <> {avatarUrl && } {pet.name[0]?.toUpperCase() ?? "?"}

{pet.name}

{formatRelativeTime(post.createdAt)}

{isOwnPost ? ( <> { setEditCaptionValue(currentCaption ?? ""); setIsEditingCaption(true); }} className="cursor-pointer" > {t("editCaption")} setShowDeleteDialog(true)} className="cursor-pointer text-destructive focus:text-destructive" > {t("deletePost")} ) : ( <> {t("reportPost")} {t("blockPet", { name: pet.name })} )} ); const mediaContent = post.type === "VIDEO" && post.videoPost ? ( ) : images.length > 0 && ( isCarousel ? (
{images.map((img) => ( {/* eslint-disable-next-line @next/next/no-img-element */} {currentCaption ))} {currentSlide} / {images.length}
{images.map((_, i) => (
) : ( // eslint-disable-next-line @next/next/no-img-element {currentCaption ) ); return ( <> { if (!o) onClose(); }}> {/* Layout: Mobile → flex-col: [header][image 45dvh][right-panel scrollable] Desktop → flex-row: [image flex-1 left][right-panel 360px right] */} {/* Mobile-only header — sits above the image on small screens */}
{headerInner}
{/* Image column — fixed 45dvh strip on mobile, flex-1 full-height on desktop */}
{mediaContent}
{/* Right panel: desktop header + scrollable body + sticky input */}
{/* Desktop-only header */}
{headerInner}
{/* Scrollable body */}
{isEditingCaption ? (
) : ( currentCaption && (

{parseCaption(currentCaption).map((seg, i) => seg.type === "hashtag" ? ( #{seg.tag} ) : seg.type === "mention" ? ( @{seg.name} ) : ( {seg.text} ) )}

) )} {activePetId && (
{comments.length > 0 && ( {comments.length === 1 ? tc("countSingular") : tc("countPlural", { count: comments.length })} )}
)}
{commentsLoading && (
)} {!commentsLoading && comments.length === 0 && (

{tc("empty")}

)} {comments.map((comment) => { const commentAvatarUrl = getAvatarUrl(comment.pet.avatarKey); const isOwnComment = comment.pet.id === activePetId; return (
{commentAvatarUrl && } {comment.pet.name[0]?.toUpperCase()}
{comment.pet.name} {formatRelativeTime(comment.createdAt)}

{parseCaption(comment.body).map((seg, i) => seg.type === "hashtag" ? ( #{seg.tag} ) : seg.type === "mention" ? ( @{seg.name} ) : ( {seg.text} ) )}

{isOwnComment && activePetId && ( )}
); })} {pendingBody && (
✓
{tc("sending")}

{pendingBody}

)}
{/* Sticky comment input */} {activePetId && (
)}
{t("deleteTitle")} {t("deleteDesc")} {t("keepPost")} deleteMutation.mutate({ postId: post.id })} disabled={deleteMutation.isPending} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > {t("yesDelete")} ); }