"use client";

import React, { useEffect, useRef, useState, useCallback } from "react";
import "./ItemsSection.css";
import { FaChevronDown, FaChevronUp } from "react-icons/fa";
import Link from "next/link";
import { useParams } from "next/navigation";
import useApi from "@/hooks/useApi";
import { CiBoxList, CiGrid41 } from "react-icons/ci";
import HorizontalSlider from "../HorizontalSlider/HorizontalSlider";
import ProductCardGrid from "../ProductCardGrid/ProductCardGrid";
import ProductCardList from "../ProductCardList/ProductCardList";
import CustomLoader from "../CustomLoader/CustomLoader";
import { useAuth } from "@/Context/AuthContext";
import { useLocation } from "@/Context/LocationContext";
import { getImageUrl } from "@/utils/imageUrl";
import { cartImage } from "@/utils/mediaConstant";
import { useRouter } from "next/navigation";
import WebsiteLoader from "@/Components/WebsiteLoader/WebsiteLoader";


// ============ SKELETON COMPONENTS ============

const ProductGridSkeleton = () => (
  <div className="grid grid-cols-2 gap-2 sm:gap-3 md:gap-4 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-4 px-1 md:px-4 mb-4">
    {[...Array(8)].map((_, index) => (
      <div key={index} className="animate-pulse bg-white rounded-lg p-3">
        <div className="w-full h-36 sm:h-40 md:h-48 bg-gray-200 rounded mb-3"></div>
        <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
        <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
        <div className="h-6 bg-gray-200 rounded w-1/3"></div>
      </div>
    ))}
  </div>
);

const ProductListSkeleton = () => (
  <div className="flex flex-col space-y-2 md:space-y-4 px-1 md:px-0 mb-4">
    {[...Array(5)].map((_, index) => (
      <div
        key={index}
        className="flex flex-row border p-4 space-x-4 bg-white animate-pulse"
      >
        <div className="w-32 h-32 md:w-64 md:h-64 bg-gray-200 rounded"></div>
        <div className="flex-1 space-y-3 py-2">
          <div className="h-6 bg-gray-200 rounded w-3/4"></div>
          <div className="h-4 bg-gray-200 rounded w-1/2"></div>
          <div className="h-8 bg-gray-200 rounded w-1/3"></div>
        </div>
      </div>
    ))}
  </div>
);

const TitleSkeleton = () => (
  <div className="mb-3 md:mb-4 flex flex-col">
    <div className="h-8 md:h-10 bg-gray-200 rounded w-48 md:w-64 animate-pulse"></div>
  </div>
);

const FilterBarSkeleton = () => (
  <div className="flex flex-col md:flex-row md:justify-between md:items-center px-2 md:px-0 py-3 md:py-4">
    <div className="h-6 bg-gray-200 rounded w-24 animate-pulse mb-2 md:mb-0"></div>
    <div className="flex justify-between md:justify-end space-x-2 md:space-x-4">
      <div className="h-10 bg-gray-200 rounded w-20 animate-pulse"></div>
      <div className="h-10 bg-gray-200 rounded w-32 animate-pulse"></div>
    </div>
  </div>
);

const SliderSkeleton = () => (
  <div className="bg-white px-2 md:px-4 py-3 md:py-4 mt-3 md:mt-0">
    <div className="h-6 bg-gray-200 rounded w-40 mb-4 animate-pulse"></div>
    <div className="flex space-x-4 overflow-hidden">
      {[...Array(6)].map((_, index) => (
        <div
          key={index}
          className="flex-shrink-0 w-32 h-32 bg-gray-200 rounded animate-pulse"
        ></div>
      ))}
    </div>
  </div>
);

// ============ OVERLAY LOADER COMPONENT ============
const NavigationLoader = () => (
  <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
    <div className="bg-white rounded-lg p-6 flex flex-col items-center space-y-3 shadow-xl">
      <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-orange-500"></div>
      <p className="text-gray-700 font-osMedium">Loading...</p>
    </div>
  </div>
);

// ============ MAIN COMPONENT ============

