// "use client";
// import React, { useEffect, useState } from "react";
// import { Button, message, Modal } from "antd";
// import Image from "next/image";
// import { useTranslations, useLocale } from "next-intl";
// import { MdOutlineShoppingCart } from "react-icons/md";
// import { useRouter } from "next/navigation";
// import { useDispatch, useSelector } from "react-redux";
// import { fetchCartLength } from "@/store/cart/actions";
// import { fetchFavouritesLength } from "@/store/cart/actions";
// import axios from "@/utils/axios-config";
// import { useMutation } from "@tanstack/react-query";
// import { CgShoppingCart } from "react-icons/cg";
// import Link from "next/link";
// import { usePathname } from "next/navigation";
// import "swiper/css";
// import "swiper/css/navigation";
// import "swiper/css/pagination";
// import { Swiper, SwiperSlide } from "swiper/react";
// import { Navigation, Pagination, Autoplay } from "swiper/modules";
// import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";
// import { IoMdHeartEmpty } from "react-icons/io";
// import { IoMdHeart } from "react-icons/io";
// import { saveProduct, saveProductId } from "@/store/product/actions";
// import { PiShareFatFill } from "react-icons/pi";
// import { PiShareFatLight } from "react-icons/pi";
// import Product from "../product/product";
// import SkeletonLoader from "../skeletons/skeleton";
// import { FaStar } from "react-icons/fa";
// import NoItem from "../no-items";

// type product = {
//   id: number;
//   image: string;
//   name: string;
//   sub_category_id: number;
//   brand_name: string;
//   requires_prescription: number;
//   price: string;
//   offer_id: null;
//   offer_title: string;
//   offer_price: string;
//   is_favourite: number;
//   is_cart: number;
// };
// export interface DataType {
//   products: product[];
//   title?: string;
// }
// // Star Rating Component
// const StarRating = ({ rating }: { rating: number }) => {
//   return (
//     <div className="flex">
//       {[...Array(5)].map((_, i) => (
//         <span key={i}>
//           {i < rating ? (
//             <FaStar className="text-yellow-400 w-5 h-5" />
//           ) : (
//             <FaStar className="text-gray-300 w-5 h-5" />
//           )}
//         </span>
//       ))}
//     </div>
//   );
// };
// export default function ProductList({ title, products }: DataType) {
//   const locale = useLocale();
//   const [productsLoading, setProductsLoading] = useState(false);
//   const [loginModalOpen, setLoginModalOpen] = useState(false);
//   const [hoveredItemId, setHoveredItemId] = useState<any>(undefined);
//   const [productHover, setProductHover] = useState(false);
//   const [productFavHover, setProductFavHover] = useState(false);
//   const [productShareHover, setProductShareHover] = useState(false);
//   const [favouritesProducts, setFavouritesProducts] = useState<any>([]);
//   const [favouriteLoading, setFavouriteLoading] = useState(false);
//   const [cartProducts, setCartProducts] = useState<any>([]);
//   const [productId, setProductId] = useState<undefined | number>(undefined);
//   const [imageErrors, setImageErrors] = useState<Record<number, boolean>>({});
//   const [imageLoaded, setImageLoaded] = useState<Record<number, boolean>>({});
//   const { cartLength } = useSelector((state: { Cart: any }) => state.Cart);
//   const { idToken } = useSelector((state: { Auth: any }) => state.Auth);
//   const router = useRouter();
//   const t = useTranslations();
//   const dispatch = useDispatch();
//   const pathname = usePathname();
//   const [imageSrc, setImageSrc] = useState(
//     ""
//     // item.image || "/images/fallback.png"
//   );
//   /// add product to cart
//   const mutation = useMutation({
//     mutationFn: (values: any) =>
//       axios["post"]("/add-to-cart", values, {
//         // headers: {
//         //   "Accept-Language": `${locale === "en" ? "en-US" : "ar-SA"}`,
//         // },
//       }),
//     onSuccess: (res) => {
//       // console.log(res.data);
//       setCartProducts([...cartProducts, productId]);
//       dispatch(fetchCartLength(Number(cartLength) + 1));
//       message.success(res.data.message);
//     },
//     onError: (err) => {
//       const {
//         status,
//         data: { message },
//       } = (err as any).response;

//       message.error(message, {
//         position: "top-center",
//         duration: 5000,
//       });
//     },
//   });
//   const addToCartFunc = (item: product) => {
//     if (!idToken) {
//       setLoginModalOpen(true);
//       return;
//     }
//     setProductId(item?.id);
//     // console.log("product", item);
//     mutation.mutate({
//       product_id: item.id,
//       offer_id: item?.offer_id,
//       quantity: 1,
//     });
//   };

//   useEffect(() => {
//     const arr = [];
//     //  console.log("products", products);
//     for (let i = 0; i <= products.length; i++) {
//       if (products[i]?.is_cart) {
//         arr.push(products[i].id);
//       }
//       setCartProducts([...arr]);
//     }
//     if (idToken) {
//       fetchFavorites();
//     }
//   }, [products]);

//   /// toggle favourite
//   const toggleFavorite = async (item: any) => {
//     if (!idToken) {
//       setLoginModalOpen(true);
//       return;
//     }
//     try {
//       setFavouriteLoading(true);
//       const response = await axios.post("/favorites", {
//         product_id: item?.id,
//       });

//       message.success(response?.data?.message);

//       fetchFavorites();
//     } catch (error: any) {
//       message.error(error?.message);
//     } finally {
//       setFavouriteLoading(false);
//     }
//   };
//   const fetchFavorites = async () => {
//     try {
//       const response = await axios.get("/favorites");
//       if (response?.data?.status) {
//         const favList = await response?.data?.data;
//         setFavouritesProducts([...favList]);
//         dispatch(fetchFavouritesLength(favList?.length));

//         //  console.log((favouritesProducts?.filter((ele:any)=>ele.product_id===9035).length>0))    // const isFav = favList.some(
//         //   (fav: any) => fav?.product_id === productData?.id
//         // );

//         // setProductData((prevData) =>
//         //   prevData ? { ...prevData, is_favourite: isFav ? 1 : 0 } : prevData
//         // );
//         //}
//       }
//     } catch (error) {
//       // console.error("Failed to fetch favorites:", error);
//     }
//   };

//   return (
//     // <section className="product-list py-2">
//     <>
//       <div className="container mx-auto relative px-4">
//         <h3 className="text-[#184363] text-lg xs:text-2xl lg:text-2xl font-bold">
//           {/* Picked for you */}
//           {title}
//         </h3>
//         <div className="absolute top-0 left-0  w-full h-full  flex items-center">
//           <div className="swiper-buttons w-full  flex  justify-between gap-2 rtl:flex-row-reverse">
//             <button className="products-swiper-button-prev-custom z-20  w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white h-[120px] rounded-r-sm transition-all duration-300 ease-in-out shadow-custom-slider  flex justify-center items-center">
//               <IoIosArrowBack className=" text-[30px]" />
//             </button>

//             <button className="products-swiper-button-next-custom z-20 w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white transition-all duration-300 ease-in-out h-[120px] rounded-l-sm  shadow-custom-slider  flex justify-center items-center">
//               <IoIosArrowForward className=" text-[30px]" />
//             </button>
//           </div>
//         </div>

