import {useRef, useState, useEffect} from "react"; import PinIcon from "../components/icons/PinIcon"; import CalendarIcon from "../components/icons/CalendarIcon"; import PhoneIcon from "../components/icons/PhoneIcon"; import TrashIcon from "../components/icons/TrashIcon"; import CheckIcon from "../components/icons/CheckIcon"; import {useContactSeller} from "../hooks/useContactSeller"; import {useRevealPhone} from "../hooks/useRevealPhone"; import {useAuthContext} from "../context/AuthContext"; import {getImageUrl} from "../config/authConstants"; import {CATEGORY_PET} from "../config/feedConstants"; import {POST_STATUS_CLOSED, POST_STATUS_MODERATION, POST_STATUS_REJECTED} from "../config/postConstants"; import {getFoundAt, formatFoundDate} from "../utils/foundAt"; import DateCalendarPopup from "../components/DateCalendarPopup"; import RewardPopup from "../components/feed/RewardPopup"; import Toast from "../components/Toast"; import {useTranslation} from 'react-i18next'; export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onLocationClick, onAuthRequired, compact }) { const { t, i18n } = useTranslation(); const [showCalendar, setShowCalendar] = useState(false); const [showReward, setShowReward] = useState(false); const [descExpanded, setDescExpanded] = useState(false); const [descTruncated, setDescTruncated] = useState(false); const [imgIndex, setImgIndex] = useState(0); const dateAnchorRef = useRef(null); const rewardAnchorRef = useRef(null); const descRef = useRef(null); const imgTouchStartRef = useRef(null); const { isAuthenticated, user } = useAuthContext(); // Своё объявление: писать самому себе нельзя (бэкенд отвечает 400), кнопку не показываем. // isOwner тут не подходит — в общей ленте он false и для своих объявлений. const isOwnAd = user?.id != null && ad.userId != null && String(ad.userId) === String(user.id); const { contactSeller, error: contactError, clearError } = useContactSeller(ad); const phoneReveal = useRevealPhone(ad.id); useEffect(() => { const check = () => { if (!descExpanded && descRef.current) { setDescTruncated(descRef.current.scrollHeight > descRef.current.clientHeight + 1); } }; check(); window.addEventListener("resize", check); return () => window.removeEventListener("resize", check); }, [descExpanded]); const handleContact = (e) => { e.stopPropagation(); if (!isAuthenticated) { if (onAuthRequired) onAuthRequired(); return; } contactSeller(); }; const images = Array.isArray(ad.images) ? ad.images : []; // Карусель включается для любого объявления с несколькими фото: листать // можно и в ленте, и в детальной модалке. Полноэкранного просмотрщика нет. const carousel = images.length > 1; const hasImages = images.length > 0; // Листание фото прямо в карточке: на телефоне — свайпом, на десктопе — // стрелками и точками. Листание зациклено: с последнего кадра переходим на // первый и наоборот. const goToImage = (target) => { const len = images.length; if (!len) return; setImgIndex(((target % len) + len) % len); }; const handleImgTouchStart = (e) => { if (!carousel) return; imgTouchStartRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }; }; const handleImgTouchEnd = (e) => { const start = imgTouchStartRef.current; imgTouchStartRef.current = null; if (!start || !carousel) return; const dx = e.changedTouches[0].clientX - start.x; const dy = e.changedTouches[0].clientY - start.y; // Реагируем только на явно горизонтальный жест — вертикальный скролл ленты // не должен переключать фото. if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) { const len = images.length; const step = dx < 0 ? 1 : -1; setImgIndex(i => (i + step + len) % len); } }; // На карточке показываем только город; полный адрес — запасной вариант, // чтобы у старых объявлений без города не пропала кнопка карты const address = ad.city || ad.district || ad.address || ad.location; const createdAt = ad.createdAt ? new Date(ad.createdAt).toLocaleDateString("ru-RU") : null; const isClosed = ad.status === POST_STATUS_CLOSED; const pendingStatusText = ad.status === POST_STATUS_MODERATION ? t('postCard.statusModeration') : ad.status === POST_STATUS_REJECTED ? t('postCard.statusRejected') : null; // Для питомцев «найдено» — это хорошая новость с воссоединением, поэтому // формулировка эмоциональнее, чем сухое «Найдено». const isPet = ad.category === CATEGORY_PET; const foundText = isPet ? t('postCard.petFoundStatus') : t('postCard.foundStatus'); const foundDate = isClosed ? formatFoundDate(getFoundAt(ad), i18n.language) : null; // aria-подпись собираем целиком: статус не должен читаться только цветом. const foundAriaText = foundDate ? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate}) : foundText; // Номер в ленту не приходит: в «Моих объявлениях» и в админке он есть в ad.phone, // в общей ленте его открывают кнопкой (proof-of-work на бэкенде) — и автор // своего объявления тоже, чтобы видеть то же, что покупатель. // У закрытого объявления номер не показывается: вещь уже вернулась. const shownPhone = ad.phone || phoneReveal.phone; const canRevealPhone = !shownPhone && ad.phoneVisible && !isClosed; const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss"; const typeBadge = (
{ad.type === "loss" ? t('postCard.loss') : t('postCard.found')}
); // У находки вознаграждения нет — его предлагает только владелец const hasReward = ad.reward && ad.type !== "found"; // В ленте кнопка стоит в строке под описанием; в compact (объявление, // открытое с карты) этой строки нет — кнопка лежит на фото справа снизу, // чтобы её было видно сразу, без прокрутки окна. const rewardButton = hasReward && ( <> {showReward && ( setShowReward(false)} /> )} ); return (
{ad.title}
{authorLabel && (
{authorLabel}
)}
{pendingStatusText && (
{pendingStatusText}
)} {typeBadge}
{images.length > 0 ? ( carousel ? (
{images.map((raw, i) => ( {ad.title} ))}
) : ( {ad.title} ) ) : ( {ad.emoji || "📋"} )} {/* Плашка статуса поверх фото: при быстром скролле шапка карточки проезжает мимо, а фото с плашкой — нет. */} {isClosed && ( {foundText} )} {carousel && ( <>
{images.map((_, i) => (
)} {compact && rewardButton}
{!compact && (
{address && (
{ e.stopPropagation(); onLocationClick?.(ad); }} > {address}
)}
{onEdit && isOwner && (!isClosed || allowEditClosed) && ( )} {onDelete && isOwner && ( )} {createdAt && (
{ e.stopPropagation(); setShowCalendar(s => !s); }} > {createdAt} {showCalendar && ( setShowCalendar(false)} anchorRef={dateAnchorRef} /> )}
)}
)}
setDescExpanded(v => !v) : undefined} > {ad.description}
{!compact && (
{rewardButton}
)}
{shownPhone ? ( e.stopPropagation()}> {shownPhone} ) : canRevealPhone && ( )}
{isOwnAd ? ( {t('postCard.ownAd')} ) : ( )}
{onMarkFound && isOwner && !isClosed && (
)} {isClosed && (
{/* Кнопка «найдено» становится неактивной подтверждением: видно, что действие уже применено, и повторно не нажать. */} {/* Отмена случайного нажатия — автору; в админ-панели это и есть возврат объявления в ленту. */} {onReopen && isOwner && ( )}
)} {phoneReveal.error && ( )} {contactError && ( )}
); }