"use client";

import * as React from "react";
import { useAppDispatch } from "@/store/hooks";
import { mergeDashboardSection } from "@/store";
import {
  useDashboardActivityFeedQuery,
  useDashboardKpisQuery,
  useDashboardLeaderboardQuery,
  useDashboardPipelineQuery,
  useDashboardRevenueQuery,
} from "@/features/dashboard/hooks/use-dashboard-section-queries";

/**
 * Mirrors each TanStack Query dashboard section into {@link dashboardStatsCache},
 * so the home page can paint instantly from persisted Redux while sections refetch.
 */
export function DashboardStatsCacheSync() {
  const dispatch = useAppDispatch();
  const { data: kpis } = useDashboardKpisQuery();
  const { data: revenueOverTime } = useDashboardRevenueQuery();
  const { data: pipelineData } = useDashboardPipelineQuery({
    module: "Lead",
  });
  const { data: leaderboard } = useDashboardLeaderboardQuery();
  const { data: activityFeed } = useDashboardActivityFeedQuery();

  React.useLayoutEffect(() => {
    if (kpis !== undefined) {
      dispatch(mergeDashboardSection({ kpis }));
    }
  }, [kpis, dispatch]);

  React.useLayoutEffect(() => {
    if (revenueOverTime !== undefined) {
      dispatch(mergeDashboardSection({ revenueOverTime }));
    }
  }, [revenueOverTime, dispatch]);

  React.useLayoutEffect(() => {
    if (pipelineData !== undefined) {
      dispatch(mergeDashboardSection({ pipelineData }));
    }
  }, [pipelineData, dispatch]);

  React.useLayoutEffect(() => {
    if (leaderboard !== undefined) {
      dispatch(mergeDashboardSection({ leaderboard }));
    }
  }, [leaderboard, dispatch]);

  React.useLayoutEffect(() => {
    if (activityFeed !== undefined) {
      dispatch(mergeDashboardSection({ activityFeed }));
    }
  }, [activityFeed, dispatch]);

  return null;
}