//         {/* <div className="w-full md:w-[97%] mx-auto "> */}

//         <Swiper
//           slidesPerView={6}
//           spaceBetween={25}
//           // initialSlide={5}
//           breakpoints={{
//             0: {
//               slidesPerView: 1,
//             },
//             400: {
//               slidesPerView: 1,
//             },
//             500: {
//               slidesPerView: 2,
//             },
//             650: {
//               slidesPerView: 3,
//             },
//             850: {
//               slidesPerView: 3,
//             },
//             1100: {
//               slidesPerView: 5,
//               //spaceBetween: 20,
//             },
//             1500: {
//               slidesPerView: 6,
//             },
//             1700: {
//               slidesPerView: 7,
//             },
//           }}
//           loop={true}
//           navigation={{
//             nextEl: ".products-swiper-button-next-custom",
//             prevEl: ".products-swiper-button-prev-custom",
//           }}
//           pagination={{
//             clickable: true,
//             type: "bullets",
//             dynamicBullets: true,
//           }}
//           //   centeredSlides={true}
//           autoplay={{
//             delay: 2000,
//             disableOnInteraction: false,
//           }}
//           modules={[Navigation, Pagination, Autoplay]}
//           className="swiper w-full "
//         >
//           {products.length === 0 ? (
//             <SkeletonLoader />
//           ) : products.length == 0 ? (
//             <NoItem />
//           ) : (
//             products?.map((item: any) => (
//               <SwiperSlide className="mb-8 " key={item.id}>
//                 <div
//                   key={item.id}
//                   className={` max-[500px]:!mx-auto  my-8 product-item  ${
//                     hoveredItemId === item.id ? "hovered" : undefined
//                   }`}
//                   onClick={() => {
//                     // router.push(
//                     //   `/${locale}/products/${(item?.name).replace(/\s+/g, "-").toLowerCase()}`
//                     // );
//                     dispatch(saveProductId(item.id));
//                     dispatch(saveProduct(item));
//                   }}
//                 >
//                   <div
//                     className="relative  aspect-[1/1] flex justify-center items-center rounded-[10px] p-4 shadow-sm cursor-pointer"
//                     onMouseOver={(e) => {
//                       setProductHover(true);

//                       setHoveredItemId(item.id);
//                     }}
//                     onMouseLeave={() => {
//                       setHoveredItemId("");
//                       setProductHover(false);
//                     }}
//                     // onClick={() =>
//                     //   router.push(
//                     //     `/${locale}/products/${(item?.name).replace(/\s+/g, "-").toLowerCase()}`
//                     //   )
//                     // }
//                   >
//                     <Link
//                       href={`/${locale}/products/${(item?.name)
//                         .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
//                         .replace(/^-+|-+$/g, "")
//                         .toLowerCase()}?id=${item.id}`}
//                       locale={false}
//                       className="absolute w-full h-full top-0 left-0 z-[99]"
//                     ></Link>
//                     {item?.offer_title && (
//                       <span className="absolute z-40 bg-red-500 text-white rounded-full text-xs top-[9px] left-[9px] py-1 px-3 text-wrap max-w-[90%]">
//                         {item?.offer_title}
//                       </span>
//                     )}

//                     <Image
//                       src={
//                         imageErrors[item?.image]
//                           ? "/images/no-data.png"
//                           : item?.image || "/images/no-data.png"
//                       }
//                       alt={item.name || "Product"}
//                       fill
//                       loading="lazy"
//                       sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
//                       className={`rounded-lg object-contain transition-opacity duration-200 ${
//                         imageLoaded[item?.image] ? "opacity-100" : "opacity-0"
//                       }`}
//                       onError={() =>
//                         setImageErrors((prev) => ({
//                           ...prev,
//                           [item?.image]: true,
//                         }))
//                       }
//                       onLoadingComplete={() =>
//                         setImageLoaded((prev) => ({
//                           ...prev,
//                           [item?.image]: true,
//                         }))
//                       }
//                     />
//                     {productHover && hoveredItemId === item.id && (
//                       <>
//                         <div className="absolute top-0 left-0 h-full w-full bg-[#F6F5FA] opacity-50 z-20"></div>

//                         <div className="absolute flex">
//                           <div
//                             className={`${
//                               !favouriteLoading
//                                 ? "pointer-events-auto opacity-100"
//                                 : "pointer-events-none opacity-35"
//                             } p-3 m-1 rounded-[50%] bg-[#EDF4F6] flex justify-center items-center z-[99]`}
//                             onMouseOver={() => setProductFavHover(true)}
//                             onMouseLeave={() => setProductFavHover(false)}
//                             onClick={() => toggleFavorite(item)}
//                           >
//                             {productFavHover ||
//                             favouritesProducts.filter(
//                               (ele: any) => ele.product_id === item.id
//                             ).length > 0 ? (
//                               <IoMdHeart className=" text-[30px] text-red-600" />
//                             ) : (
//                               <IoMdHeartEmpty className="text-[30px]" />
//                             )}
//                           </div>
//                         </div>
//                       </>
//                     )}
//                     {item?.requires_prescription === 1 && (
//                       <div
//                         className={`absolute bottom-2 ${
//                           locale === "ar"
//                             ? "right-0 rounded-l-[5px]"
//                             : "left-0 rounded-r-[5px]"
//                         } flex items-center justify-center  gap-1 px-2 py-1  w-fit h-fit bg-[#FBC43A] text-white `}
//                       >
//                         <Image
//                           src={"/images/prescription-icon.svg"}
//                           alt="prescription icon"
//                           width={18}
//                           height={18}
//                         />
//                         <p className="text-[12px]">{t("prescription")}</p>
//                       </div>
//                     )}
//                   </div>

//                   <Link
//                     href={`/${locale}/products/${(item?.name)
//                       .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
//                       .replace(/^-+|-+$/g, "")
//                       .toLowerCase()}`}
//                     locale={false}
//                     className="md:p-1 text-productNameColor overflow-hidden text-ellipsis whitespace-nowrap font-sans max-w-[200px] block mt-2"
//                   >
//                     {item?.name}
//                   </Link>

//                   <div className="flex justify-between items-center">
//                     <div className="flex items-center">
//                       <StarRating
//                         rating={item.rate_count ? item.rate_count : 0}
//                       />{" "}
//                       <span className="mx-1">{item?.rate_avg} </span> (
//                       {item?.rate_count})
//                     </div>
//                     {favouritesProducts?.filter(
//                       (ele: any) => ele.product_id === item.id
//                     ).length > 0 && (
//                       <IoMdHeart className="text-[24px] ms-1 text-red-600" />
//                     )}
//                   </div>

//                       <div className="flex py-2">
//                                 {item?.offer_price &&
//                                   item?.offer_price < item?.price && (
//                                     <div className="flex items-center">
//                                       <p className="text-secondary  ms-2">
//                                         {" "}
//                                         {item?.offer_price}{" "}
//                                       </p>
//                                       <span className="inline-block ">
//                                         <Image
//                                           src={"/images/ryial.svg"}
//                                           alt="currancy icon"
//                                           width={25}
//                                           height={25}
//                                         />
//                                       </span>
//                                     </div>
//                                   )}
//                                 <div className="flex items-center">
//                                   <p
//                                     className={`${
//                                       item?.offer_price &&
//                                       item?.offer_price < item?.price
//                                         ? "line-through text-gray-400"
//                                         : "text-secondary"
//                                     }   ms-2`}
//                                   >

