"use client";
import * as React from "react";
import { apiCall } from "../utils/apiCall.js";
import {
  subscribeProgressUpdate,
  subscribeProgressComplete
} from "@open-mercato/shared/lib/frontend/progressEvents";
const POLL_INTERVAL = 5e3;
function isVisibleProgressJob(job) {
  return job.meta?.hiddenFromTopBar !== true;
}
function useProgressPoll() {
  const [activeJobs, setActiveJobs] = React.useState([]);
  const [recentlyCompleted, setRecentlyCompleted] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const fetchJobs = React.useCallback(async () => {
    try {
      const result = await apiCall(
        "/api/progress/active"
      );
      if (result.ok && result.result) {
        setActiveJobs(result.result.active.filter(isVisibleProgressJob));
        setRecentlyCompleted(result.result.recentlyCompleted.filter(isVisibleProgressJob));
        setError(null);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch progress");
    } finally {
      setIsLoading(false);
    }
  }, []);
  const refresh = React.useCallback(() => {
    fetchJobs();
  }, [fetchJobs]);
  React.useEffect(() => {
    fetchJobs();
    let interval = setInterval(fetchJobs, POLL_INTERVAL);
    const onVisibilityChange = () => {
      if (document.hidden) {
        if (interval) {
          clearInterval(interval);
          interval = null;
        }
      } else {
        fetchJobs();
        interval = setInterval(fetchJobs, POLL_INTERVAL);
      }
    };
    document.addEventListener("visibilitychange", onVisibilityChange);
    return () => {
      if (interval) clearInterval(interval);
      document.removeEventListener("visibilitychange", onVisibilityChange);
    };
  }, [fetchJobs]);
  React.useEffect(() => {
    const unsubUpdate = subscribeProgressUpdate(() => refresh());
    const unsubComplete = subscribeProgressComplete(() => refresh());
    return () => {
      unsubUpdate();
      unsubComplete();
    };
  }, [refresh]);
  return { activeJobs, recentlyCompleted, isLoading, error, refresh };
}
export {
  useProgressPoll
};
//# sourceMappingURL=useProgressPoll.js.map
