"use client";

import { useEffect, useRef } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchSectionList, selectHomePagination } from "@/store/slices/homeSlice";
import type { RootState } from "@/store/store";

const HOME_KEY = "1_0";

export default function HomeSectionsLoader() {
  const dispatch = useAppDispatch();

  // Tracks which pages have already been dispatched — prevents double-dispatch
  // across re-renders regardless of what the API returns.
  const dispatchedPages = useRef<Set<number>>(new Set());

  const isLoaded    = useAppSelector((s: RootState) => s.home.loadedKeys.includes(HOME_KEY));
  const isLoading   = useAppSelector((s: RootState) => s.home.isLoading);
  const hasMore     = useAppSelector((s: RootState) => s.home.paginationByKey[HOME_KEY]?.hasMore     ?? false);
  const currentPage = useAppSelector((s: RootState) => s.home.paginationByKey[HOME_KEY]?.currentPage ?? 0);
  const totalPage   = useAppSelector((s: RootState) => s.home.paginationByKey[HOME_KEY]?.totalPage   ?? 0);

  // Load page 1 exactly once on mount
  useEffect(() => {
    if (dispatchedPages.current.has(1)) return;
    dispatchedPages.current.add(1);
    dispatch(fetchSectionList({ is_home_screen: 1, top_category_id: 0, page: 1 }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Auto-load the next page after each page completes
  useEffect(() => {
    if (!isLoaded || isLoading) return;
    if (!hasMore || currentPage <= 0 || currentPage >= totalPage) return;

    const nextPage = currentPage + 1;
    if (dispatchedPages.current.has(nextPage)) return; // already dispatched
    dispatchedPages.current.add(nextPage);

    dispatch(fetchSectionList({ is_home_screen: 1, top_category_id: 0, page: nextPage }));
  }, [dispatch, isLoaded, isLoading, hasMore, currentPage, totalPage]);

  return null;
}