//                                     {item?.price}{" "}
//                                   </p>
//                                   <span className="inline-block ">
//                                     <Image
//                                       src={"/images/ryial.svg"}
//                                       alt="currancy icon"
//                                       width={25}
//                                       height={25}
//                                     />
//                                   </span>
//                                   {/* {t("sar")} */}{" "}
//                                 </div>
//                               </div>

//                   <Button
//                     onClick={() => addToCartFunc(item)}
//                     loading={productId === item?.id && mutation.isPending}
//                     disabled={
//                       cartProducts?.filter((ele: any) => ele === item.id)
//                         .length > 0
//                     }
//                     className={`rounded-[72px] ${
//                       cartProducts?.filter((ele: any) => ele === item.id)
//                         .length > 0
//                         ? "!text-primary"
//                         : "!text-secondary"
//                     } mt-4 min-h-[40px] !border-none !outline-none bg-[#EDF4F6] p-4 w-full hover:!bg-[#EDF4F6]`}
//                   >
//                     <CgShoppingCart className="text-[20px]" />
//                     <p>
//                       {cartProducts?.filter((ele: any) => ele === item.id)
//                         .length > 0
//                         ? t("added-to-cart")
//                         : t("add-to-cart")}
//                     </p>
//                   </Button>
//                 </div>
//               </SwiperSlide>
//             ))
//           )}

//         </Swiper>

//       </div>

//       <Modal
//         className="confirm-pickup"
//         open={loginModalOpen}
//         onCancel={() => setLoginModalOpen(false)}
//         footer={null}
//       >
//         <div className="flex flex-col items-center py-8">
//           <Image
//             src={"/images/login-first.png"}
//             width={160}
//             height={160}
//             style={
//               {
//                 // objectFit:"contain"
//               }
//             }
//             alt="image"
//           />

//           <p className="font-semibold py-4 text-[16px] md:text-[20px] text-gray-700">
//             {t("build-your-profile")}
//           </p>
//           <Button
//             onClick={() => setLoginModalOpen(false)}
//             className="relative !text-primary !bg-white !border-primary !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto mt-[30px] mb-[10px] min-h-[50px] w-[70%]  !rounded-[12px]"
//           >
//             <Link
//               href={`/${locale}/login`}
//               locale={false}
//               className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
//             >
//               {t("log-in")}
//             </Link>
//           </Button>
//           <Button
//             onClick={() => setLoginModalOpen(false)}
//             className="relative !text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto my-[10px] min-h-[50px] w-[70%]  !rounded-[12px]"
//           >
//             <Link
//               href={`/${locale}/signup`}
//               locale={false}
//               className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
//             >
//               {t("sign-up")}
//             </Link>
//           </Button>
//         </div>
//       </Modal>
//     </>
//     // </section>
//   );
// }

//////// 2 solution ////////////

// "use client";
// import React, { useEffect, useState, useRef } from "react";
// import { Button, message, Modal } from "antd";
// import Image from "next/image";
// import { useTranslations, useLocale } from "next-intl";
// import { useRouter } from "next/navigation";
// import { useDispatch, useSelector } from "react-redux";
// import { fetchCartLength } from "@/store/cart/actions";
// import { fetchFavouritesLength } from "@/store/cart/actions";
// import axios from "@/utils/axios-config";
// import { useMutation } from "@tanstack/react-query";
// import { CgShoppingCart } from "react-icons/cg";
// import Link from "next/link";
// import { usePathname } from "next/navigation";
// import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";
// import { IoMdHeartEmpty, IoMdHeart } from "react-icons/io";
// import { saveProduct, saveProductId } from "@/store/product/actions";
// import { FaStar } from "react-icons/fa";

// // Import Swiper modules with proper handling
// const loadSwiper = async () => {
//   if (typeof window !== 'undefined') {
//     const { Swiper } = await import('swiper');
//     const { Navigation, Pagination, Autoplay } = await import('swiper/modules');
//     return { Swiper, Navigation, Pagination, Autoplay };
//   }
// };

// // Import Swiper styles
// import 'swiper/css';
// import 'swiper/css/navigation';
// import 'swiper/css/pagination';

// type product = {
//   id: number;
//   image: string;
//   name: string;
//   sub_category_id: number;
//   brand_name: string;
//   requires_prescription: number;
//   price: string;
//   offer_id: null;
//   offer_title: string;
//   offer_price: string;
//   is_favourite: number;
//   is_cart: number;
//   rate_count?: number;
//   rate_avg?: number;
// };

// export interface DataType {
//   products: product[];
//   title?: string;
// }

// // Star Rating Component
// const StarRating = ({ rating }: { rating: number }) => {
//   return (
//     <div className="flex">
//       {[...Array(5)].map((_, i) => (
//         <span key={i}>
//           {i < rating ? (
//             <FaStar className="text-yellow-400 w-5 h-5" />
//           ) : (
//             <FaStar className="text-gray-300 w-5 h-5" />
//           )}
//         </span>
//       ))}
//     </div>
//   );
// };

// // Swiper component with autoplay fix
// const SwiperComponent = ({
//   products,
//   favouritesProducts,
//   cartProducts,
//   productId,
//   mutation,
//   toggleFavorite,
//   favouriteLoading,
//   addToCartFunc,
//   t,
//   locale,
//   dispatch,
//   imageErrors,
//   imageLoaded,
//   setImageErrors,
//   setImageLoaded,
//   productHover,
//   setProductHover,
//   hoveredItemId,
//   setHoveredItemId,
//   productFavHover,
//   setProductFavHover
// }: any) => {
//   const Swiper = typeof window !== 'undefined' ? require('swiper').Swiper : null;
//   const Navigation = typeof window !== 'undefined' ? require('swiper/modules').Navigation : null;
//   const Pagination = typeof window !== 'undefined' ? require('swiper/modules').Pagination : null;
//   const Autoplay = typeof window !== 'undefined' ? require('swiper/modules').Autoplay : null;
//   const SwiperReact = typeof window !== 'undefined' ? require('swiper/react').Swiper : () => null;
//   const SwiperSlide = typeof window !== 'undefined' ? require('swiper/react').SwiperSlide : () => null;

//   const swiperRef = useRef<any>(null);

//   useEffect(() => {
//     // Force autoplay to start after a short delay
//     const timer = setTimeout(() => {
//       if (swiperRef.current && swiperRef.current.swiper) {
//         const swiper = swiperRef.current.swiper;
//         if (swiper.autoplay && !swiper.autoplay.running) {
//           swiper.autoplay.start();
//         }
//       }
//     }, 500);

//     return () => clearTimeout(timer);
//   }, []);

//   const handleSwiperInit = (swiper: any) => {
//     // Force autoplay to start immediately
//     setTimeout(() => {
//       if (swiper.autoplay && !swiper.autoplay.running) {
//         swiper.autoplay.start();
//       }
//     }, 100);
//   };

