({
+ getSupportConversation: builder.query({
+ query: () => ({
+ url: "/chat/support",
+ headers: { Accept: "application/json" },
+ }),
+ transformResponse: (response) => response.data ?? null,
+ }),
+ startSupportConversation: builder.mutation({
+ query: () => ({
+ url: "/chat/support",
+ method: "POST",
+ headers: { Accept: "application/json" },
+ }),
+ transformResponse: (response) => response.data,
+ }),
+ getChatMessages: builder.query({
+ query: ({ conversationId, page = 1, perPage = 50 }) => ({
+ url: `/chat/conversations/${conversationId}/messages?perPage=${perPage}&page=${page}`,
+ headers: { Accept: "application/json" },
+ }),
+ transformResponse: (response) => ({
+ items: response.data || [],
+ pagination: response.pagination || {},
+ }),
+ }),
+ sendChatMessage: builder.mutation({
+ query: ({ conversationId, body }) => ({
+ url: `/chat/conversations/${conversationId}/messages`,
+ method: "POST",
+ body: { body },
+ headers: { Accept: "application/json" },
+ }),
+ transformResponse: (response) => response.data,
+ }),
+ readChat: builder.mutation({
+ query: (conversationId) => ({
+ url: `/chat/conversations/${conversationId}/read`,
+ method: "POST",
+ headers: { Accept: "application/json" },
+ }),
+ }),
+ }),
+});
+
+export const {
+ useGetSupportConversationQuery,
+ useStartSupportConversationMutation,
+ useLazyGetChatMessagesQuery,
+ useSendChatMessageMutation,
+ useReadChatMutation,
+} = chatApi;
diff --git a/src/app/store.js b/src/app/store.js
index 1afa2ec..6d7f417 100644
--- a/src/app/store.js
+++ b/src/app/store.js
@@ -1,12 +1,64 @@
import { configureStore } from "@reduxjs/toolkit";
import { baseApi } from "./api/baseApi";
+<<<<<<< Updated upstream
+=======
+import { categoriesApi } from "./api/categories";
+import { searchApi } from "./api/searchApi";
+import { cartApi } from "./api/cartApi";
+import { brandsApi } from "./api/brandsApi";
+import { collectionsApi } from "./api/collectionsApi";
+import { favoritesApi } from "./api/favoritesApi";
+import { legalPagesApi } from "./api/legalPagesApi";
+import { locationApi } from "./api/locationApi";
+import { orderApi } from "./api/orderApi";
+import { mediaApi } from "./api/bannersApi";
+import { reviewsApi } from "./api/reviewApi";
+import { profileApi } from "./api/myProfileApi";
+import { contactApi } from "./api/contactUs";
+import { chatApi } from "./api/chatApi";
+>>>>>>> Stashed changes
const store = configureStore({
reducer: {
[baseApi.reducerPath]: baseApi.reducer,
+<<<<<<< Updated upstream
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(baseApi.middleware),
+=======
+ [categoriesApi.reducerPath]: categoriesApi.reducer,
+ [searchApi.reducerPath]: searchApi.reducer,
+ [cartApi.reducerPath]: cartApi.reducer,
+ [brandsApi.reducerPath]: brandsApi.reducer,
+ [collectionsApi.reducerPath]: collectionsApi.reducer,
+ [favoritesApi.reducerPath]: favoritesApi.reducer,
+ [legalPagesApi.reducerPath]: legalPagesApi.reducer,
+ [locationApi.reducerPath]: locationApi.reducer,
+ [orderApi.reducerPath]: orderApi.reducer,
+ [mediaApi.reducerPath]: mediaApi.reducer,
+ [reviewsApi.reducerPath]: reviewsApi.reducer,
+ [profileApi.reducerPath]: profileApi.reducer,
+ [contactApi.reducerPath]: contactApi.reducer,
+ [chatApi.reducerPath]: chatApi.reducer,
+ },
+ middleware: (getDefaultMiddleware) =>
+ getDefaultMiddleware().concat(
+ baseApi.middleware,
+ categoriesApi.middleware,
+ searchApi.middleware,
+ brandsApi.middleware,
+ collectionsApi.middleware,
+ favoritesApi.middleware,
+ legalPagesApi.middleware,
+ locationApi.middleware,
+ orderApi.middleware,
+ reviewsApi.middleware,
+ mediaApi.middleware,
+ profileApi.middleware,
+ contactApi.middleware,
+ chatApi.middleware,
+ ),
+>>>>>>> Stashed changes
});
export default store;
diff --git a/src/components/ChatWidget/ChatWidget.module.scss b/src/components/ChatWidget/ChatWidget.module.scss
new file mode 100644
index 0000000..dff3d4f
--- /dev/null
+++ b/src/components/ChatWidget/ChatWidget.module.scss
@@ -0,0 +1,167 @@
+.wrap {
+ position: fixed;
+ right: 24px;
+ bottom: 24px;
+ z-index: 1100;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+ gap: 12px;
+}
+
+.panel {
+ width: 380px;
+ max-width: calc(100vw - 32px);
+ height: 520px;
+ max-height: calc(100vh - 120px);
+ background: #fff;
+ border-radius: 16px;
+ box-shadow: 0 12px 40px rgba(15, 23, 42, 0.2);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 16px;
+ background: #d32824;
+ color: #fff;
+ font-weight: 700;
+}
+
+.iconBtn {
+ border: 0;
+ background: transparent;
+ color: #fff;
+ cursor: pointer;
+ display: flex;
+ padding: 4px;
+}
+
+.messages {
+ flex: 1;
+ overflow-y: auto;
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ background: #f8fafc;
+}
+
+.empty {
+ margin: auto;
+ color: #94a3b8;
+ font-size: 13px;
+ text-align: center;
+ padding: 0 16px;
+}
+
+.bubble {
+ max-width: 80%;
+ padding: 8px 12px;
+ border-radius: 14px;
+ font-size: 14px;
+ line-height: 1.4;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.bubble span {
+ display: block;
+ margin-top: 4px;
+ font-size: 11px;
+ opacity: 0.7;
+}
+
+.in {
+ align-self: flex-start;
+ background: #fff;
+ color: #0f172a;
+}
+
+.out {
+ align-self: flex-end;
+ background: #d32824;
+ color: #fff;
+}
+
+.composer {
+ display: flex;
+ gap: 8px;
+ padding: 10px 12px;
+ border-top: 1px solid #e2e8f0;
+ background: #fff;
+}
+
+.composer textarea {
+ flex: 1;
+ resize: none;
+ border: 1px solid #e2e8f0;
+ border-radius: 10px;
+ padding: 8px 10px;
+ font: inherit;
+ min-height: 40px;
+ max-height: 96px;
+}
+
+.composer button {
+ width: 40px;
+ border: 0;
+ border-radius: 10px;
+ background: #d32824;
+ color: #fff;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.composer button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.fab {
+ position: relative;
+ width: 56px;
+ height: 56px;
+ border: 0;
+ border-radius: 50%;
+ background: #d32824;
+ color: #fff;
+ cursor: pointer;
+ box-shadow: 0 8px 20px rgba(211, 40, 36, 0.35);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.badge {
+ position: absolute;
+ top: -4px;
+ right: -4px;
+ min-width: 20px;
+ height: 20px;
+ padding: 0 6px;
+ border-radius: 999px;
+ background: #0f172a;
+ color: #fff;
+ font-size: 11px;
+ font-weight: 700;
+ line-height: 20px;
+}
+
+@media (max-width: 480px) {
+ .wrap {
+ right: 16px;
+ bottom: 16px;
+ }
+
+ .panel {
+ width: calc(100vw - 32px);
+ height: calc(100vh - 100px);
+ }
+}
diff --git a/src/components/ChatWidget/index.jsx b/src/components/ChatWidget/index.jsx
new file mode 100644
index 0000000..6800e85
--- /dev/null
+++ b/src/components/ChatWidget/index.jsx
@@ -0,0 +1,296 @@
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { MessageCircle, Send, X } from "lucide-react";
+import { useAuth } from "../../context/authContext";
+import {
+ useGetSupportConversationQuery,
+ useLazyGetChatMessagesQuery,
+ useReadChatMutation,
+ useSendChatMessageMutation,
+ useStartSupportConversationMutation,
+} from "../../app/api/chatApi";
+import { getChatEcho, leaveChatChannel } from "../../utils/echo";
+import styles from "./ChatWidget.module.scss";
+
+function formatTime(value) {
+ if (!value) return "";
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return "";
+ return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
+}
+
+export default function ChatWidget() {
+ const { t } = useTranslation();
+ const { authToken, guestToken } = useAuth();
+ const ready = Boolean(authToken || guestToken);
+
+ const [open, setOpen] = useState(false);
+ const [hidden, setHidden] = useState(false);
+ const [conversation, setConversation] = useState(null);
+ const [messages, setMessages] = useState([]);
+ const [nextPage, setNextPage] = useState(null);
+ const [draft, setDraft] = useState("");
+ const [unread, setUnread] = useState(0);
+ const [loadingThread, setLoadingThread] = useState(false);
+
+ const listRef = useRef(null);
+ const subscribedId = useRef(null);
+ const openRef = useRef(open);
+ openRef.current = open;
+ const pendingPrepend = useRef(false);
+
+ const { data: existing, error } = useGetSupportConversationQuery(undefined, {
+ skip: !ready || hidden,
+ pollingInterval: open ? 0 : 15000,
+ });
+ const [startSupport] = useStartSupportConversationMutation();
+ const [fetchMessages] = useLazyGetChatMessagesQuery();
+ const [sendMessage, { isLoading: sending }] = useSendChatMessageMutation();
+ const [markRead] = useReadChatMutation();
+
+ useEffect(() => {
+ const status = error?.status;
+ if (status === 403 || status === 422) {
+ setHidden(true);
+ }
+ }, [error]);
+
+ useEffect(() => {
+ if (!existing) {
+ return;
+ }
+ setConversation(existing);
+ if (!open) {
+ setUnread(existing.unread_count || 0);
+ }
+ }, [existing, open]);
+
+ useLayoutEffect(() => {
+ if (!open || loadingThread || pendingPrepend.current) {
+ return;
+ }
+ const el = listRef.current;
+ if (!el) {
+ return;
+ }
+ el.scrollTop = el.scrollHeight;
+ }, [messages, open, loadingThread]);
+
+ const appendMessage = useCallback((message) => {
+ setMessages((current) => {
+ if (current.some((item) => item.id === message.id)) {
+ return current;
+ }
+ return [...current, message];
+ });
+ }, []);
+
+ const loadPage = useCallback(
+ async (conversationId, page = 1, prepend = false) => {
+ const result = await fetchMessages({ conversationId, page, perPage: 50 }).unwrap();
+ const items = (result.items || []).slice().reverse();
+ setNextPage(result.pagination?.next_page_url ? page + 1 : null);
+ setMessages((current) => {
+ if (!prepend) {
+ return items;
+ }
+ const known = new Set(current.map((item) => item.id));
+ return [...items.filter((item) => !known.has(item.id)), ...current];
+ });
+ return items;
+ },
+ [fetchMessages]
+ );
+
+ const openThread = useCallback(async () => {
+ setOpen(true);
+ setLoadingThread(true);
+ try {
+ let current = conversation;
+ if (!current?.id) {
+ current = await startSupport().unwrap();
+ setConversation(current);
+ }
+ await loadPage(current.id, 1, false);
+ await markRead(current.id);
+ setUnread(0);
+ } catch (err) {
+ if (err?.status === 403 || err?.status === 422) {
+ setHidden(true);
+ setOpen(false);
+ }
+ } finally {
+ setLoadingThread(false);
+ }
+ }, [conversation, loadPage, markRead, startSupport]);
+
+ useEffect(() => {
+ const conversationId = conversation?.id;
+ if (!conversationId || hidden) {
+ return undefined;
+ }
+
+ const echo = getChatEcho();
+ if (!echo) {
+ return undefined;
+ }
+
+ if (subscribedId.current && subscribedId.current !== conversationId) {
+ leaveChatChannel(subscribedId.current);
+ }
+
+ subscribedId.current = conversationId;
+ echo.private(`chat.${conversationId}`).listen(".message.sent", (payload) => {
+ appendMessage(payload);
+ if (openRef.current) {
+ markRead(conversationId);
+ setUnread(0);
+ } else {
+ setUnread((count) => count + 1);
+ }
+ });
+
+ return () => {
+ leaveChatChannel(conversationId);
+ subscribedId.current = null;
+ };
+ }, [appendMessage, conversation?.id, hidden, markRead]);
+
+ useEffect(() => {
+ if (!open || !conversation?.id || getChatEcho()) {
+ return undefined;
+ }
+
+ const timer = setInterval(async () => {
+ try {
+ const result = await fetchMessages({
+ conversationId: conversation.id,
+ page: 1,
+ perPage: 50,
+ }).unwrap();
+ const items = (result.items || []).slice().reverse();
+ setMessages((current) => {
+ const known = new Set(current.map((item) => item.id));
+ const incoming = items.filter((item) => !known.has(item.id));
+ return incoming.length ? [...current, ...incoming] : current;
+ });
+ } catch {
+ // polling is best-effort
+ }
+ }, 4000);
+
+ return () => clearInterval(timer);
+ }, [conversation?.id, fetchMessages, open]);
+
+ const handleScroll = async () => {
+ if (!listRef.current || !nextPage || !conversation?.id || loadingThread) {
+ return;
+ }
+ if (listRef.current.scrollTop > 40) {
+ return;
+ }
+ pendingPrepend.current = true;
+ const previousHeight = listRef.current.scrollHeight;
+ await loadPage(conversation.id, nextPage, true);
+ requestAnimationFrame(() => {
+ if (listRef.current) {
+ listRef.current.scrollTop = listRef.current.scrollHeight - previousHeight;
+ }
+ pendingPrepend.current = false;
+ });
+ };
+
+ const handleSend = async (event) => {
+ event.preventDefault();
+ const body = draft.trim();
+ if (!body || sending) {
+ return;
+ }
+
+ try {
+ let current = conversation;
+ if (!current?.id) {
+ current = await startSupport().unwrap();
+ setConversation(current);
+ }
+ const message = await sendMessage({
+ conversationId: current.id,
+ body,
+ }).unwrap();
+ appendMessage(message);
+ setDraft("");
+ } catch (err) {
+ if (err?.status === 403 || err?.status === 422) {
+ setHidden(true);
+ }
+ }
+ };
+
+ if (!ready || hidden) {
+ return null;
+ }
+
+ const otherName = conversation?.user?.name || t("chat.title");
+ const otherId = conversation?.user?.id;
+
+ return (
+
+ {open && (
+
+
+ {otherName}
+
+
+
+ {loadingThread &&
{t("chat.loading")}
}
+ {!loadingThread && messages.length === 0 && (
+
{t("chat.empty")}
+ )}
+ {messages.map((message) => {
+ const mine = otherId ? message.user?.id !== otherId : true;
+ return (
+
+
{message.body}
+
{formatTime(message.created_at)}
+
+ );
+ })}
+
+
+
+ )}
+
+
+
+ );
+}
diff --git a/src/i18n/locales/en.js b/src/i18n/locales/en.js
index a167e25..b3dedec 100644
--- a/src/i18n/locales/en.js
+++ b/src/i18n/locales/en.js
@@ -231,4 +231,12 @@ export default {
about_paragraph4:
"We are always open to co-operation and welcome feedback. Do you have an idea, question or suggestion? Write to us - we will be happy to answer!",
},
+ chat: {
+ title: "Support",
+ placeholder: "Write a message...",
+ send: "Send",
+ empty: "Send a message and we will reply soon.",
+ loading: "Loading...",
+ close: "Close",
+ },
};
diff --git a/src/i18n/locales/ru.js b/src/i18n/locales/ru.js
index eeec789..bf40f63 100644
--- a/src/i18n/locales/ru.js
+++ b/src/i18n/locales/ru.js
@@ -229,4 +229,12 @@ export default {
about_paragraph4:
"Мы всегда открыты к сотрудничеству и рады обратной связи. Есть идея, вопрос или предложение? Напишите нам — мы с удовольствием ответим!",
},
+ chat: {
+ title: "Поддержка",
+ placeholder: "Напишите сообщение...",
+ send: "Отправить",
+ empty: "Напишите сообщение, и мы скоро ответим.",
+ loading: "Загрузка...",
+ close: "Закрыть",
+ },
};
diff --git a/src/i18n/locales/tm.js b/src/i18n/locales/tm.js
index b04d246..c8f00ca 100644
--- a/src/i18n/locales/tm.js
+++ b/src/i18n/locales/tm.js
@@ -231,4 +231,12 @@ export default {
about_paragraph4:
"Hyzmatdaşlyga elmydama açyk we pikirleri kabul edýäris. Pikiriňiz, soragyňyz ýa-da teklibiňiz barmy? Bize ýazyň - jogap bermäge şat bolarys!",
},
+ chat: {
+ title: "Goldaw",
+ placeholder: "Hat ýazyň...",
+ send: "Ugrat",
+ empty: "Hat ýazyň, biz gysga wagtda jogap bereris.",
+ loading: "Ýüklenýär...",
+ close: "Ýap",
+ },
};
diff --git a/src/utils/echo.js b/src/utils/echo.js
new file mode 100644
index 0000000..591ddea
--- /dev/null
+++ b/src/utils/echo.js
@@ -0,0 +1,80 @@
+import Echo from "laravel-echo";
+import Pusher from "pusher-js";
+
+let echoClient = null;
+let echoToken = null;
+
+function getToken() {
+ const authTokenCookie = document.cookie
+ .split("; ")
+ .find((row) => row.startsWith("authToken="));
+ const guestTokenCookie = document.cookie
+ .split("; ")
+ .find((row) => row.startsWith("guestToken="));
+
+ if (authTokenCookie) return authTokenCookie.split("=")[1];
+ if (localStorage.getItem("authToken")) return localStorage.getItem("authToken");
+ if (guestTokenCookie) return guestTokenCookie.split("=")[1];
+ if (localStorage.getItem("guestToken")) return localStorage.getItem("guestToken");
+
+ return null;
+}
+
+function apiOrigin() {
+ const url = import.meta.env.VITE_API_URL || "https://mm.com.tm/api/v1/";
+ return url.replace(/\/?api\/v1\/?$/, "");
+}
+
+export function getChatEcho() {
+ const key = import.meta.env.VITE_REVERB_APP_KEY;
+ const token = getToken();
+
+ if (!key || !token) {
+ return null;
+ }
+
+ if (echoClient && echoToken !== token) {
+ echoClient.disconnect();
+ echoClient = null;
+ }
+
+ if (echoClient) {
+ return echoClient;
+ }
+
+ window.Pusher = Pusher;
+
+ const scheme = import.meta.env.VITE_REVERB_SCHEME || "http";
+ const port = Number(import.meta.env.VITE_REVERB_PORT || (scheme === "https" ? 443 : 8080));
+ const host = import.meta.env.VITE_REVERB_HOST || "127.0.0.1";
+
+ echoToken = token;
+ echoClient = new Echo({
+ broadcaster: "reverb",
+ key,
+ wsHost: host,
+ wsPort: port,
+ wssPort: port,
+ forceTLS: scheme === "https",
+ enabledTransports: ["ws", "wss"],
+ disableStats: true,
+ Pusher,
+ authEndpoint: `${apiOrigin()}/broadcasting/auth`,
+ auth: {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: "application/json",
+ },
+ },
+ });
+
+ return echoClient;
+}
+
+export function leaveChatChannel(conversationId) {
+ if (!echoClient || !conversationId) {
+ return;
+ }
+
+ echoClient.leave(`chat.${conversationId}`);
+}