import { useEffect, useState } from 'react'; import { useCat, useDeleteCat } from '@/hooks/useCats'; import { useLikeStatus, useLikeCat, useUnlikeCat } from '@/hooks/useLikes'; import { useAuth } from '@/hooks/useAuth'; import { useToast } from '@/components/Toast'; import { Avatar, AvatarFallback } from '@/components/ui/avatar'; import { X, Heart, Trash2 } from 'lucide-react'; interface CatModalProps { catId: number; onClose: () => void; } export default function CatModal({ catId, onClose }: CatModalProps) { const { user, updateUser } = useAuth(); const { data, isLoading } = useCat(catId); const { data: likeData, refetch: refetchLike } = useLikeStatus(catId); const likeMutation = useLikeCat(catId); const unlikeMutation = useUnlikeCat(catId); const deleteMutation = useDeleteCat(); const { toast } = useToast(); const [liked, setLiked] = useState(false); const [likeCount, setLikeCount] = useState(0); const [imageLoaded, setImageLoaded] = useState(false); useEffect(() => { if (likeData) setLiked(likeData.liked); }, [likeData]); useEffect(() => { if (data?.cat) setLikeCount(data.cat.likes_count); }, [data]); useEffect(() => { document.body.style.overflow = 'hidden'; return () => { document.body.style.overflow = ''; }; }, []); useEffect(() => { const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); }; window.addEventListener('keydown', handler); return () => window.removeEventListener('keydown', handler); }, [onClose]); const cat = data?.cat; const isOwner = cat && user && cat.user_id === user.id; const toggleLike = async () => { if (isOwner || !user || !cat) return; if (liked) { setLiked(false); setLikeCount((c) => c - 1); try { const res = await unlikeMutation.mutateAsync(); if (res.ownerPoints !== undefined && cat.user_id === user.id) updateUser({ ...user, points: res.ownerPoints }); refetchLike(); } catch { setLiked(true); setLikeCount((c) => c + 1); } } else { setLiked(true); setLikeCount((c) => c + 1); toast('Нравится ❤️'); try { await likeMutation.mutateAsync(); refetchLike(); } catch { setLiked(false); setLikeCount((c) => c - 1); } } }; const handleDelete = async () => { if (!isOwner || !cat) return; try { await deleteMutation.mutateAsync(cat.id); toast('Удалено'); onClose(); } catch { toast('Ошибка удаления', 'error'); } }; if (isLoading || !cat) { return (
{dateStr}
@{cat.username} {cat.caption || 'Без подписи'}