//   if (typeof window === 'undefined' || !SwiperReact) {
//     return <div className="flex justify-center items-center h-64">Loading products...</div>;
//   }

//   return (
//     <SwiperReact
//       ref={swiperRef}
//       slidesPerView={6}
//       spaceBetween={25}
//       breakpoints={{
//         0: { slidesPerView: 1 },
//         400: { slidesPerView: 1 },
//         500: { slidesPerView: 2 },
//         650: { slidesPerView: 3 },
//         850: { slidesPerView: 3 },
//         1100: { slidesPerView: 5 },
//         1500: { slidesPerView: 6 },
//         1700: { slidesPerView: 7 },
//       }}
//       loop={true}
//       navigation={{
//         nextEl: ".products-swiper-button-next-custom",
//         prevEl: ".products-swiper-button-prev-custom",
//       }}
//       pagination={{
//         clickable: true,
//         type: "bullets",
//         dynamicBullets: true,
//       }}
//       autoplay={{
//         delay: 2000,
//         disableOnInteraction: false,
//         waitForTransition: true,
//       }}
//       modules={[Navigation, Pagination, Autoplay]}
//       className="swiper w-full"
//       onInit={handleSwiperInit}
//       onAfterInit={(swiper: any) => {
//         // Additional insurance for autoplay start
//         setTimeout(() => {
//           if (swiper.autoplay && !swiper.autoplay.running) {
//             swiper.autoplay.start();
//           }
//         }, 300);
//       }}
//     >
//       {products.length === 0 ? (
//         <div className="flex justify-center items-center h-64 w-full">
//           <p>No products available</p>
//         </div>
//       ) : (
//         products.map((item: any) => (
//           <SwiperSlide className="mb-8" key={item.id}>
//             <div
//               className={`max-[500px]:!mx-auto my-8 product-item ${
//                 hoveredItemId === item.id ? "hovered" : undefined
//               }`}
//               onClick={() => {
//                 dispatch(saveProductId(item.id));
//                 dispatch(saveProduct(item));
//               }}
//             >
//               <div
//                 className="relative aspect-[1/1] flex justify-center items-center rounded-[10px] p-4 shadow-sm cursor-pointer"
//                 onMouseOver={(e) => {
//                   setProductHover(true);
//                   setHoveredItemId(item.id);
//                 }}
//                 onMouseLeave={() => {
//                   setHoveredItemId("");
//                   setProductHover(false);
//                 }}
//               >
//                 <Link
//                   href={`/${locale}/products/${(item?.name)
//                     .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
//                     .replace(/^-+|-+$/g, "")
//                     .toLowerCase()}?id=${item.id}`}
//                   locale={false}
//                   className="absolute w-full h-full top-0 left-0 z-[99]"
//                 ></Link>
//                 {item?.offer_title && (
//                   <span className="absolute z-40 bg-red-500 text-white rounded-full text-xs top-[9px] left-[9px] py-1 px-3 text-wrap max-w-[90%]">
//                     {item?.offer_title}
//                   </span>
//                 )}

//                 <Image
//                   src={
//                     imageErrors[item?.image]
//                       ? "/images/no-data.png"
//                       : item?.image || "/images/no-data.png"
//                   }
//                   alt={item.name || "Product"}
//                   fill
//                   loading="lazy"
//                   sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
//                   className={`rounded-lg object-contain transition-opacity duration-200 ${
//                     imageLoaded[item?.image] ? "opacity-100" : "opacity-0"
//                   }`}
//                   onError={() =>
//                     setImageErrors((prev: any) => ({
//                       ...prev,
//                       [item?.image]: true,
//                     }))
//                   }
//                   onLoadingComplete={() =>
//                     setImageLoaded((prev: any) => ({
//                       ...prev,
//                       [item?.image]: true,
//                     }))
//                   }
//                 />
//                 {productHover && hoveredItemId === item.id && (
//                   <>
//                     <div className="absolute top-0 left-0 h-full w-full bg-[#F6F5FA] opacity-50 z-20"></div>

//                     <div className="absolute flex">
//                       <div
//                         className={`${
//                           !favouriteLoading
//                             ? "pointer-events-auto opacity-100"
//                             : "pointer-events-none opacity-35"
//                         } p-3 m-1 rounded-[50%] bg-[#EDF4F6] flex justify-center items-center z-[99]`}
//                         onMouseOver={() => setProductFavHover(true)}
//                         onMouseLeave={() => setProductFavHover(false)}
//                         onClick={() => toggleFavorite(item)}
//                       >
//                         {productFavHover ||
//                         favouritesProducts.filter(
//                           (ele: any) => ele.product_id === item.id
//                         ).length > 0 ? (
//                           <IoMdHeart className="text-[30px] text-red-600" />
//                         ) : (
//                           <IoMdHeartEmpty className="text-[30px]" />
//                         )}
//                       </div>
//                     </div>
//                   </>
//                 )}
//                 {item?.requires_prescription === 1 && (
//                   <div
//                     className={`absolute bottom-2 ${
//                       locale === "ar"
//                         ? "right-0 rounded-l-[5px]"
//                         : "left-0 rounded-r-[5px]"
//                     } flex items-center justify-center gap-1 px-2 py-1 w-fit h-fit bg-[#FBC43A] text-white`}
//                   >
//                     <Image
//                       src={"/images/prescription-icon.svg"}
//                       alt="prescription icon"
//                       width={18}
//                       height={18}
//                     />
//                     <p className="text-[12px]">{t("prescription")}</p>
//                   </div>
//                 )}
//               </div>

//               <Link
//                 href={`/${locale}/products/${(item?.name)
//                   .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
//                   .replace(/^-+|-+$/g, "")
//                   .toLowerCase()}`}
//                 locale={false}
//                 className="md:p-1 text-productNameColor overflow-hidden text-ellipsis whitespace-nowrap font-sans max-w-[200px] block mt-2"
//               >
//                 {item?.name}
//               </Link>

//               <div className="flex justify-between items-center">
//                 <div className="flex items-center">
//                   <StarRating
//                     rating={item.rate_count ? item.rate_count : 0}
//                   />{" "}
//                   <span className="mx-1">{item?.rate_avg} </span> (
//                   {item?.rate_count})
//                 </div>
//                 {favouritesProducts?.filter(
//                   (ele: any) => ele.product_id === item.id
//                 ).length > 0 && (
//                   <IoMdHeart className="text-[24px] ms-1 text-red-600" />
//                 )}
//               </div>

//               <div className="flex py-2">
//                 {item?.offer_price && item?.offer_price < item?.price && (
//                   <div className="flex items-center">
//                     <p className="text-secondary ms-2">
//                       {item?.offer_price}{" "}
//                     </p>
//                     <span className="inline-block">
//                       <Image
//                         src={"/images/ryial.svg"}
//                         alt="currancy icon"
//                         width={25}
//                         height={25}
//                       />
//                     </span>
//                   </div>
//                 )}
//                 <div className="flex items-center">
//                   <p
//                     className={`${
//                       item?.offer_price && item?.offer_price < item?.price
//                         ? "line-through text-gray-400"
//                         : "text-secondary"
//                     } ms-2`}
//                   >
//                     {item?.price}{" "}
//                   </p>
//                   <span className="inline-block">
//                     <Image
//                       src={"/images/ryial.svg"}
//                       alt="currancy icon"
//                       width={25}
//                       height={25}
//                     />
//                   </span>
//                 </div>
//               </div>

