"use client";

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "../store";
import { categoryImages, homeContent } from "../api/api";
import dynamic from "next/dynamic";
import { useInView } from "react-intersection-observer";
import HeroBanner from "../common/HeroBanner";
const CategorySlider = dynamic(
  () => import("../components/bayerProfile/pages/components/CategorySlider")
);
const AuctionListings = dynamic(
  () => import("../components/bayerProfile/pages/components/AuctionListings")
);
const CategoryCarousel = dynamic(
  () => import("../components/bayerProfile/pages/components/CategoryCarousel")
);

const Page = () => {
  const dispatch: AppDispatch = useDispatch();
  const { categoryImagesData } = useSelector(
    (state: RootState) => state.CategoryImagesReducer
  );
  const categoryData = categoryImagesData?.data || [];
  const { ref: auctionListingsRef, inView: auctionListingsInView } = useInView({
    triggerOnce: true,
    rootMargin: "200px 0px",
  });

  const { ref: categoryCarouselRef, inView: categoryCarouselInView } =
    useInView({
      triggerOnce: true,
      rootMargin: "200px 0px",
    });

  const { ref: categorySliderRef, inView: categorySliderInView } = useInView({
    triggerOnce: true,
    rootMargin: "200px 0px",
  });

  useEffect(() => {
    if (!categoryImagesData?.data) {
      dispatch(categoryImages());
    }
  }, [dispatch, categoryImagesData]);

  useEffect(() => {
    dispatch(homeContent());
  }, [dispatch]);

  return (
    <>
      <div>
        <HeroBanner />
        <div ref={categorySliderRef}>
          {categorySliderInView ? <CategorySlider /> : null}
        </div>
        <div ref={auctionListingsRef}>
          {auctionListingsInView ? <AuctionListings /> : null}
        </div>
        <div className="flex gap-6 items-center lg:max-w-6xl justify-center mx-auto mt-10 pb-11">
          <div className="w-full" ref={categoryCarouselRef}>
            {categoryCarouselInView ? (
              <CategoryCarousel categoryData={categoryData} />
            ) : null}
          </div>
        </div>
      </div>
    </>
  );
};

export default Page;