const ItemsSection = ({ initialCategories = {}, pageDetails = {} }) => {
  const { get } = useApi();
  const {
    mainCategories: contextMainCats,
    subCategories: contextSubCats,
    superSubCategories: contextSuperCats,
  } = useAuth();

  const router = useRouter();
  const [isNavigating, setIsNavigating] = useState(false);
  const [clickedProductId, setClickedProductId] = useState(null);

  const [mainCategories, setMainCategories] = useState(
    initialCategories.mainCategories || [],
  );
  const [subCategories, setSubCategories] = useState(
    initialCategories.subCategories || [],
  );
  const [superSubCategories, setSuperSubCategories] = useState(
    initialCategories.superSubCategories || [],
  );

  const [changeView, setChangeView] = useState(true);
  const params = useParams();
  const [isOpen, setIsOpen] = useState(true);
  const [visibleCount, setVisibleCount] = useState(10);
  const [products, setProducts] = useState([]);
  const [sliderCategories, setSliderCategories] = useState([]);
  const [dataType, setDataType] = useState("");
  const [headingTitle, setHeadingTitle] = useState("");
  const [categoryDetails, setCategoryDetails] = useState({});
  const [expandedCategory, setExpandedCategory] = useState(null);
  const [expandedSubcategory, setExpandedSubcategory] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [hasMore, setHasMore] = useState(true);
  const [sortValue, setSortValue] = useState("");
  const [supersubCategoryDescription, setSupersubCategoryDescription] =
    useState("");
  const { location } = useLocation();
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const [searchRadius, setSearchRadius] = useState(null);
  const [maxRadiusReached, setMaxRadiusReached] = useState(false);
  const [searchInfo, setSearchInfo] = useState(null);

 const handleProductClick = useCallback((e, alias) => {
  e.preventDefault();
  e.stopPropagation();
  setIsNavigating(true);
  router.push(`/product/${alias}`);
}, [router]);

  // Reset navigation state when page changes
  useEffect(() => {
    setIsNavigating(false);
    setClickedProductId(null);
  }, [params?.items]);

  const sidebarMainCategories = mainCategories
    ?.sort((a, b) => a?.sequence - b?.sequence)
    ?.sort((a, b) => a?.mainCategoryName?.localeCompare(b?.mainCategoryName));

  const sidebarSubCategories = subCategories
    ?.sort((a, b) => a?.sequence - b?.sequence)
    ?.sort((a, b) => a?.subCategoryName?.localeCompare(b?.subCategoryName));

  const sidebarSuperSubCategories = superSubCategories
    ?.sort((a, b) => a?.sequence - b?.sequence)
    ?.sort((a, b) =>
      a?.superSubCategoryName?.localeCompare(b?.superSubCategoryName),
    );

  const handleShowMore = () => {
    setVisibleCount(sidebarMainCategories.length);
  };

  const handleShowLess = () => {
    setVisibleCount(10);
  };

  useEffect(() => {
    if (contextMainCats?.length > 0 && contextMainCats !== mainCategories) {
      setMainCategories(contextMainCats);
    }
    if (contextSubCats?.length > 0 && contextSubCats !== subCategories) {
      setSubCategories(contextSubCats);
    }
    if (
      contextSuperCats?.length > 0 &&
      contextSuperCats !== superSubCategories
    ) {
      setSuperSubCategories(contextSuperCats);
    }
  }, [contextMainCats, contextSubCats, contextSuperCats]);

  const handleCategoryClick = (category) => {
    setExpandedCategory(expandedCategory === category ? null : category);
    setExpandedSubcategory(null);
  };

  const handleSubcategoryClick = (subcategory) => {
    setExpandedSubcategory(
      expandedSubcategory === subcategory ? null : subcategory,
    );
  };

  useEffect(() => {
    setProducts([]);
    setCurrentPage(1);
    setHasMore(true);
    setSearchRadius(null);
    setMaxRadiusReached(false);
  }, [sortValue, location?.city, params?.items]);

  // Initial fetch
  useEffect(() => {
    const fetchInitialProducts = async () => {
      setIsLoading(true);
      try {
        const currentCityId =
          location?.cityId || localStorage.getItem("user_city_id") || "";
        const currentCity = location?.cleanCity || location?.city || "";
        const currentCountry =
          location?.country || localStorage.getItem("user_country") || "";
        const latitude = location?.latitude || "";
        const longitude = location?.longitude || "";

        const paramsObj = {
          alias: params?.items,
          sortValue: sortValue,
          page: 1,
          limit: limit,
        };

        if (currentCityId) {
          paramsObj.cityId = currentCityId;
        } else if (currentCity) {
          paramsObj.city = currentCity;
        }

        if (currentCountry) {
          paramsObj.country = currentCountry;
        }

        if (latitude && longitude) {
          paramsObj.latitude = latitude;
          paramsObj.longitude = longitude;
          paramsObj.initialRadius = 1;
          paramsObj.maxRadius = 50;
          paramsObj.radiusStep = 5;
        }

        const apiUrl = `product/getAllProductByAliasWithRadius?${new URLSearchParams(
          paramsObj,
        )}`;

        const { data } = await get(apiUrl);

        const fetchedProducts = data?.products || [];
        
        setProducts(fetchedProducts);
        setDataType(data?.dataType);
        setCurrentPage(1);
        setSliderCategories(data?.categories || []);
        setHeadingTitle(data?.title);
        setCategoryDetails(data?.categoryDetails || {});
        setSearchRadius(data?.searchRadius || null);
        setMaxRadiusReached(data?.maxRadiusReached || false);
        setSearchInfo(data?.searchInfo || null);
        
        const moreAvailable = data?.hasMore === true;
        setHasMore(moreAvailable);

        if (data?.dataType === "super" && data?.categoryDetails) {
          const description =
            data.categoryDetails.superSubCategoryDescription || "";
          setSupersubCategoryDescription(description);
        } else {
          setSupersubCategoryDescription("");
        }
      } catch (error) {
        console.log("Error fetching products:", error);
        setProducts([]);
        setHasMore(false);
      } finally {
        setIsLoading(false);
      }
    };

    fetchInitialProducts();
  }, [
    sortValue,
    location?.city,
    location?.latitude,
    location?.longitude,
    params?.items,
    get,
    limit,
  ]);

  // Show More function
  const handleShowMoreClick = useCallback(async () => {
    if (!hasMore || isFetchingMore) return;

    setIsFetchingMore(true);
    const nextPage = currentPage + 1;

    try {
      const currentCityId =
        location?.cityId || localStorage.getItem("user_city_id") || "";
      const currentCity = location?.cleanCity || location?.city || "";
      const currentCountry =
        location?.country || localStorage.getItem("user_country") || "";
      const latitude = location?.latitude || "";
      const longitude = location?.longitude || "";

      const paramsObj = {
        alias: params?.items,
        sortValue: sortValue,
        page: nextPage,
        limit: limit,
      };

      if (currentCityId) {
        paramsObj.cityId = currentCityId;
      } else if (currentCity) {
        paramsObj.city = currentCity;
      }

      if (currentCountry) {
        paramsObj.country = currentCountry;
      }

      if (latitude && longitude) {
        paramsObj.latitude = latitude;
        paramsObj.longitude = longitude;
        paramsObj.initialRadius = searchRadius || 1;
        paramsObj.maxRadius = 50;
        paramsObj.radiusStep = 5;
      }

      const apiUrl = `product/getAllProductByAliasWithRadius?${new URLSearchParams(
        paramsObj,
      )}`;

      const { data } = await get(apiUrl);
      const newProducts = data?.products || [];

      if (newProducts.length > 0) {
        const existingProductIds = new Set(products.map((p) => p._id));
        const uniqueNewProducts = newProducts.filter(
          (product) => !existingProductIds.has(product._id),
        );

        if (uniqueNewProducts.length > 0) {
          setProducts((prev) => [...prev, ...uniqueNewProducts]);
          setCurrentPage(nextPage);
          
          const moreAvailable = data?.hasMore === true;
          setHasMore(moreAvailable);
          
          setSearchRadius(data?.searchRadius || searchRadius);
          setMaxRadiusReached(data?.maxRadiusReached || false);
          setSearchInfo(data?.searchInfo || searchInfo);
        } else {
          setHasMore(false);
        }
      } else {
        setHasMore(false);
      }
    } catch (error) {
      console.log("Error fetching more products:", error);
      setHasMore(false);
    } finally {
      setIsFetchingMore(false);
    }
  }, [
    currentPage,
    hasMore,
    isFetchingMore,
    sortValue,
    location?.cityId,
    location?.cleanCity,
    location?.city,
    location?.latitude,
    location?.longitude,
    params?.items,
    limit,
    get,
    products,
    searchRadius,
    searchInfo,
  ]);

  const [isSortModalOpen, setIsSortModalOpen] = useState(false);
  const buttonRef = useRef(null);
  const dropdownRef = useRef(null);

  const toggleDropdown = () => {
    setIsSortModalOpen(!isSortModalOpen);
  };

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target)
      ) {
        setIsSortModalOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const renderCategoriesSidebar = (isMobile = false) => (
    <div
      className={`w-full bg-white ${isMobile ? "block md:hidden" : "hidden md:block"}`}
    >
      <div className="p-2 w-full">
        <button
          onClick={() => setIsOpen(!isOpen)}
          className="px-4 py-2 text-black transition-colors duration-300 flex items-center justify-between w-full"
        >
          <span className="m-0 text-sm font-osSemiBold">CATEGORIES</span>
          <div className="flex-shrink-0">
            {isOpen ? (
              <FaChevronUp className="text-[rgba(33,37,41,0.75)]" />
            ) : (
              <FaChevronDown className="text-[rgba(33,37,41,0.75)]" />
            )}
          </div>
        </button>

        <div
          className={`overflow-hidden transition-max-height duration-500 ease-in-out ${
            isOpen ? "max-h-screen" : "max-h-0"
          }`}
        >
          <div
            className={`w-full bg-white px-2 py-4 ${isMobile ? "" : "sidebar-scrollbar"}`}
          >
            <ul>
              {(sidebarMainCategories || [])
                .slice(0, visibleCount)
                .map((category) => {
                  if (category?.published !== false) {
                    return (
                      <li key={category?.mainCategoryId} className="">
                        <div className="flex items-center justify-between cursor-pointer">
                          <Link
                            className="category-link"
                            href={`/${category?.alias}`}
                          >
                            <p
                              className={`${
                                expandedCategory === category?.mainCategoryId ||
                                category?.mainCategoryId ===
                                  categoryDetails?.mainCategoryId ||
                                category?.alias === params?.items
                                  ? "font-osBold"
                                  : "font-osRegular"
                              } text-sm text-start`}
                            >
                              {category?.mainCategoryName}
                            </p>
                          </Link>
                          {expandedCategory === category?.mainCategoryId ? (
                            <button
                              className="ml-2 p-1 text-[rgba(33,37,41,0.75)] rounded"
                              onClick={() =>
                                handleCategoryClick(category?.mainCategoryId)
                              }
                            >
                              -
                            </button>
                          ) : (
                            <button
                              className="ml-2 p-1 text-[rgba(33,37,41,0.75)] rounded"
                              onClick={() =>
                                handleCategoryClick(category?.mainCategoryId)
                              }
                            >
                              +
                            </button>
                          )}
                        </div>
                        {expandedCategory === category?.mainCategoryId && (
                          <ul className="ml-4 mt-2">
                            {sidebarSubCategories
                              .filter(
                                (i) =>
                                  i?.mainCategoryId ===
                                    category?.mainCategoryId &&
                                  i?.published !== false,
                              )
                              .map((subcategory) => (
                                <li
                                  key={subcategory?.subCategoryId}
                                  className=""
                                >
                                  <div className="flex items-center justify-between cursor-pointer my-2">
                                    <Link
                                      href={`/${subcategory?.alias}`}
                                      className="category-link text-left"
                                    >
                                      <p
                                        className={`text-sm ${
                                          expandedSubcategory ===
                                            subcategory?.subCategoryId ||
                                          subcategory?.subCategoryId ===
                                            categoryDetails?.subCategoryId
                                            ? "font-osBold"
                                            : "font-osRegular"
                                        }`}
                                      >
                                        {subcategory?.subCategoryName}
                                      </p>
                                    </Link>
                                    {expandedSubcategory ===
                                    subcategory?.subCategoryId ? (
                                      <button
                                        className="ml-2 p-1 text-[rgba(33,37,41,0.75)] rounded"
                                        onClick={() =>
                                          handleSubcategoryClick(
                                            subcategory?.subCategoryId,
                                          )
                                        }
                                      >
                                        -
                                      </button>
                                    ) : (
                                      <button
                                        className="ml-2 p-1 text-[rgba(33,37,41,0.75)] rounded"
                                        onClick={() =>
                                          handleSubcategoryClick(
                                            subcategory?.subCategoryId,
                                          )
                                        }
                                      >
                                        +
                                      </button>
                                    )}
                                  </div>
                                  {expandedSubcategory ===
                                    subcategory?.subCategoryId && (
                                    <ul className="ml-4 mt-2">
                                      {sidebarSuperSubCategories
                                        .filter(
                                          (i) =>
                                            i?.subCategoryId ===
                                              subcategory?.subCategoryId &&
                                            i?.published !== false,
                                        )
                                        .map((superSubCategory) => (
                                          <li
                                            key={
                                              superSubCategory?.superSubCategoryId
                                            }
                                            className="mb-2"
                                          >
                                            <Link
                                              className="category-link text-left w-full"
                                              href={`/${superSubCategory?.alias}`}
                                            >
                                              <p className="cursor-pointer text-sm font-osRegular">
                                                {
                                                  superSubCategory?.superSubCategoryName
                                                }
                                              </p>
                                            </Link>
                                          </li>
                                        ))}
                                    </ul>
                                  )}
                                </li>
                              ))}
                          </ul>
                        )}
                      </li>
                    );
                  }
                })}
            </ul>
          </div>

          {visibleCount < sidebarMainCategories.length ? (
            <button
              className="text-[rgb(25,135,84)] font-osBold text-sm mt-1 ml-3"
              onClick={handleShowMore}
            >
              {"+ Show More"}
            </button>
          ) : (
            <button
              className="text-[rgb(220,53,69)] font-osBold text-sm mt-1 ml-3"
              onClick={handleShowLess}
            >
              - Show Less
            </button>
          )}

          <div className="border-t-[1px] border-gray-300 mt-4"></div>
        </div>
      </div>
    </div>
  );

  const renderProductsSection = () => {
    if (isNavigating) {
      return (
        <div className="w-full bg-gray-100 px-2 md:px-4">
          <TitleSkeleton />
          <SliderSkeleton />
          <FilterBarSkeleton />
          {changeView ? <ProductGridSkeleton /> : <ProductListSkeleton />}
        </div>
      );
    }
    return (
      <div className="w-full bg-gray-100 px-2 md:px-4">
        <div>
          <div className="flex justify-between flex-col">
            {isLoading ? (
              <TitleSkeleton />
            ) : (
              <div className="mb-3 md:mb-4 flex flex-col">
                <h1 className="text-xl md:text-2xl lg:text-[35px] font-pMedium text-center md:text-left">
                  {headingTitle}
                </h1>
              </div>
            )}

            {!isLoading &&
              dataType === "super" &&
              supersubCategoryDescription && (
                <div className="px-2 md:px-0">
                  {supersubCategoryDescription.includes("<") ? (
                    <div
                      dangerouslySetInnerHTML={{
                        __html: supersubCategoryDescription,
                      }}
                      className="prose prose-sm max-w-none text-sm md:text-base"
                    />
                  ) : (
                    <p>{supersubCategoryDescription}</p>
                  )}
                </div>
              )}

            {isLoading ? (
              <SliderSkeleton />
            ) : (dataType === "main" || dataType === "sub") &&
              sliderCategories?.length > 0 ? (
              <div className="bg-white px-2 md:px-4 py-3 md:py-4 mt-3 md:mt-0">
                <div>
                  <span className="text-lg md:text-xl font-pMedium">
                    Shop by Category
                  </span>
                </div>
                <HorizontalSlider
                  sliderData={sliderCategories}
                  dataType={dataType}
                />
              </div>
            ) : null}

            {isLoading ? (
              <FilterBarSkeleton />
            ) : products?.length > 0 ? (
              <div className="flex flex-col md:flex-row md:justify-between md:items-center px-2 md:px-0 py-3 md:py-4">
                <div className="text-black p-2 text-center md:text-left mb-2 md:mb-0">
                  {products?.length} items
                  {searchRadius && ` within ${searchRadius}km`}
                </div>

                <div className="flex justify-between md:justify-end space-x-2 md:space-x-4">
                  <div>
                    <button
                      onClick={() => setChangeView(!changeView)}
                      className="bg-white text-black flex items-center py-1 px-3 md:py-[6px] md:px-2 space-x-1 md:space-x-2 border border-gray-300 rounded"
                    >
                      {changeView ? (
                        <CiBoxList className="text-black text-lg md:text-xl" />
                      ) : (
                        <CiGrid41 className="text-black text-lg md:text-xl" />
                      )}
                      <p className="text-xs md:text-sm text-black font-osRegular hidden md:block">
                        {changeView ? "View as List" : "View as Grid"}
                      </p>
                    </button>
                  </div>

                  <div className="relative">
                    <div className="relative inline-block text-left">
                      <button
                        onClick={toggleDropdown}
                        className={`bg-white text-black flex items-center py-1 px-3 md:py-2 md:px-2 border border-gray-300 rounded ${
                          sortValue
                            ? "space-x-2 md:space-x-4"
                            : "space-x-8 md:space-x-20"
                        }`}
                        ref={buttonRef}
                      >
                        <p className="text-xs font-osRegular text-gray-600 md:text-gray-400">
                          Sort{sortValue && ":"}{" "}
                          {sortValue && (
                            <span className="font-osBold text-black text-xs md:text-sm">
                              {sortValue.split(":")[0]}
                            </span>
                          )}
                        </p>
                        <FaChevronDown className="text-black text-sm" />
                      </button>

                      {isSortModalOpen && (
                        <div
                          className="absolute right-0 mt-1 z-50 bg-white border border-gray-200 shadow-lg rounded min-w-[180px] md:min-w-full"
                          ref={dropdownRef}
                          style={{
                            width: buttonRef.current?.offsetWidth,
                            maxWidth: "250px",
                          }}
                        >
                          <ul>
                            <li
                              className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                              onClick={() => {
                                setSortValue("Price: Low to High");
                                toggleDropdown();
                              }}
                            >
                              Price: Low to High
                            </li>
                            <li
                              className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                              onClick={() => {
                                setSortValue("Price: High to Low");
                                toggleDropdown();
                              }}
                            >
                              Price: High to Low
                            </li>
                            <li
                              className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                              onClick={() => {
                                setSortValue("Name: Ascending");
                                toggleDropdown();
                              }}
                            >
                              Name: Ascending
                            </li>
                            <li
                              className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                              onClick={() => {
                                setSortValue("Name: Descending");
                                toggleDropdown();
                              }}
                            >
                              Name: Descending
                            </li>
                            {location?.latitude && location?.longitude && (
                              <li
                                className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                                onClick={() => {
                                  setSortValue("Distance: Nearest");
                                  toggleDropdown();
                                }}
                              >
                                Distance: Nearest
                              </li>
                            )}
                          </ul>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            ) : null}
          </div>

          {isLoading ? (
            changeView ? (
              <ProductGridSkeleton />
            ) : (
              <ProductListSkeleton />
            )
          ) : products.length > 0 ? (
            <>
             {changeView ? (
  <div className="grid grid-cols-2 gap-2 sm:gap-3 md:gap-4 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-4 px-1 md:px-4 mb-4">
    {products.map((item) => (
      <div 
        key={item?._id}
        onClick={(e) => handleProductClick(e, item?.alias)}
        className="cursor-pointer transition-all duration-200 hover:scale-105"
      >
        <ProductCardGrid
          productName={item?.productName}
          productPrice={item?.productPrice}
          salePrice={item?.salePrice}
          customImageStyles={"w-full h-36 sm:h-40 md:h-48"}
          customImgTagStyles={"w-full h-36 sm:h-40 md:h-48 object-fill"}
          productImage={getImageUrl(item?.productImages?.[0]) || cartImage}
          productId={item?._id}
          productMainCatId={item?.mainCategoryId}
          productSubCatId={item?.subCategoryId}
          productSuperSubCatId={item?.superSubCategoryId}
          sellerId={item?.sellerId}
          alias={item?.alias}
          productStarNumber={
            typeof Number(item?.packageName?.substring(0, 1)) === "number"
              ? Number(item?.packageName?.substring(0, 1))
              : ""
          }
          productData={item}
          showPrice={item?.showPrice}
          distance={item?.distance ? `${item.distance.toFixed(1)}km` : null}
          packageName={item?.packageName}
        />
      </div>
    ))}
  </div>
) : (
                <div className="flex flex-col space-y-2 md:space-y-4 px-1 md:px-0 mb-4">
  {products.map((item) => (
    <div 
      key={item?._id}
      onClick={(e) => handleProductClick(e, item?.alias)}
      className="cursor-pointer transition-all duration-200 hover:bg-gray-50"
    >
      <ProductCardList
        productName={item?.productName}
        salePrice={item?.salePrice}
        productPrice={item?.productPrice}
        productImage={getImageUrl(item?.productImages?.[0]) || cartImage}
        productId={item?._id}
        productMainCatId={item?.mainCategoryId}
        productSubCatId={item?.subCategoryId}
        productSuperSubCatId={item?.superSubCategoryId}
        sellerId={item?.sellerId}
        alias={item?.alias}
        productStarNumber={
          typeof Number(item?.packageName?.substring(0, 1)) === "number"
            ? Number(item?.packageName?.substring(0, 1))
            : ""
        }
        productData={item}
        showPrice={item?.showPrice}
        distance={item?.distance ? `${item.distance.toFixed(1)}km` : null}
        packageName={item?.packageName}
      />
    </div>
  ))}
</div>
              )}

              {/* SHOW MORE BUTTON */}
              {hasMore && (
                <div className="flex justify-center items-center py-6 px-2">
                  <button
                    onClick={handleShowMoreClick}
                    disabled={isFetchingMore}
                    className="bg-[#f97316] hover:bg-orange-600 text-white font-osSemiBold py-3 px-8 rounded-lg transition-colors duration-300 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2 min-w-[200px]"
                  >
                    {isFetchingMore ? (
                      <>
                        <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                      </>
                    ) : (
                      <span>Show More Results</span>
                    )}
                  </button>
                </div>
              )}

              {/* End Message */}
              {!hasMore && products.length > 0 && (
                <div className="text-center py-6 px-2 w-full">
                  <p className="text-gray-500 text-sm">
                 
                  </p>
                </div>
              )}
            </>
          ) : (
            !isLoading && (
              <div className="text-center items-center flex flex-col justify-center py-8 px-2">
                <img
                  src="/images/no-data-found.png"
                  alt="No products found"
                  className="w-48 md:w-auto"
                />
              </div>
            )
          )}
        </div>
      </div>
    );
  };

  return (
    <>
      {/* Navigation Loader Overlay */}
       {isNavigating && <WebsiteLoader />}
      
      <div className="flex flex-col md:flex-row relative">
        <div className="w-full md:w-1/4 bg-white hidden md:block">
          {renderCategoriesSidebar(false)}
        </div>

        <div className="w-full md:w-3/4">
          <div className="block md:hidden">{renderCategoriesSidebar(true)}</div>
          {renderProductsSection()}
        </div>
      </div>
    </>
  );
};

export default ItemsSection;