"use client";
import { useFetchDataInfinite } from "@/hooks/use-infinite-fetch";
import { useTriggerScroll } from "@/hooks/use-trigger-scroll";
import { useLocale, useTranslations } from "next-intl";
import Loading from "../shared/Loading";
import TriggerFetchingElement from "../shared/TriggerFetchingElement";
import VendorCard from "./VendorCard/VendorCard";
import ProductState from "./VendorCard/ProductState";

export default function PaginationVendorProduct({ categories }) {
  const l = useLocale();
  const t = useTranslations("vendor");

  const { data, isError, isLoading, fetchNextPage, hasNextPage, isFetching } =
    useFetchDataInfinite(`/user/products`, l);

  const { lastElementRef } = useTriggerScroll({
    isLoading,
    fetchNextPage,
    threshold: 0,
    rootMargin: "0px", // start fetching data before 200 px of the end of the section
    hasNextPage,
    isError,
  });
  const products = data?.pages.flatMap(
    (page) => page?.data?.data?.data // Note the nested .data structure
  );

  return (
    <>
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
        {products?.map((item, i) => {
          return (
            <ProductState item={item} key={i}>
              <VendorCard product={item} categories={categories} />
            </ProductState>
          );
        })}
      </div>
      {/* next */}
      <TriggerFetchingElement lastElementRef={lastElementRef} />
      {(isFetching || isLoading) && (
        <div className="relative mt-20">
          <Loading />
        </div>
      )}
    </>
  );
}