//               <Button
//                 onClick={() => addToCartFunc(item)}
//                 loading={productId === item?.id && mutation.isPending}
//                 disabled={
//                   cartProducts?.filter((ele: any) => ele === item.id)
//                     .length > 0
//                 }
//                 className={`rounded-[72px] ${
//                   cartProducts?.filter((ele: any) => ele === item.id)
//                     .length > 0
//                     ? "!text-primary"
//                     : "!text-secondary"
//                 } mt-4 min-h-[40px] !border-none !outline-none bg-[#EDF4F6] p-4 w-full hover:!bg-[#EDF4F6]`}
//               >
//                 <CgShoppingCart className="text-[20px]" />
//                 <p>
//                   {cartProducts?.filter((ele: any) => ele === item.id)
//                     .length > 0
//                     ? t("added-to-cart")
//                     : t("add-to-cart")}
//                 </p>
//               </Button>
//             </div>
//           </SwiperSlide>
//         ))
//       )}
//     </SwiperReact>
//   );
// };

// export default function ProductList({ title, products }: DataType) {
//   const locale = useLocale();
//   const [loginModalOpen, setLoginModalOpen] = useState(false);
//   const [hoveredItemId, setHoveredItemId] = useState<any>(undefined);
//   const [productHover, setProductHover] = useState(false);
//   const [productFavHover, setProductFavHover] = useState(false);
//   const [favouritesProducts, setFavouritesProducts] = useState<any>([]);
//   const [favouriteLoading, setFavouriteLoading] = useState(false);
//   const [cartProducts, setCartProducts] = useState<any>([]);
//   const [productId, setProductId] = useState<undefined | number>(undefined);
//   const [imageErrors, setImageErrors] = useState<Record<number, boolean>>({});
//   const [imageLoaded, setImageLoaded] = useState<Record<number, boolean>>({});
//   const [swiperReady, setSwiperReady] = useState(false);

//   const { cartLength } = useSelector((state: { Cart: any }) => state.Cart);
//   const { idToken } = useSelector((state: { Auth: any }) => state.Auth);
//   const router = useRouter();
//   const t = useTranslations();
//   const dispatch = useDispatch();
//   const pathname = usePathname();

//   // Load Swiper after component mounts
//   useEffect(() => {
//     const initializeSwiper = async () => {
//       try {
//         await loadSwiper();
//         setSwiperReady(true);
//       } catch (error) {
//         console.error('Failed to load Swiper:', error);
//       }
//     };

//     initializeSwiper();
//   }, []);

//   // Add product to cart
//   const mutation = useMutation({
//     mutationFn: (values: any) =>
//       axios["post"]("/add-to-cart", values),
//     onSuccess: (res) => {
//       setCartProducts([...cartProducts, productId]);
//       dispatch(fetchCartLength(Number(cartLength) + 1));
//       message.success(res.data.message);
//     },
//     onError: (err) => {
//       const { message: errorMsg } = (err as any).response.data;
//       message.error(errorMsg
//       //   , {
//       // //  position: "top-center",
//       //   duration: 5000,
//       // }
//     );
//     },
//   });

//   const addToCartFunc = (item: product) => {
//     if (!idToken) {
//       setLoginModalOpen(true);
//       return;
//     }
//     setProductId(item?.id);
//     mutation.mutate({
//       product_id: item.id,
//       offer_id: item?.offer_id,
//       quantity: 1,
//     });
//   };

//   useEffect(() => {
//     const arr = [];
//     for (let i = 0; i <= products.length; i++) {
//       if (products[i]?.is_cart) {
//         arr.push(products[i].id);
//       }
//       setCartProducts([...arr]);
//     }
//     if (idToken) {
//       fetchFavorites();
//     }
//   }, [products]);

//   // Toggle favourite
//   const toggleFavorite = async (item: any) => {
//     if (!idToken) {
//       setLoginModalOpen(true);
//       return;
//     }
//     try {
//       setFavouriteLoading(true);
//       const response = await axios.post("/favorites", {
//         product_id: item?.id,
//       });

//       message.success(response?.data?.message);
//       fetchFavorites();
//     } catch (error: any) {
//       message.error(error?.message);
//     } finally {
//       setFavouriteLoading(false);
//     }
//   };

//   const fetchFavorites = async () => {
//     try {
//       const response = await axios.get("/favorites");
//       if (response?.data?.status) {
//         const favList = await response?.data?.data;
//         setFavouritesProducts([...favList]);
//         dispatch(fetchFavouritesLength(favList?.length));
//       }
//     } catch (error) {
//       console.error("Failed to fetch favorites:", error);
//     }
//   };

//   if (!swiperReady) {
//     return (
//       <div className="container mx-auto relative px-4">
//         <h3 className="text-[#184363] text-lg xs:text-2xl lg:text-2xl font-bold">
//           {title}
//         </h3>
//         <div className="flex justify-center items-center h-64">
//           <p>Loading products...</p>
//         </div>
//       </div>
//     );
//   }

//   return (
//     <>
//       <div className="container mx-auto relative px-4">
//         <h3 className="text-[#184363] text-lg xs:text-2xl lg:text-2xl font-bold">
//           {title}
//         </h3>

//         {/* Navigation buttons */}
//         <div className="absolute top-1/2 left-4 -translate-y-1/2 z-20">
//           <button className="products-swiper-button-prev-custom z-20 w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white h-[120px] rounded-r-sm transition-all duration-300 ease-in-out shadow-custom-slider flex justify-center items-center">
//             <IoIosArrowBack className="text-[30px]" />
//           </button>
//         </div>

//         <div className="absolute top-1/2 right-4 -translate-y-1/2 z-20">
//           <button className="products-swiper-button-next-custom z-20 w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white transition-all duration-300 ease-in-out h-[120px] rounded-l-sm shadow-custom-slider flex justify-center items-center">
//             <IoIosArrowForward className="text-[30px]" />
//           </button>
//         </div>

//         {/* Use the Swiper component */}
//         <SwiperComponent
//           products={products}
//           favouritesProducts={favouritesProducts}
//           cartProducts={cartProducts}
//           productId={productId}
//           mutation={mutation}
//           toggleFavorite={toggleFavorite}
//           favouriteLoading={favouriteLoading}
//           addToCartFunc={addToCartFunc}
//           t={t}
//           locale={locale}
//           dispatch={dispatch}
//           imageErrors={imageErrors}
//           imageLoaded={imageLoaded}
//           setImageErrors={setImageErrors}
//           setImageLoaded={setImageLoaded}
//           productHover={productHover}
//           setProductHover={setProductHover}
//           hoveredItemId={hoveredItemId}
//           setHoveredItemId={setHoveredItemId}
//           productFavHover={productFavHover}
//           setProductFavHover={setProductFavHover}
//         />
//       </div>

