"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { FiSearch } from "react-icons/fi";
import { BsThreeDotsVertical } from "react-icons/bs";
import { IoChevronBackOutline, IoClose } from "react-icons/io5";
import ChatWindow from "@/components/ChatWindow/Window";
import {
  getAllChats,
  getCounterOffers,
  indexNegotiation,
} from "@/lib/actions/chatActions";
import { useAppSelector } from "@/app/store/hooks";
import { RootState } from "@/app/store/store";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { useDispatch } from "react-redux";
import { useRouter, useSearchParams } from "next/navigation";
import { toast } from "react-toastify";
import { useTranslations } from "next-intl";
import { socket } from "./chatSocket";
import { IoIosArrowDown, IoIosArrowUp, IoIosClose } from "react-icons/io";
import { MdOutlineHistory, MdOutlineLocalOffer } from "react-icons/md";
import { FaStar } from "react-icons/fa";
import {
  getImageUrl,
  resolveOtherAttributeSmallImage,
} from "@/hooks/useImageUrl";
import DataNotFound from "@/components/common/DataNotFound";
import RouteLoader from "@/components/common/RouteLoader";
import {
  MobileNumber,
  OtherAttribute,
  VehicleNumber,
} from "../../../../types/common-types";
import { getVehicleDisplayNumber } from "../my-orders/MyOrders";
import { getStoredLocale } from "@/lib/getLocale";

