import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; import Sidebar from "../Sidebar"; import ChatListItem from "../chat/ChatListItem"; import Toast from "../Toast"; import AuthModal from "../AuthModal"; import { ProfileModal } from "../profile"; import RulesModal from "../../pages/RulesModal"; import ChatPage from "../../pages/ChatPage"; import { DesktopIcons } from "./DesktopIcons"; import { useChatList } from "../../hooks/useChatList"; import { useProfileData } from "../../hooks/useProfileData"; import { useAuthContext } from "../../context/AuthContext"; import { getPostForChat } from "../../stores/chatPostStore"; import { getChatDisplayInfo } from "../../utils/chatDisplay"; /** * DesktopChats — двухпанельный мессенджер десктопа: список чатов слева, * открытая переписка справа. Один компонент обслуживает /chats, /chats/new * и /chats/:chatId, поэтому список не перезагружается при переключении чатов. */ export default function DesktopChats() { const { t } = useTranslation(); const navigate = useNavigate(); const location = useLocation(); const { chatId } = useParams(); const isDraft = location.pathname === "/chats/new"; const { user } = useAuthContext(); const profileData = useProfileData(user); const { chats, loading, fetchChats, unreadMap, isAuthenticated, handleDeleteChat, deleteError, clearDeleteError, } = useChatList(); const [query, setQuery] = useState(""); const [modal, setModal] = useState(null); // Новое сообщение в открытом чате → обновляем превью в списке // (с небольшой задержкой, чтобы сервер успел сохранить сообщение). const refreshTimerRef = useRef(null); const refreshList = useCallback(() => { clearTimeout(refreshTimerRef.current); refreshTimerRef.current = setTimeout(() => fetchChats({ silent: true }), 700); }, [fetchChats]); useEffect(() => () => clearTimeout(refreshTimerRef.current), []); const items = useMemo(() => { const q = query.trim().toLowerCase(); return chats .map((chat) => { const post = getPostForChat(chat.id); const info = getChatDisplayInfo(chat, post, unreadMap, t); return { chat, post, info }; }) .filter(({ info }) => !q || String(info.title || "").toLowerCase().includes(q) || String(info.preview || "").toLowerCase().includes(q)); }, [chats, unreadMap, query, t]); const onDelete = async (id) => { const deleted = await handleDeleteChat(id); if (deleted && String(id) === String(chatId)) navigate("/chats", { replace: true }); }; const goFeed = (state) => navigate("/feed", state ? { state } : undefined); return (
{}} onNavClick={(key) => goFeed({ desktopNav: key })} isAuthenticated={isAuthenticated} onLoginClick={() => setModal("auth")} onRulesClick={() => setModal("rules")} onReviewsClick={() => navigate("/reviews")} onCreatePost={() => (isAuthenticated ? goFeed({ desktopAction: "create" }) : setModal("auth"))} onProfileClick={() => setModal("profile")} onMapClick={() => navigate("/feed?view=map")} profileData={profileData} />

{t("chat.chats")} {chats.length > 0 && {chats.length}}

{isAuthenticated && chats.length > 0 && ( )}
{!isAuthenticated ? (
{t("chat.loginToSee")}
) : loading ? ( Array.from({ length: 7 }, (_, i) => ( )) ) : chats.length === 0 && !isDraft ? (
{t("chat.noChats")}
) : items.length === 0 && !isDraft ? (
{t("desktop.chats.nothingFound")}
) : ( <> {isDraft && (
{location.state?.post?.title || t("desktop.chats.newChat")}
{t("desktop.chats.newChat")}
)} {items.map(({ chat, post }) => (
navigate(`/chats/${id}`)} onDelete={onDelete} />
))} )}
{!isAuthenticated ? (
{t("chat.loginToSee")}
) : chatId || isDraft ? ( ) : (
{t("desktop.chats.selectTitle")}
{t("desktop.chats.selectSub")}
)}
{deleteError && } {modal === "auth" && setModal(null)} />} {modal === "rules" && setModal(null)} />} {modal === "profile" && isAuthenticated && ( setModal(null)} initialData={profileData} /> )}
); }