//       <Modal
//         className="confirm-pickup"
//         open={loginModalOpen}
//         onCancel={() => setLoginModalOpen(false)}
//         footer={null}
//       >
//         <div className="flex flex-col items-center py-8">
//           <Image
//             src={"/images/login-first.png"}
//             width={160}
//             height={160}
//             alt="Login required"
//           />

//           <p className="font-semibold py-4 text-[16px] md:text-[20px] text-gray-700">
//             {t("build-your-profile")}
//           </p>
//           <Button
//             onClick={() => setLoginModalOpen(false)}
//             className="relative !text-primary !bg-white !border-primary !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto mt-[30px] mb-[10px] min-h-[50px] w-[70%] !rounded-[12px]"
//           >
//             <Link
//               href={`/${locale}/login`}
//               locale={false}
//               className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
//             >
//               {t("log-in")}
//             </Link>
//           </Button>
//           <Button
//             onClick={() => setLoginModalOpen(false)}
//             className="relative !text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto my-[10px] min-h-[50px] w-[70%] !rounded-[12px]"
//           >
//             <Link
//               href={`/${locale}/signup`}
//               locale={false}
//               className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
//             >
//               {t("sign-up")}
//             </Link>
//           </Button>
//         </div>
//       </Modal>
//     </>
//   );
// }

////3 solution ////

"use client";
import React, { useEffect, useState, useRef } from "react";
import { Button, message, Modal, Tooltip } from "antd";
import Image from "next/image";
import { useTranslations, useLocale } from "next-intl";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { fetchCartLength } from "@/store/cart/actions";
import { fetchFavouritesLength } from "@/store/cart/actions";
import axios from "@/utils/axios-config";
import { useMutation } from "@tanstack/react-query";
import { CgShoppingCart } from "react-icons/cg";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";
import { IoMdHeartEmpty, IoMdHeart } from "react-icons/io";
import { saveProduct, saveProductId } from "@/store/product/actions";
import { FaStar } from "react-icons/fa";

// Import Swiper components and styles
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Pagination, Autoplay } from "swiper/modules";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";

type product = {
  id: number;
  image: string;
  name: string;
  sub_category_id: number;
  brand_name: string;
  requires_prescription: number;
  price: string;
  offer_id: null;
  offer_title: string;
  offer_price: string;
  is_favourite: number;
  is_cart: number;
  rate_count?: number;
  rate_avg?: number;
};

export interface DataType {
  products: product[];
  title?: string;
}

// Star Rating Component
const StarRating = ({ rating }: { rating: number }) => {
  return (
    <div className="flex">
      {[...Array(5)].map((_, i) => (
        <span key={i}>
          {i < rating ? (
            <FaStar className="text-yellow-400 w-5 h-5" />
          ) : (
            <FaStar className="text-gray-300 w-5 h-5" />
          )}
        </span>
      ))}
    </div>
  );
};

