"use client";

import { useEffect } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchSectionList, selectCategorySections } from "@/store/slices/homeSlice";
import { slugify } from "@/lib/utils/slugify";

interface CategorySectionsLoaderProps {
  categorySlug: string;
}

export default function CategorySectionsLoader({ categorySlug }: CategorySectionsLoaderProps) {
  const dispatch = useAppDispatch();
  const navCategories = useAppSelector((s) => s.navCategories.items);
  const category = navCategories.find((c) => slugify(c.name) === categorySlug);
  const categoryId = category?.id ?? 0;
  const sections = useAppSelector((s) => selectCategorySections(s, categoryId));

  useEffect(() => {
    if (categoryId && sections.length === 0) {
      dispatch(
        fetchSectionList({ is_home_screen: 2, top_category_id: categoryId }),
      );
    }
  }, [categoryId, dispatch, sections.length]);

  return null;
}