export default function ChatPage() {
  const [activeDrawer, setActiveDrawer] = useState<null | "addreview">(null);
  const closeDrawer = () => setActiveDrawer(null);
  const [activeUser, setActiveUser] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [showSearch, setShowSearch] = useState(false);
  const t = useTranslations();
  const locale = getStoredLocale();
  const { user } = useAppSelector((state: RootState) => state.auth);
  const dispatch = useDispatch();
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState(searchTerm);
  const viewAllProductsRef = useRef<HTMLDivElement>(null);
  const [otherAttribute, setOtherAttribute] = useState<
    | OtherAttribute<"mobile_number">
    | OtherAttribute<"vehicle_number_plate">
    | null
  >(null);

  const [initialFetchComplete, setInitialFetchComplete] =
    useState<boolean>(false);

  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 1024);
    checkMobile();

    const handleClickOutside = (event: MouseEvent) => {
      if (
        viewAllProductsRef.current &&
        !viewAllProductsRef.current.contains(event.target as Node)
      ) {
        setMenuOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    window.addEventListener("resize", checkMobile);
    return () => {
      window.removeEventListener("resize", checkMobile);
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const [allChats, setAllChats] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchLoading, setSearchLoading] = useState<boolean>(false);
  const [selectedUser, setSelectedUser] = useState<any>();
  const [conversationId, setConversationId] = useState<string>("");
  const [productSnapshot, setProductSnapshot] = useState<any | null>(null);
  const [openChatId, setOpenChatId] = useState<string | null>(null);
  const handleToggle = (chatId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setOpenChatId((prev) => (prev === chatId ? null : chatId));
  };

  const [hasMore, setHasMore] = useState(true);
  const sidebarRef = useRef<HTMLDivElement>(null);
  const [page, setPage] = useState<number>(1);

  const initialLoadComplete = useRef(false);

  useEffect(() => {
    if (allChats.length > 0 && !initialLoadComplete.current) {
      initialLoadComplete.current = true;
    }
  }, [allChats.length]);

  useEffect(() => {
    if (allChats.length < 1) return;

    socket.auth = { token: user?.token };
    socket.connect();

    socket.on("connect", () => {
      // console.log("Connected to Socket", socket.id);
    });

    const handleConversationUnreadCount = (data: any) => {
      const { details, productId } = data?.data;

      const updatedChats = allChats.map((ch: any) => {
        if (ch.productId === productId) {
          ch.unreadCount = 0;

          details?.forEach((chat: any) => {
            if (conversationId === chat.conversationId) {
              ch.unreadCount = 0;
            } else {
              ch.unreadCount += chat.unreadCount;
            }
            const senderId = chat.senderId || chat.receiverId;

            ch.otherUsers?.forEach((user: any) => {
              if (user._id === senderId) {
                if (conversationId === chat.conversationId) {
                  user.unreadCount = 0;
                } else {
                  user.unreadCount = chat.unreadCount;
                }
              }
            });
          });
        }
        return ch;
      });

      setAllChats(updatedChats);
    };

    const handleConversationUpdate = (data: any) => {
      const id = data?._id;

      function getChatIdByOtherUserConversationId(
        targetConversationId: string,
      ) {
        const chat = allChats.find((c) =>
          c.otherUsers?.some(
            (user: any) => user.conversationId === targetConversationId,
          ),
        );
        return chat || null;
      }

      setAllChats((prevChats) => {
        const parentChat = getChatIdByOtherUserConversationId(id);

        // no parent chat found for this chat
        if (!parentChat) return prevChats;

        const idx = prevChats.findIndex((obj) => obj._id === parentChat._id);

        if (idx === -1) {
          return prevChats;
        }

        const updatedChats = [...prevChats];

        const finalChatOrder = [
          updatedChats[idx],
          ...updatedChats.slice(0, idx),
          ...updatedChats.slice(idx + 1),
        ];

        finalChatOrder[0].lastMessage = data.lastMessage;
        finalChatOrder[0].updatedAt = data.updatedAt;

        return finalChatOrder;
      });
    };

    const handleConversationCreated = (data: any) => {
      const { productId } = data;

      const prevChat = allChats.find(
        (chat: any) => chat.productId === productId,
      );

      if (prevChat) {
        prevChat.otherUsers.push(data.otherUsers[0]);
        setAllChats([...allChats]);
      } else {
        setAllChats((prev) => [data, ...prev]);
      }
    };

    socket.on("conversation_updated", handleConversationUpdate);
    socket.on("conversation_unread_count", handleConversationUnreadCount);
    socket.on("conversation_created", handleConversationCreated);

    // join a conversation
    socket.emit("join_conversation", conversationId);

    return () => {
      socket.off("connect", () => {
        // console.log("Disconnected To Socket");
      });

      socket.off("conversation_unread_count", handleConversationUnreadCount);
      socket.off("conversation_updated", handleConversationUpdate);
      socket.off("conversation_created", handleConversationCreated);
    };
  }, [user?.token, allChats]);

  const searchParams = useSearchParams();

  const renderOtherAttribute = (otherAttr: any = null) => {
    if (!otherAttr) {
      if (otherAttribute?.valueType === "mobile_number") {
        return `${otherAttribute?.content[0]?.number}`;
      }

      return getVehicleDisplayNumber(
        otherAttribute?.content[0] as VehicleNumber,
        locale,
      );
    } else {
      if (otherAttr?.valueType === "mobile_number") {
        return `${otherAttr?.content[0]?.number}`;
      }

      return getVehicleDisplayNumber(
        otherAttr?.content[0] as VehicleNumber,
        locale,
      );
    }
  };

  const fetchAllChats = useCallback(
    async (search: string = "") => {
      try {
        const productId = searchParams.get("id");
        const payload = {
          user_id: user.id,
        };

        if (productId) {
          (payload as any).productId = productId;
        }

        if (search) {
          setSearchLoading(true);
        } else {
          setLoading(true);
        }
        const response = await getAllChats(user.token, payload, {
          page,
          search,
        });

        const totalPages = response.totalPages ?? 0;
        setHasMore(page < totalPages);

        if (response.success && Array.isArray(response?.data)) {
          if (!initialFetchComplete && !search) {
            setInitialFetchComplete(true);
          }
          let chats = [...response.data];
          const priorityProductId =
            searchParams.get("id") ?? chats[0]?.productId;

          if (priorityProductId) {
            chats.sort((a, b) => {
              if (
                a.productId === priorityProductId &&
                b.productId !== priorityProductId
              )
                return -1;
              if (
                a.productId !== priorityProductId &&
                b.productId === priorityProductId
              )
                return 1;
              return 0;
            });
          }

          setAllChats((prev) => (page === 1 ? chats : [...prev, ...chats]));

          if (page === 1 && response.data.length > 0) {
            const selectedChat = chats[0];

            const otherAttr:
              | OtherAttribute<"mobile_number">
              | OtherAttribute<"vehicle_number_plate">
              | null = selectedChat?.productSnapshot?.isOtherAttribute
                ? selectedChat?.productSnapshot?.otherAttribute
                : null;
            let otherAttrData = null;

            if (otherAttr) {
              if (otherAttr?.valueType === "vehicle_number_plate") {
                otherAttrData = {
                  ...otherAttr,
                  valueType: "vehicle_number_plate",
                } as OtherAttribute<"vehicle_number_plate">;
              } else if (otherAttr?.valueType === "mobile_number") {
                otherAttrData = {
                  ...otherAttr,
                } as OtherAttribute<"mobile_number">;
              }
            }

            setOtherAttribute(otherAttr);

            const createdAt = new Date(
              selectedChat?.createdAt,
            ).toLocaleTimeString("en-US", {
              hour: "2-digit",
              minute: "2-digit",
              hour12: true,
            });

            let obj = selectedChat?.otherUsers[0];
            obj = {
              ...obj,
              seller: response?.data[0]?.seller,
            };

            setSelectedUser(obj);
            setConversationId(selectedChat._id);
            setProductSnapshot({
              productId: selectedChat.productId,
              product: selectedChat.productSnapshot,
              initialOffer: selectedChat?.initialOffer ?? 10000,
              seller: selectedChat.seller,
              initialText: selectedChat?.initialMessage || "",
              createdAt: createdAt,
            });

            // on first selection
            socket.emit("conversation_read", {
              conversationId: selectedChat._id,
              userId: selectedChat?.otherUsers[0]?._id,
            });

            setAllChats((prev) => {
              return prev.map((ch) => {
                if (ch._id === selectedChat._id) {
                  return {
                    ...ch,
                    unreadCount: 0,
                  };
                } else {
                  return ch;
                }
              });
            });
          }
        }
      } catch (error: any) {
        if (checkAuthErrorGet(error, dispatch, router)) return;
        const errorMsg =
          error?.response?.data?.message || t("validation.error_msg");
        toast.error(errorMsg);
      } finally {
        setLoading(false);
        setSearchLoading(false);
      }
    },
    [user?.token, page, initialFetchComplete],
  );

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchTerm(value);
    setPage(1); // Reset to first page whenever search changes
    // setAllChats([]); // clear previous results
    // setHasMore(true); // reset hasMore
  };
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearch(searchTerm);
    }, 400); // wait 400ms

    return () => clearTimeout(handler);
  }, [searchTerm]);

  useEffect(() => {
    fetchAllChats(debouncedSearch);
  }, [debouncedSearch, page]);

  const handleScroll = () => {
    const sidebar = sidebarRef.current;
    if (!sidebar) return;

    const isAtBottom =
      sidebar.scrollTop + sidebar.clientHeight >= sidebar.scrollHeight - 10;

    if (isAtBottom && hasMore) {
      setPage((prev) => prev + 1);
    }
  };

  const [menuOpen, setMenuOpen] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState<
    "negotiation" | "seller" | null
  >(null);
  const containerRef = useRef<HTMLDivElement | null>(null);

  const handleOpenDropdown = (type: "negotiation" | "seller") => {
    setActiveDropdown((prev) => (prev === type ? null : type));
    setMenuOpen(false);
  };

  const [negotiationData, setNegotiationData] = useState<any[] | null>(null);
  const [counterOfferData, setCounterOfferData] = useState<any[] | null>(null);

  const handleNegotiation = async () => {
    try {
      const response = await indexNegotiation(user.token, {
        conversation_id: conversationId,
      });

      if (response.success) {
        if (Array.isArray(response.data) && response.data.length > 0) {
          handleOpenDropdown("negotiation");
          setNegotiationData(response?.data);
        } else {
          toast.error(t("no_record_found"));
        }
      } else {
        toast.error(t("no_record_found"));
      }
    } catch (error: any) {
      console.log("Error: ", error);
      if (checkAuthErrorGet(error, dispatch, router)) return;

      const errorMsg =
        error?.response?.data?.message || t("validation.error_msg");
      toast.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleCounterOffer = async () => {
    try {
      const response = await getCounterOffers(user.token, {
        productId: productSnapshot.productId,
      });

      if (response.success) {
        if (Array.isArray(response.data) && response.data.length > 0) {
          handleOpenDropdown("seller");
          setCounterOfferData(response?.data);
        } else {
          toast.error(t("no_record_found"));
        }
      } else {
        toast.error(t("no_record_found"));
      }
    } catch (error: any) {
      console.log("Error: ", error);
      if (checkAuthErrorGet(error, dispatch, router)) return;

      const errorMsg =
        error?.response?.data?.message || t("validation.error_msg");
      toast.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleProductRedirect = async (id: string) => {
    router.push(`/products/${id}`);
  };

  const handleRedirect = async (seller: string) => {
    if (seller == user.id) {
      router.push("/listing");
    } else {
      router.push(
        `/products?category=fresh-recommendations&sellerId=${seller}`,
      );
    }
  };

  const handleSelectConversation = (chat: any, user: any, createdAt: any) => {
    // Mark conversation as read
    socket.emit("conversation_read", {
      conversationId: user?.conversationId,
      userId: user?._id,
    });

    const updatedChats = allChats.map((ch: any) => {
      if (ch.productId === chat?.productId) {
        ch.unreadCount -= user.unreadCount;
        ch.otherUsers.forEach((us: any) => {
          if (us._id === user._id) {
            us.unreadCount = 0;
          }
        });
      }
      return ch;
    });

    setAllChats(updatedChats);

    setProductSnapshot({
      product: chat?.productSnapshot,
      productId: chat?.productId,
      initialOffer: chat?.initialOffer,
      seller: chat?.seller,
      initialText: chat?.initialMessage,
      createdAt: createdAt,
    });
    let obj = user;
    obj = {
      ...obj,
      seller: chat?.seller,
    };
    setSelectedUser(obj);
    setConversationId(user.conversationId);
  };

  if (loading && !initialLoadComplete.current && allChats.length === 0) {
    return <div>Loading...</div>;
  }

  if (
    !loading &&
    allChats.length === 0 &&
    !debouncedSearch &&
    initialFetchComplete
  ) {
    return <DataNotFound />;
  }
  return (
    <RouteLoader>
      <section className="pt-2.5 p-6 max-lg:p-0">
        <div className="max-w-w1660 mx-auto relative">
          <div className="flex h-[calc(100vh-120px)] max-lg:block max-lg:h-full">
            {/* Sidebar */}
            <div
              ref={sidebarRef}
              onScroll={handleScroll}
              className={`custom-scrollbar w-1/4 h-full bg-white max-lg:w-full dark:bg-card overflow-auto shadow-[rgba(0,0,0,0.1)_0px_0px_1px_0px,rgba(0,0,0,0.06)_0px_0px_2px_0px]
 ${activeUser && isMobile ? "hidden" : ""}`}
            >
              <div className="relative max-lg:shadow-sm">
                {showSearch && (
                  <div className="absolute top-0 left-0 w-full bg-white z-10 flex items-center justify-between px-6 py-3 shadow-md dark:bg-darkbg">
                    <div className="flex items-center w-full relative">
                      <input
                        type="text"
                        placeholder="Search..."
                        value={searchTerm}
                        onChange={handleSearchChange}
                        autoFocus
                        className="w-full py-2 px-4 border border-gray-300 rounded-md focus:outline-none dark:bg-background dark:border-darkborder dark:text-white"
                      />
                      {searchLoading && (
                        <div className="absolute right-12 top-1/2 transform -translate-y-1/2">
                          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary500"></div>
                        </div>
                      )}
                    </div>
                    <IoClose
                      size={24}
                      className="ml-3 text-neutrals800 cursor-pointer dark:text-neutrals400 dark:hover:text-white"
                      onClick={() => {
                        setShowSearch(false);
                        setSearchTerm("");
                        setPage(1);
                        setDebouncedSearch("");
                      }}
                    />
                  </div>
                )}
                <div className="flex justify-between items-center py-4 px-6 max-md:px-5">
                  <h2 className="text-xl font-bold text-neutrals800 dark:text-white">
                    {t("chat.chat")}
                  </h2>
                  <div className="flex items-center gap-2">
                    <FiSearch
                      size={20}
                      className="text-neutrals800 cursor-pointer dark:text-neutrals200"
                      onClick={() => setShowSearch(true)}
                    />
                    {/* <BsThreeDotsVertical
                      size={20}
                      className="text-neutrals800 cursor-pointer dark:text-neutrals200"
                    /> */}
                  </div>
                </div>
              </div>
              {
                allChats.length > 0 ? (
                  <div className="mt-3 max-lg:mt-0">
                    {allChats.map((chat: any) => {
                      const otherAttr:
                        | OtherAttribute<"mobile_number">
                        | OtherAttribute<"vehicle_number_plate">
                        | null = chat?.productSnapshot?.isOtherAttribute
                          ? chat?.productSnapshot?.otherAttribute
                          : null;
                      let otherAttrData = null;

                      if (otherAttr) {
                        if (otherAttr?.valueType === "vehicle_number_plate") {
                          otherAttrData = {
                            ...otherAttr,
                            valueType: "vehicle_number_plate",
                          } as OtherAttribute<"vehicle_number_plate">;
                        } else if (otherAttr?.valueType === "mobile_number") {
                          otherAttrData = {
                            ...otherAttr,
                          } as OtherAttribute<"mobile_number">;
                        }
                      }
                      let createdAt = new Date(
                        chat?.createdAt,
                      ).toLocaleTimeString("en-US", {
                        hour: "2-digit",
                        minute: "2-digit",
                        hour12: true,
                      });

                      let updatedAt = new Date(
                        chat?.updatedAt,
                      ).toLocaleTimeString("en-US", {
                        hour: "2-digit",
                        minute: "2-digit",
                        hour12: true,
                      });
                      const isOpen = openChatId === chat._id;
                      return (
                        <div
                          key={chat?._id}
                          onClick={() => {
                            if (isMobile) setActiveUser(true);

                            handleSelectConversation(
                              chat,
                              chat?.otherUsers[0],
                              createdAt,
                            );

                            setOtherAttribute(otherAttrData);
                          }}
                          className={`cursor-pointer transition-colors duration-200
                          ${conversationId === chat?._id
                              ? "bg-gray-50 dark:bg-background"
                              : ""
                            }`}
                        >
                          <div className="relative flex items-start justify-between border-l-0 border border-neutrals100 border-r-2 border-r-white hover:border-r-primary500 py-4 px-6 pr-9 max-lg:border-t-white dark:border-darkborder max-[1680px]:px-5 max-[1680px]:pr-8 max-[1280px]:px-2 max-lg:px-5 max-lg:pr-9 rtl:max-lg:pl-9 rtl:max-lg:pr-5 last:border-b-0 rtl:pl-9 rtl:pr-6 rtl:max-[1680px]:pl-8 rtl:max-[1680px]:pr-5 rtl:border-r-0 rtl:border-l-2 rtl:hover:border-l-primary500">
                            <div className="flex items-start gap-3 w-full">
                              {/* Product Avatar */}

                              {Number(chat.unreadCount) > 0 && (
                                <span className="absolute top-[18px] right-2 bg-red-500 text-white text-[10px] font-semibold w-4 h-4 px-[6px] py-[2px] rounded-full shadow-sm leading-none min-w-[18px] min-h-[18px] flex items-center justify-center max-md:right-2.5 rtl:left-2 rtl:right-auto">
                                  {chat.unreadCount}
                                </span>
                              )}
                              <div
                                className="relative min-w-[45px]"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleProductRedirect(chat?.productId);
                                }}
                              >
                                <img
                                  src={resolveOtherAttributeSmallImage({
                                    otherAttr: otherAttrData,
                                    productImage: chat?.productSnapshot?.image,
                                  })}
                                  alt="Preview"
                                  onError={(e) => {
                                    e.currentTarget.onerror = null;
                                    e.currentTarget.src = "/default.jpg";
                                  }}
                                  className="w-[45px] h-[45px] rounded-full border-2 border-primary100 dark:border-darkborder object-cover bg-neutrals100 dark:bg-neutrals200"
                                />
                              </div>

                              {/* Text Content */}
                              <div className="w-full">
                                {user?.id === chat?.buyer && (
                                  <div className="relative group inline-block">
                                    <img
                                      src={`${getImageUrl(
                                        chat?.otherUsers[0]?.profileImage?.url,
                                        true,
                                      )}`}
                                      alt={user?.name}
                                      onError={(e) => {
                                        if (
                                          e.currentTarget.src.endsWith(
                                            "/profile-avatar.png",
                                          )
                                        )
                                          return;
                                        e.currentTarget.onerror = null;
                                        e.currentTarget.src =
                                          "/profile-avatar.png";
                                      }}
                                      width={20}
                                      height={20}
                                      className="relative z-10 inline-block cursor-pointer rounded-full w-5 h-5"
                                    />{" "}
                                    <span className="text-xs text-gray-500 dark:text-neutrals400">
                                      {chat?.otherUsers[0]?.name}
                                    </span>
                                    <div className="absolute top-8 -left-10 z-50 hidden group-hover:block w-fit min-w-52 bg-white rounded-lg shadow-lg border border-neutrals100 dark:bg-background dark:border-darkborder rtl:-right-10 rtl:-left-auto cursor-auto transition-all duration-150">
                                      <div className="absolute -top-2 left-10 w-4 h-4 bg-white border-l border-t border-neutrals100 rotate-45 z-10 dark:bg-darkbg dark:border-darkborder rtl:right-10 rtl:left-auto"></div>
                                      <div className="flex items-start p-2.5 border rounded-lg border-neutrals100 gap-2 dark:border-darkborder dark:bg-darkbg">
                                        <div className="w-[70px]">
                                          <div className="relative">
                                            <img
                                              src={`${getImageUrl(
                                                chat?.otherUsers[0]
                                                  ?.profileImage?.url,
                                                true,
                                              )}`}
                                              alt="Preview"
                                              width={93}
                                              height={93}
                                              className="rounded-md object-cover w-16 h-16"
                                              onError={(e) => {
                                                if (
                                                  e.currentTarget.src.endsWith(
                                                    "/profile-avatar.png",
                                                  )
                                                )
                                                  return;
                                                e.currentTarget.onerror = null;
                                                e.currentTarget.src =
                                                  "/profile-avatar.png";
                                              }}
                                            />
                                            <img
                                              src="/checkmark.svg"
                                              className="absolute top-0 -right-0.5 text-kzgreen600 bg-white rounded-full text-xs"
                                              alt="checkmark"
                                            />
                                          </div>
                                        </div>

                                        <div className="flex flex-col justify-center">
                                          <p className="font-semibold text-sm text-neutrals800 line-clamp-1 mb-0 dark:text-neutrals200">
                                            {chat?.otherUsers[0]?.name ||
                                              "Unknown User"}
                                          </p>
                                          <p className="text-xs text-gray-500 dark:text-neutrals400">
                                            {t("chat.seller")}
                                          </p>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                )}

                                <div className="flex items-center justify-between">
                                  <p className="font-semibold text-sm text-neutrals900 dark:text-neutrals200 line-clamp-1">
                                    {renderOtherAttribute(otherAttrData)} |{" "}
                                    {chat?.productSnapshot?.title}
                                  </p>
                                  <p className="text-[11px] text-neutrals500 dark:text-neutrals400 whitespace-nowrap ml-2 rtl:ml-0 rtl:mr-2">
                                    {updatedAt}
                                  </p>
                                </div>

                                {/* Last message */}
                                <p className="text-xs font-bold text-primary500 dark:text-primary400 mt-0.5 line-clamp-1">
                                  {process.env.NEXT_PUBLIC_CURRENCY_TYPE}{" "}
                                  {chat?.productSnapshot?.price}
                                </p>

                                {/* Seller toggle (for seller screen) */}
                                {user?.id === chat?.seller && (
                                  <div className="relative w-full mt-1 ">
                                    <div
                                      onClick={(e) =>
                                        handleToggle(chat?._id, e)
                                      }
                                      className="flex justify-end items-center text-gray-400 dark:text-gray-500 cursor-pointer"
                                    >
                                      {isOpen ? (
                                        <IoIosArrowUp />
                                      ) : (
                                        <IoIosArrowDown />
                                      )}
                                    </div>

                                    {isOpen && (
                                      <div className="custom-scrollbar max-h-[200px] overflow-auto mt-1">
                                        {chat?.otherUsers?.map(
                                          (otherUser: any) => (
                                            <div
                                              key={otherUser?._id}
                                              onClick={(e) => {
                                                e.stopPropagation();

                                                handleSelectConversation(
                                                  chat,
                                                  otherUser,
                                                  createdAt,
                                                );
                                                setOtherAttribute(
                                                  otherAttrData,
                                                );

                                                if (isMobile)
                                                  setActiveUser(true);
                                              }}
                                              className="group flex gap-1 p-1"
                                            >
                                              <img
                                                src={`${getImageUrl(
                                                  otherUser.profileImage?.url,
                                                  true,
                                                )}`}
                                                alt={otherUser.name}
                                                onError={(e) => {
                                                  if (
                                                    e.currentTarget.src.endsWith(
                                                      "/profile-avatar.png",
                                                    )
                                                  )
                                                    return;
                                                  e.currentTarget.onerror =
                                                    null;
                                                  e.currentTarget.src =
                                                    "/profile-avatar.png";
                                                }}
                                                className="w-[24px] h-[24px] rounded-full object-cover border border-gray-200 dark:border-darkborder"
                                              />
                                              <div>
                                                <div className="font-semibold text-sm text-neutrals800 line-clamp-2 mb-0 dark:text-neutrals200 max-sm:text-xs">
                                                  <p className="flex items-center gap-1">
                                                    {otherUser?.name}{" "}
                                                    {Number(
                                                      otherUser.unreadCount,
                                                    ) > 0 && (
                                                        <span className="bg-red-500 text-white text-[9px] font-semibold w-4 h-4 rounded-full shadow-sm leading-none flex items-center justify-center">
                                                          {otherUser.unreadCount}
                                                        </span>
                                                      )}
                                                  </p>
                                                </div>
                                                <div className="flex items-center gap-1 w-full whitespace-nowrap mb-2">
                                                  <FaStar className="text-orange-500 text-sm max-sm:text-xs" />
                                                  {otherUser?.review.total >
                                                    0 ? (
                                                    <p className="text-xs text-gray-800 dark:text-primary400">
                                                      <span className="font-semibold">
                                                        {
                                                          otherUser?.review
                                                            ?.average
                                                        }
                                                      </span>{" "}
                                                      <span className="text-gray-500 dark:text-neutrals400">
                                                        (
                                                        {
                                                          otherUser?.review
                                                            .total
                                                        }{" "}
                                                        {t("review")})
                                                      </span>
                                                    </p>
                                                  ) : (
                                                    <p className="text-xs text-gray-800 dark:text-primary400">
                                                      <span className="text-gray-500 dark:text-neutrals400">
                                                        {t("no_review_yet")}
                                                      </span>
                                                    </p>
                                                  )}
                                                </div>
                                              </div>
                                            </div>
                                          ),
                                        )}
                                      </div>
                                    )}
                                  </div>
                                )}
                                {user?.id === chat?.buyer && (
                                  <div className="group flex mt-1">
                                    <div className="absolute top-5 -left-10 z-50 hidden group-hover:block w-fit min-w-40 bg-white rounded-lg shadow-lg border border-neutrals100 dark:bg-background dark:border-darkborder rtl:-right-10 rtl:-left-auto cursor-auto">
                                      <div className="absolute -top-2 right-6 w-4 h-4 bg-white border-l border-t border-neutrals100 rotate-45 z-10 dark:bg-darkbg dark:border-darkborder"></div>
                                      <div className="flex p-2.5 border rounded-lg border-neutrals100 gap-2 dark:border-darkborder dark:bg-darkbg">
                                        <div className="w-[70px]">
                                          <div className="relative">
                                            <img
                                              src={`${getImageUrl(
                                                chat?.otherUsers[0]
                                                  ?.profileImage?.url,
                                                true,
                                              )}`}
                                              alt="Preview"
                                              width={93}
                                              onError={(e) => {
                                                if (
                                                  e.currentTarget.src.endsWith(
                                                    "/profile-avatar.png",
                                                  )
                                                )
                                                  return;
                                                e.currentTarget.onerror = null;
                                                e.currentTarget.src =
                                                  "/profile-avatar.png";
                                              }}
                                              height={93}
                                              className="rounded-md object-cover w-16 h-16"
                                            />
                                            <img
                                              src="/checkmark.svg"
                                              className="absolute top-0 -right-0.5 text-kzgreen600 bg-white rounded-full text-xs"
                                              alt="checkmark"
                                            />
                                          </div>
                                        </div>
                                        <div className="w-fit">
                                          <p className="font-semibold text-sm text-neutrals800 line-clamp-1 mb-0 dark:text-neutrals200">
                                            {chat?.otherUsers[0]?.name}
                                          </p>
                                          <p className="text-xs text-gray-500 dark:text-neutrals400">
                                            {t("chat.seller")}
                                          </p>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                ) : debouncedSearch ? (
                  <p className="mt-4 pl-5 dark:text-neutrals200">
                    {t("not_found")}
                  </p>
                ) : initialFetchComplete ? null : null // <DataNotFound />
              }
            </div>

            {selectedUser && (
              <div
                key={`${selectedUser._id}_${conversationId}`}
                className={`flex flex-col bg-gray-50 dark:bg-cardfooter ${activeUser && isMobile ? "flex" : "max-lg:hidden"
                  } max-lg:w-full lg:w-3/4`}
              >
                <div className="flex items-center justify-between px-6 py-4 bg-white max-lg:px-3 shadow-headerShadow dark:bg-card">
                  <div className="flex items-center gap-3 max-sm:gap-2 w-full">
                    {isMobile && (
                      <IoChevronBackOutline
                        onClick={() => setActiveUser(false)}
                        className="text-neutrals800 text-xl max-lg:block cursor-pointer dark:text-white rtl:rotate-180"
                      />
                    )}
                    {!isMobile && (
                      <IoChevronBackOutline className="text-neutrals800 text-xl dark:text-white rtl:rotate-180" />
                    )}

                    <div className="relative">
                      <img
                        src={`${getImageUrl(
                          selectedUser?.profileImage?.url,
                          true,
                        )}`}
                        alt={selectedUser?.name}
                        onError={(e) => {
                          if (
                            e.currentTarget.src.endsWith("/profile-avatar.png")
                          )
                            return;
                          e.currentTarget.onerror = null;
                          e.currentTarget.src = "/profile-avatar.png";
                        }}
                        className="w-10 h-10 rounded-full border-2 border-primary100"
                      />
                      {/* <div className="absolute bottom-0 right-0 border-2 border-neutrals100 w-3.5 h-3.5 bg-green-400 rounded-full"></div> */}
                    </div>

                    <div>
                      {selectedUser?.seller === user?.id ? (
                        <>
                          <p className="font-semibold text-sm dark:text-white">
                            {selectedUser?.name} ({t("chat.buyer")})
                          </p>
                          <p className="text-xs text-gray-500 dark:text-neutrals400">
                            {renderOtherAttribute()}{" "}
                            {productSnapshot?.product?.title}
                          </p>
                        </>
                      ) : (
                        <>
                          <p className="font-semibold text-sm dark:text-white">
                            {productSnapshot?.product?.title}
                          </p>
                          <p className="text-xs text-gray-500 dark:text-neutrals400">
                            {selectedUser?.name} ({t("chat.seller")})
                          </p>
                        </>
                      )}
                    </div>
                  </div>

                  <div
                    className="relative flex items-center gap-2 justify-normal"
                    ref={containerRef}
                  >
                    <button
                      onClick={() => {
                        handleNegotiation();
                      }}
                      className="block w-full text-left text-sm px-2 py-2 bg-primary500 text-white hover:bg-primary400 dark:bg-primary400 whitespace-nowrap rounded-lg max-md:px-2"
                      aria-label="Options"
                    >
                      {/* <span className="max-sm:hidden">
                        {t("chat.negotiation")}
                      </span> */}
                      <MdOutlineHistory
                        className="max-sm:block text-xl"
                        title={t("chat.negotiation")}
                      />
                    </button>
                    {selectedUser?.seller == user?.id && (
                      <button
                        onClick={() => {
                          handleCounterOffer();
                        }}
                        className="block w-full text-left text-sm px-2 py-2 bg-primary500 text-white hover:bg-primary400 dark:bg-primary400 whitespace-nowrap rounded-lg max-md:px-2"
                        aria-label="Options"
                      >
                        {/* <span className="max-sm:hidden">
                          {t("chat.counter_offers")}
                        </span> */}
                        <MdOutlineLocalOffer
                          className="max-sm:block text-xl"
                          title={t("chat.counter_offers")}
                        />
                      </button>
                    )}

                    <button
                      type="button"
                      aria-expanded={menuOpen}
                      aria-label="Options"
                      onPointerDown={(e) => e.stopPropagation()}
                      onClick={(e) => {
                        e.stopPropagation();
                        setMenuOpen((prev) => !prev);
                        setActiveDropdown(null);
                      }}
                      className="inline-flex items-center"
                    >
                      <BsThreeDotsVertical
                        size={18}
                        className="text-gray-500 dark:text-neutrals400 cursor-pointer"
                      />
                    </button>

                    {menuOpen && (
                      <div
                        ref={viewAllProductsRef}
                        role="menu"
                        onPointerDown={(e) => e.stopPropagation()}
                        className="absolute right-0 top-6 mt-2 w-auto min-w-[160px] bg-white border border-gray-100 dark:bg-background dark:border-darkborder shadow-lg rounded-md z-50 rtl:right-auto rtl:left-0"
                      >
                        <button
                          onClick={() => handleRedirect(selectedUser?.seller)}
                          className="block w-full text-left text-sm text-neutrals800 dark:text-neutrals400 px-4 py-2 hover:bg-gray-100 dark:hover:bg-darkbg"
                          role="menuitem"
                        >
                          {t("chat.view_all_products")}
                        </button>
                      </div>
                    )}

                    {activeDropdown === "negotiation" && (
                      <div
                        onPointerDown={(e) => e.stopPropagation()}
                        className="absolute right-0 top-8 mt-2 w-auto min-w-[500px] max-md:min-w-[340px] bg-white border border-gray-200 rounded-lg shadow-lg dark:bg-card dark:border-gray-700 z-40 overflow-hidden rtl:right-auto rtl:left-0 max-[370px]:min-w-[300px]"
                      >
                        <div className="flex items-center justify-between drop-box-head p-4 bg-primary800 dark:bg-primary400 max-sm:p-2 max-sm:px-3">
                          <span className="w-full block text-white">
                            {t("chat.negotiation")}
                          </span>
                          <div
                            className="text-white text-3xl cursor-pointer"
                            onClick={() => setActiveDropdown(null)}
                          >
                            <IoIosClose width={28} height={28} />
                          </div>
                        </div>

                        <ul className="p-4 text-sm text-gray-700 dark:text-gray-200 max-h-[320px] overflow-auto dark:bg-card space-y-4 max-sm:p-2">
                          {negotiationData ? (
                            negotiationData.map((item, index: number) => {
                              if (item.type == "counter_offer") {
                                return (
                                  <li key={index}>
                                    <div className="text-xs w-fit text-neutrals500 mb-1.5 ml-auto dark:text-neutrals400">
                                      09 Sep 26 04:24 PM
                                    </div>
                                    <div className="ml-auto max-w-fit min-w-[200px] border rounded-lg overflow-hidden bg-white border-neutrals200 dark:bg-background dark:border-card">
                                      <div className="flex items-center justify-between gap-1 bg-neutrals100 p-2.5 dark:bg-gray-700">
                                        <span className="text-sm text-primary500 dark:text-neutrals300">
                                          {t("chat.counter_offer")}:
                                        </span>
                                        <span className="text-sm text-primary500 font-bold dark:text-primary400">
                                          {item.currency} {item.amount}
                                        </span>
                                      </div>
                                    </div>
                                  </li>
                                );
                              } else {
                                return (
                                  <li key={index}>
                                    <div className="text-xs w-fit text-neutrals500 mb-1.5 mr-auto dark:text-neutrals400">
                                      09 Sep 26 04:24 PM
                                    </div>
                                    <div className="mr-auto max-w-fit min-w-[200px] border rounded-lg overflow-hidden bg-white border-neutrals200 dark:bg-background dark:border-card">
                                      <div className="flex items-center justify-between gap-1 bg-neutrals100 p-2.5 dark:bg-gray-700">
                                        <span className="text-sm text-primary500 dark:text-neutrals300">
                                          {t("chat.seller_offer")}:
                                        </span>
                                        <span className="text-sm text-primary500 font-bold dark:text-primary400">
                                          {item.currency} {item.amount}
                                        </span>
                                      </div>
                                    </div>
                                  </li>
                                );
                              }
                            })
                          ) : (
                            <li>
                              <div className="text-xs w-fit text-neutrals500 mb-1.5 ml-auto dark:text-neutrals400">
                                {t("no_negoitation_data")}
                              </div>
                            </li>
                          )}
                        </ul>
                      </div>
                    )}

                    {activeDropdown === "seller" && (
                      <div
                        onPointerDown={(e) => e.stopPropagation()}
                        className="absolute right-0 top-8 mt-2 w-auto min-w-[500px] max-md:min-w-[340px] bg-white border border-gray-200 rounded-lg shadow-lg dark:bg-card dark:border-gray-700 z-40 overflow-hidden rtl:right-auto rtl:left-0 max-[370px]:min-w-[300px]"
                      >
                        <div className="flex items-center justify-between drop-box-head p-4 bg-primary800 dark:bg-primary400 max-sm:p-2 max-sm:px-3">
                          <span className="w-full block text-white">
                            {t("chat.counter_offers")}
                          </span>
                          <div
                            className="text-white text-3xl cursor-pointer"
                            onClick={() => setActiveDropdown(null)}
                          >
                            <IoIosClose width={28} height={28} />
                          </div>
                        </div>

                        <ul className="p-4 text-sm text-gray-700 dark:text-gray-200 max-h-[320px] overflow-auto dark:bg-card space-y-4 max-sm:p-2">
                          {counterOfferData ? (
                            counterOfferData?.map((item, index: number) => {
                              return (
                                <li key={item?.userId || index}>
                                  <div className="buyer-offer-wrap">
                                    <div className="p-2 px-3 border border-neutrals100 flex items-center justify-between gap-3 rounded-md dark:border-darkborder max-sm:px-2 max-sm:gap-2 max-[370px]:gap-1">
                                      <div className="flex items-center gap-3 max-sm:gap-1">
                                        <div className="relative min-w-[40px] max-sm:min-w-[30px]">
                                          <img
                                            src={`${getImageUrl(
                                              item.profileImage?.url,
                                              true,
                                            )}`}
                                            alt={item?.name}
                                            width={40}
                                            height={40}
                                            onError={(e) => {
                                              if (
                                                e.currentTarget.src.endsWith(
                                                  "/profile-avatar.png",
                                                )
                                              )
                                                return;
                                              e.currentTarget.onerror = null;
                                              e.currentTarget.src =
                                                "/profile-avatar.png";
                                            }}
                                            className="w-[40px] h-[40px] rounded-full max-sm:w-[30px] max-sm:h-[30px]"
                                          />
                                        </div>
                                        <p className="min-w-28 font-semibold text-base text-neutrals900 dark:text-neutrals200 truncate max-w-[250px] max-[1680px]:max-w-[190px] max-[1440px]:max-w-[150px] max-[1240px]:max-w-[110px] max-lg:max-w-[350px] max-sm:max-w-[210px] max-sm:text-sm">
                                          {item?.name}
                                        </p>
                                      </div>
                                      <div className="buyer-dtails flex items-center gap-3 max-sm:gap-1">
                                        <div className="max-w-fit mr-auto border rounded-lg overflow-hidden bg-white border-neutrals200 rtl:mr-auto rtl:ml-0 dark:bg-background dark:border-card">
                                          <div className="flex items-center justify-between gap-1 bg-neutrals100 p-2.5 dark:bg-background whitespace-nowrap max-sm:px-1.5">
                                            <span className="text-sm text-primary500 font-bold dark:text-primary400 max-sm:text-sm">
                                              {
                                                process.env
                                                  .NEXT_PUBLIC_CURRENCY_TYPE
                                              }{" "}
                                              {item?.bestOffer}
                                            </span>
                                          </div>
                                        </div>
                                        <button
                                          onClick={() => {
                                            setConversationId(
                                              item.conversationId,
                                            );
                                            setSelectedUser({
                                              seller: productSnapshot.seller,
                                              conversationId:
                                                item.conversationId,
                                              name: item.name,
                                              profileImage: item.profileImage,
                                              _id: item.profileImage._id,
                                            });
                                            setActiveDropdown(null);
                                          }}
                                          className="flex items-center gap-2 px-3 py-2 text-base rounded-lg transition-all text-white bg-primary500 hover:bg-primary600 dark:bg-primary400 max-sm:px-2 max-[370px]:px-1.5"
                                        >
                                          <svg
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            xmlns="http://www.w3.org/2000/svg"
                                          >
                                            <path
                                              fillRule="evenodd"
                                              clipRule="evenodd"
                                              d="M11.9921 3C6.99416 3 2.98499 6.95015 3.00004 11.7792L3.00005 11.7816C2.99999 13.4614 3.49098 15.1045 4.4124 16.5088C4.46503 16.5806 4.51426 16.655 4.55994 16.7315L4.56356 16.7375L4.56708 16.7437C4.64102 16.873 4.72871 17.0473 4.78914 17.2397C4.84444 17.4157 4.90814 17.7028 4.8249 18.0091L4.82403 18.0123L4.04982 20.8128L6.72863 19.846C6.99541 19.7363 7.28132 19.6803 7.56993 19.6814L7.56708 20.4313L7.56792 19.6814C7.56859 19.6814 7.56926 19.6814 7.56993 19.6814C7.83919 19.682 8.10608 19.7318 8.35742 19.8284L8.35851 19.8288C8.51054 19.8875 9.11616 20.1125 9.715 20.2801C10.3037 20.4449 11.3908 20.6447 12.1599 20.6447C17.1329 20.6447 20.9999 16.6518 21 11.7889C20.9998 11.1856 20.936 10.5838 20.8095 9.99391L20.8092 9.99234C19.9657 6.01596 16.3474 3 11.9921 3ZM1.50005 11.7827C1.48295 6.08891 6.19977 1.5 11.9921 1.5C17.0471 1.5 21.2839 5.00303 22.2764 9.68031C22.4248 10.3732 22.4998 11.0797 22.5 11.7883C22.5 17.4637 17.9774 22.1447 12.1599 22.1447C11.2133 22.1447 9.98483 21.9133 9.31072 21.7246C8.64793 21.5391 7.99375 21.2959 7.81907 21.2284C7.73838 21.1974 7.65268 21.1815 7.56624 21.1814L7.56423 21.1814C7.47098 21.181 7.37863 21.1996 7.29277 21.236L7.27407 21.2439L4.09313 22.3919C4.10134 22.3885 4.10952 22.3851 4.11768 22.3816L3.82083 21.6928L4.07543 22.3983L4.09313 22.3919C3.96107 22.446 3.82192 22.4811 3.67987 22.4959L3.63987 22.5001L3.59966 22.5C3.4409 22.4995 3.28382 22.4675 3.13751 22.4059C2.99121 22.3443 2.85858 22.2543 2.74731 22.141C2.63605 22.0278 2.54836 21.8936 2.48933 21.7462C2.4303 21.5989 2.40109 21.4412 2.40341 21.2825L2.40374 21.26L2.40542 21.2375C2.4131 21.1349 2.43136 21.0333 2.45991 20.9345L2.45857 20.9394L3.1814 21.1392L2.46194 20.9276C2.46126 20.9299 2.46058 20.9322 2.45991 20.9345L3.35756 17.6875C3.35773 17.6881 3.3579 17.6886 3.35806 17.6891C3.36431 17.709 3.36577 17.7185 3.36581 17.7185C3.36582 17.7185 3.36573 17.7178 3.3656 17.7164C3.36506 17.7107 3.36189 17.6729 3.37738 17.6159L4.10114 17.8125L3.37826 17.6127L3.37738 17.6159L3.35756 17.6875C3.34119 17.6361 3.30995 17.5678 3.26845 17.4945C3.26965 17.4964 3.27084 17.4984 3.27203 17.5004L3.91598 17.1159L3.26489 17.4882C3.26609 17.4903 3.26727 17.4924 3.26845 17.4945C3.24588 17.4571 3.22151 17.4208 3.19543 17.3858L3.18261 17.3686L3.17079 17.3507C2.08111 15.6981 1.50021 13.7622 1.50005 11.7827ZM1.50005 11.7827C1.50005 11.7831 1.50005 11.7835 1.50005 11.7839L2.25005 11.7816L1.50005 11.7815C1.50005 11.7819 1.50005 11.7823 1.50005 11.7827Z"
                                              fill="currentColor"
                                              className="dark:fill-white"
                                            />
                                            <path
                                              d="M7.56993 19.6814C7.28132 19.6803 6.99541 19.7363 6.72863 19.846L4.04982 20.8128L4.82403 18.0123L4.8249 18.0091C4.90814 17.7028 4.84444 17.4157 4.78914 17.2397C4.72871 17.0473 4.64102 16.873 4.56708 16.7437L4.56356 16.7375L4.55994 16.7315C4.51426 16.655 4.46503 16.5806 4.4124 16.5088C3.49098 15.1045 2.99999 13.4614 3.00005 11.7816L3.00004 11.7792C2.98499 6.95015 6.99416 3 11.9921 3C16.3474 3 19.9657 6.01596 20.8092 9.99234L20.8095 9.99391C20.936 10.5838 20.9998 11.1856 21 11.7889M7.56993 19.6814L7.56708 20.4313L7.56792 19.6814C7.56859 19.6814 7.56926 19.6814 7.56993 19.6814ZM7.56993 19.6814C7.83919 19.682 8.10608 19.7318 8.35742 19.8284L8.35851 19.8288C8.51054 19.8875 9.11616 20.1125 9.715 20.2801C10.3037 20.4449 11.3908 20.6447 12.1599 20.6447C17.1329 20.6447 20.9999 16.6518 21 11.7889M21 11.7889L21.75 11.7886M1.50005 11.7827C1.48295 6.08891 6.19977 1.5 11.9921 1.5C17.0471 1.5 21.2839 5.00303 22.2764 9.68031C22.4248 10.3732 22.4998 11.0797 22.5 11.7883C22.5 17.4637 17.9774 22.1447 12.1599 22.1447C11.2133 22.1447 9.98483 21.9133 9.31072 21.7246C8.64793 21.5391 7.99375 21.2959 7.81907 21.2284M1.50005 11.7827C1.50021 13.7622 2.08111 15.6981 3.17079 17.3507L3.18261 17.3686L3.19543 17.3858C3.22151 17.4208 3.24588 17.4571 3.26845 17.4945M1.50005 11.7827C1.50005 11.7831 1.50005 11.7835 1.50005 11.7839L2.25005 11.7816L1.50005 11.7815C1.50005 11.7819 1.50005 11.7823 1.50005 11.7827ZM7.81907 21.2284C7.81938 21.2286 7.81876 21.2283 7.81907 21.2284ZM7.81907 21.2284L8.08833 20.5284M7.81907 21.2284C7.73838 21.1974 7.65268 21.1815 7.56624 21.1814L7.56423 21.1814C7.47098 21.181 7.37863 21.1996 7.29277 21.236L7.27407 21.2439L4.09313 22.3919M4.09313 22.3919C4.10134 22.3885 4.10952 22.3851 4.11768 22.3816L3.82083 21.6928L4.07543 22.3983L4.09313 22.3919ZM4.09313 22.3919C3.96107 22.446 3.82192 22.4811 3.67987 22.4959L3.63987 22.5001L3.59966 22.5C3.4409 22.4995 3.28382 22.4675 3.13751 22.4059C2.99121 22.3443 2.85858 22.2543 2.74731 22.141C2.63605 22.0278 2.54836 21.8936 2.48933 21.7462C2.4303 21.5989 2.40109 21.4412 2.40341 21.2825L2.40374 21.26L2.40542 21.2375C2.4131 21.1349 2.43136 21.0333 2.45991 20.9345M2.45991 20.9345L2.45857 20.9394L3.1814 21.1392L2.46194 20.9276C2.46126 20.9299 2.46058 20.9322 2.45991 20.9345ZM2.45991 20.9345L3.35756 17.6875M3.35756 17.6875C3.35773 17.6881 3.3579 17.6886 3.35806 17.6891C3.36431 17.709 3.36577 17.7185 3.36581 17.7185C3.36582 17.7185 3.36573 17.7178 3.3656 17.7164C3.36506 17.7107 3.36189 17.6729 3.37738 17.6159M3.35756 17.6875L3.37738 17.6159M3.35756 17.6875C3.34119 17.6361 3.30995 17.5678 3.26845 17.4945M3.37738 17.6159L4.10114 17.8125L3.37826 17.6127L3.37738 17.6159ZM3.26845 17.4945C3.26965 17.4964 3.27084 17.4984 3.27203 17.5004L3.91598 17.1159L3.26489 17.4882C3.26609 17.4903 3.26727 17.4924 3.26845 17.4945Z"
                                              stroke="currentColor"
                                              className="dark:stroke-white"
                                              strokeWidth="0.2"
                                              strokeMiterlimit="10"
                                              strokeLinecap="round"
                                            />
                                          </svg>
                                        </button>
                                      </div>
                                    </div>
                                  </div>
                                </li>
                              );
                            })
                          ) : (
                            <li>
                              <div className="text-xs w-fit text-neutrals500 mb-1.5 ml-auto dark:text-neutrals400">
                                {t("no_counter_offer")}
                              </div>
                            </li>
                          )}
                        </ul>
                      </div>
                    )}
                  </div>
                </div>

                {/* Messages */}
                {conversationId && selectedUser && (
                  <ChatWindow
                    socket={socket}
                    key={`${conversationId}-${selectedUser._id}`}
                    product={productSnapshot}
                    conversationId={conversationId}
                    currUser={selectedUser}
                  />
                )}
              </div>
            )}
          </div>
        </div>
      </section>
    </RouteLoader>
  );
}