export default function ProductList({ title, products }: DataType) {
  const locale = useLocale();
  const [loginModalOpen, setLoginModalOpen] = useState(false);
  const [hoveredItemId, setHoveredItemId] = useState<any>(undefined);
  const [productHover, setProductHover] = useState(false);
  const [productFavHover, setProductFavHover] = useState(false);
  const [favouritesProducts, setFavouritesProducts] = useState<any>([]);
  const [favouriteLoading, setFavouriteLoading] = useState(false);
  const [cartProducts, setCartProducts] = useState<any>([]);
  const [productId, setProductId] = useState<undefined | number>(undefined);
  const [imageErrors, setImageErrors] = useState<Record<number, boolean>>({});
  const [imageLoaded, setImageLoaded] = useState<Record<number, boolean>>({});

  const { cartLength } = useSelector((state: { Cart: any }) => state.Cart);
  const { idToken } = useSelector((state: { Auth: any }) => state.Auth);
  const router = useRouter();
  const t = useTranslations();
  const dispatch = useDispatch();
  const pathname = usePathname();

  // Swiper reference - CRITICAL FIX
  const swiperRef = useRef<any>(null);

  // Add product to cart
  const mutation = useMutation({
    mutationFn: (values: any) => axios["post"]("/add-to-cart", values),
    onSuccess: (res) => {
      setCartProducts([...cartProducts, productId]);
      dispatch(fetchCartLength(Number(cartLength) + 1));
      message.success(res.data.message);
    },
    onError: (err) => {
      const { message: errorMsg } = (err as any).response?.data || {};
      if (errorMsg) {
        message.error(errorMsg);
      }
    },
  });

  const addToCartFunc = (item: product) => {
    if (!idToken) {
      setLoginModalOpen(true);
      return;
    }
    setProductId(item?.id);
    mutation.mutate({
      product_id: item.id,
      offer_id: item?.offer_id,
      quantity: 1,
    });
  };

  useEffect(() => {
    const arr = [];
    for (let i = 0; i < products.length; i++) {
      if (products[i]?.is_cart) {
        arr.push(products[i].id);
      }
    }
    setCartProducts([...arr]);

    if (idToken) {
      fetchFavorites();
    }
  }, [products]);

  // Toggle favourite
  const toggleFavorite = async (item: any) => {
    if (!idToken) {
      setLoginModalOpen(true);
      return;
    }
    try {
      setFavouriteLoading(true);
      const response = await axios.post("/favorites", {
        product_id: item?.id,
      });

      message.success(response?.data?.message);
      fetchFavorites();
    } catch (error: any) {
      message.error(error?.message);
    } finally {
      setFavouriteLoading(false);
    }
  };

  const fetchFavorites = async () => {
    try {
      const response = await axios.get("/favorites");
      if (response?.data?.status) {
        const favList = await response?.data?.data;
        setFavouritesProducts([...favList]);
        dispatch(fetchFavouritesLength(favList?.length));
      }
    } catch (error) {
      console.error("Failed to fetch favorites:", error);
    }
  };

  const offerDiscreption = (
    buyQuantity: number,
    freeQuantity: number,
    discountType: number,
    discountValue: number
  ) => {
    return (
      <>
        {freeQuantity === 0 ? (
          <div
            className={`${
              locale === "en" ? "flex-row-reverse" : "flex-row"
            } flex items-center`}
          >
            <span className={`${locale === "en" ? "ms-2" : "me-2"}`}>
              {t("off")}{" "}
            </span>

            {discountValue}
            {discountType === 1 ? (
              <Image
                src={"/images/ryial.svg"}
                alt="currancy icon"
                width={12}
                height={12}
                className="ms-1"
              />
            ) : (
              "%"
            )}
          </div>
        ) : discountValue === 100 && discountType === 2 ? (
          ` ${buyQuantity} + ${freeQuantity} ${t("for-free")}`
        ) : (
          <>
            {/* {t("buy")} {buyQuantity} + {freeQuantity} {t("and-get")} */}
            <>
              {" "}
              <span className="ps-[2px]">{discountValue}</span>
              {discountType === 1 ? (
                <Image
                  src={"/images/currancy-white.svg"}
                  alt="currency icon"
                  width={15}
                  height={15}
                  className="inline"
                />
              ) : (
                "%"
              )}{" "}
              {Number(buyQuantity) === 1
                ? t("off-on-second-item")
                : t("off-on-third-item")}
            </>
          </>
        )}
      </>
    );
  };

  const offerCalcLabel = (
    price: number,
    buyQuantity: number,
    freeQuantity: number,
    discountType: number,
    discountValue: number
  ) => {
    return (
      <div className="flex items-center">
      <span className="me-1  text-[12px]">{t("offer-price")}</span>
        {freeQuantity === 0 ? (
          <></>
        ) : discountValue === 100 && discountType === 2 ? (
          // ` ${buyQuantity} + ${freeQuantity} ${t("for-free")}`
          <div className="flex items-center gap-1">
            <p className="text-white">{(Number(buyQuantity) * Number(price)).toFixed(2)}</p>
            <p className="text-white opacity-70 line-through">
              {((Number(buyQuantity) + Number(freeQuantity)) * Number(price)).toFixed(2)}
            </p>
          </div>
        ) : (
          <>
            {/* {t("buy")} {buyQuantity} + {freeQuantity} {t("and-get")} */}
            <>
              {/* {" "}
              <span className="ps-[2px]">{discountValue}</span>
              {discountType === 1 ? (
                <Image
                  src={"/images/currancy-white.svg"}
                  alt="currency icon"
                  width={15}
                  height={15}
                  className="inline"
                />
              ) : (
                "%"
              )}{" "}
              {Number(buyQuantity) === 1
                ? t("off-on-second-item")
                : t("off-on-third-item")} */}
              <div className="flex items-center gap-1">
                <p className="text-white">
                  {(Number(discountType) === 1
                    ? Number(buyQuantity) * Number(price) +
                      Number(freeQuantity) *
                        (Number(price) - Number(discountValue))
                    : (Number(buyQuantity) * Number(price)) +
                      Number(freeQuantity) *
                        ((Number(price) / 100) * (100-Number(discountValue)))).toFixed(2)}
                </p>
                <p className="text-white opacity-70 line-through">
                  {((Number(freeQuantity) + Number(buyQuantity)) * Number(price)).toFixed(2)}
                </p>
              </div>
            </>
          </>
        )}
      </div>
    );
  };

  if (products.length === 0) {
    return (
      <div className="container mx-auto relative px-4">
        <h3 className="text-[#184363] text-lg xs:text-2xl lg:text-2xl font-bold">
          {title}
        </h3>
       
         
    <div className="flex justify-center items-center flex-wrap my-5">
      {[1, 2, 3, 4, 5].map((_, index) => (
        <div
          className="w-[200px] m-4 p-4 border rounded-lg space-y-3"
          key={index}
        >
          {/* Image */}
          <div className="w-full h-40 bg-gray-300 rounded-md animate-pulse"></div>

          {/* Title */}
          <div className="w-3/4 h-6 bg-gray-300 rounded-md animate-pulse"></div>

          {/* Description */}
          <div className="w-full h-4 bg-gray-300 rounded-md animate-pulse"></div>
          <div className="w-5/6 h-4 bg-gray-300 rounded-md animate-pulse"></div>
        </div>
      ))}
    </div>
 
        
      </div>
    );
  }

  return (
    <>
      <div className="container mx-auto relative px-4">
        <h3 className="text-[#184363] text-lg xs:text-2xl lg:text-2xl font-bold">
          {title}
        </h3>

        {/* Navigation buttons - Fixed positioning */}
        <div className="absolute top-1/2 left-4 -translate-y-1/2 z-20">
          <button className="products-swiper-button-prev-custom z-20 w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white h-[120px] rounded-r-sm transition-all duration-300 ease-in-out shadow-custom-slider flex justify-center items-center">
            <IoIosArrowBack className="text-[30px]" />
          </button>
        </div>

        <div className="absolute top-1/2 right-4 -translate-y-1/2 z-20">
          <button className="products-swiper-button-next-custom z-20 w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white transition-all duration-300 ease-in-out h-[120px] rounded-l-sm shadow-custom-slider flex justify-center items-center">
            <IoIosArrowForward className="text-[30px]" />
          </button>
        </div>

        {/* Swiper component with the same pattern as working Brands component */}
        <style>{`
          .product-list-swiper .swiper-wrapper {
            align-items: stretch !important;
          }
          .product-list-swiper .swiper-slide {
            height: auto !important;
          }
        `}</style>
        <div className="w-full">
          <Swiper
            slidesPerView={6}
            spaceBetween={25}
            breakpoints={{
              0: { slidesPerView: 1, spaceBetween: 10 },
              400: { slidesPerView: 1, spaceBetween: 12 },
              500: { slidesPerView: 2, spaceBetween: 15 },
              650: { slidesPerView: 3 },
              850: { slidesPerView: 3 },
              1100: { slidesPerView: 5 },
              1500: { slidesPerView: 6 },
              1700: { slidesPerView: 7 },
            }}
            loop={true}
            navigation={{
              nextEl: ".products-swiper-button-next-custom",
              prevEl: ".products-swiper-button-prev-custom",
            }}
            pagination={{
              clickable: true,
              type: "bullets",
              dynamicBullets: true,
            }}
            autoplay={{
              delay: 2000,
              disableOnInteraction: false,
            }}
           // autoplay={false} // Start with autoplay disabled
            modules={[Navigation, Pagination, Autoplay]}
            className="swiper w-full product-list-swiper"
            onSwiper={(swiper) => (swiperRef.current = swiper)} // CRITICAL: Set the ref
          >
            {products.map((item: any) => (
              <SwiperSlide
                className="mb-8"
                key={item.id}
                onMouseEnter={() => swiperRef.current?.autoplay?.stop()} // Pause on hover
                onMouseLeave={() => swiperRef.current?.autoplay?.start()} // Resume on leave
              >
                <div
                  className={`max-[500px]:!mx-auto max-[500px]:max-w-[220px] my-8 product-item h-full flex flex-col   ${
                    hoveredItemId === item.id ? "hovered" : undefined
                  }`}
                  onClick={() => {
                    dispatch(saveProductId(item.id));
                    dispatch(saveProduct(item));
                  }}
                >
                  <div>
                    <div
                      className="relative aspect-[1/1] flex justify-center items-center rounded-[10px] p-4 shadow-sm cursor-pointer"
                      onMouseOver={(e) => {
                        setProductHover(true);
                        setHoveredItemId(item.id);
                      }}
                      onMouseLeave={() => {
                        setHoveredItemId("");
                        setProductHover(false);
                      }}
                    >
                      <Link
                        href={`/${locale}/products/${(item?.name)
                          .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
                          .replace(/^-+|-+$/g, "")
                          .toLowerCase()}?id=${item.id}`}
                        locale={false}
                        className="absolute w-full h-full top-0 left-0 z-[99]"
                      ></Link>
                      {item?.offer_title && (
                        <p className="absolute z-[20] gap-2 w-fit bg-red-500 text-white py-1 rounded-ss-[5px] text-[11px] top-[0px] start-[0px]  px-1 text-wrap opacity-80 max-w-[160px]">
                         
                          {offerDiscreption(
                            item?.offer_buy_quantity,
                            item?.offer_free_quantity,
                            item?.offer_discount_type,
                            item?.offer_discount_value
                          )}
                        </p>
                      )}

                      <Image
                        src={
                          imageErrors[item?.image]
                            ? "/images/no-data.png"
                            : item?.image || "/images/no-data.png"
                        }
                        alt={item.name || "Product"}
                        fill
                        loading="lazy"
                        sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
                        className={`rounded-lg object-contain transition-opacity duration-200 ${
                          imageLoaded[item?.image] ? "opacity-100" : "opacity-0"
                        }`}
                        onError={() =>
                          setImageErrors((prev: any) => ({
                            ...prev,
                            [item?.image]: true,
                          }))
                        }
                        onLoadingComplete={() =>
                          setImageLoaded((prev: any) => ({
                            ...prev,
                            [item?.image]: true,
                          }))
                        }
                      />
                      {productHover && hoveredItemId === item.id && (
                        <>
                          <div className="absolute top-0 left-0 h-full w-full bg-[#F6F5FA] opacity-50 z-20"></div>

                          <div className="absolute flex">
                            <div
                              className={`${
                                !favouriteLoading
                                  ? "pointer-events-auto opacity-100"
                                  : "pointer-events-none opacity-35"
                              } p-3 m-1 rounded-[50%] bg-[#EDF4F6] flex justify-center items-center z-[99]`}
                              onMouseOver={() => setProductFavHover(true)}
                              onMouseLeave={() => setProductFavHover(false)}
                              onClick={(e) => {
                                e.stopPropagation();
                                toggleFavorite(item);
                              }}
                            >
                              {productFavHover ||
                              favouritesProducts.filter(
                                (ele: any) => ele.product_id === item.id
                              ).length > 0 ? (
                                <IoMdHeart className="text-[30px] text-red-600" />
                              ) : (
                                <IoMdHeartEmpty className="text-[30px]" />
                              )}
                            </div>
                          </div>
                        </>
                      )}
                      {item?.requires_prescription === 1 && (
                        <div
                          className={`absolute bottom-2 ${
                            locale === "ar"
                              ? "right-0 rounded-l-[5px]"
                              : "left-0 rounded-r-[5px]"
                          } flex items-center justify-center gap-1 px-2 py-1 w-fit h-fit bg-[#FBC43A] text-white`}
                        >
                          <Image
                            src={"/images/prescription-icon.svg"}
                            alt="prescription icon"
                            width={18}
                            height={18}
                          />
                          <p className="text-[12px]">{t("prescription")}</p>
                        </div>
                      )}
                    </div>

                    <Tooltip title={item?.name} color="rgba(3,184,158,0.6)" overlayInnerStyle={{ fontSize: 12, padding: "4px 8px" }}>
                      <Link
                        href={`/${locale}/products/${(item?.name)
                          .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
                          .replace(/^-+|-+$/g, "")
                          .toLowerCase()}?id=${item.id}`}
                        locale={false}
                        className="md:p-1 text-productNameColor  font-sans text-[15px] block "
                      >
                        {item?.name}
                      </Link>
                    </Tooltip>

                    <div className="flex justify-between items-center">
                      <div className="flex items-center">
                        <StarRating
                          rating={item.rate_count ? item.rate_count : 0}
                        />{" "}
                        <span className="mx-1">{item?.rate_avg} </span> (
                        {item?.rate_count})
                      </div>
                      {favouritesProducts?.filter(
                        (ele: any) => ele.product_id === item.id
                      ).length > 0 && (
                        <IoMdHeart className="text-[24px] ms-1 text-red-600" />
                      )}
                    </div>

                    <div className="flex">
                      {item?.offer_price && item?.offer_price < item?.price && (
                        <div className="flex items-center">
                          <p className="text-secondary ms-2">
                            {item?.offer_price}{" "}
                          </p>
                          <span className="inline-block">
                            <Image
                              src={"/images/ryial.svg"}
                              alt="currency icon"
                              width={12}
                              height={12}
                              className="ms-1"
                            />
                          </span>
                        </div>
                      )}
                      <div className="flex items-center">
                        <p
                          className={`${
                            item?.offer_price && item?.offer_price < item?.price
                              ? "line-through text-gray-400"
                              : "text-secondary"
                          } ms-2`}
                        >
                          {item?.price}{" "}
                        </p>
                        <span className="inline-block">
                          <Image
                            src={"/images/ryial.svg"}
                            alt="currency icon"
                            width={12}
                            height={12}
                            className="ms-1"
                          />
                        </span>
                      </div>
                    </div>
                    {Number(item?.offer_free_quantity) > 0 ? (
                      <div className="mt-auto w-fit bg-primary bg-opacity-50 px-2  rounded-[5px]">
                        {offerCalcLabel(
                          item?.price,
                          item?.offer_buy_quantity,
                          item?.offer_free_quantity,
                          item?.offer_discount_type,
                          item?.offer_discount_value
                        )}
                      </div>
                    ) : null}
                  </div>

                  <Button
                    onClick={() => addToCartFunc(item)}
                    loading={productId === item?.id && mutation.isPending}
                    disabled={
                      cartProducts?.filter((ele: any) => ele === item.id)
                        .length > 0
                    }
                    className={`rounded-[72px] ${
                      cartProducts?.filter((ele: any) => ele === item.id)
                        .length > 0
                        ? "!text-primary"
                        : "!text-secondary"
                    } mt-auto !mb-[25px] min-h-[35px] sm:min-h-[40px] !border-none !outline-none bg-[#EDF4F6] p-2 sm:p-4 w-full hover:!bg-[#EDF4F6] !text-[12px] sm:!text-[14px]`}
                  >
                    <CgShoppingCart className="text-[16px] sm:text-[20px] shrink-0" />
                    <p className="truncate">
                      {cartProducts?.filter((ele: any) => ele === item.id)
                        .length > 0
                        ? t("added-to-cart")
                        : t("add-to-cart")}
                    </p>
                  </Button>
                </div>
              </SwiperSlide>
            ))}
          </Swiper>
        </div>
      </div>

      <Modal
        className="confirm-pickup"
        open={loginModalOpen}
        onCancel={() => setLoginModalOpen(false)}
        footer={null}
      >
        <div className="flex flex-col items-center py-8">
          <Image
            src={"/images/login-first.png"}
            width={160}
            height={160}
            alt="Login required"
          />

          <p className="font-semibold py-4 text-[16px] md:text-[20px] text-gray-700">
            {t("build-your-profile")}
          </p>
          <Button
            onClick={() => setLoginModalOpen(false)}
            className="relative !text-primary !bg-white !border-primary !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto mt-[30px] mb-[10px] min-h-[50px] w-[70%] !rounded-[12px]"
          >
            <Link
              href={`/${locale}/login`}
              locale={false}
              className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
            >
              {t("log-in")}
            </Link>
          </Button>
          <Button
            onClick={() => setLoginModalOpen(false)}
            className="relative !text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto my-[10px] min-h-[50px] w-[70%] !rounded-[12px]"
          >
            <Link
              href={`/${locale}/signup`}
              locale={false}
              className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
            >
              {t("sign-up")}
            </Link>
          </Button>
        </div>
      </Modal>
    </>
  );
}
