"use client";
import { useState, useRef, useEffect } from "react";
import { useAppEvent } from "./useAppEvent.js";
const IDLE_STATE = {
  status: "idle",
  progress: 0,
  processedCount: 0,
  totalCount: 0,
  errors: 0,
  elapsedMs: 0
};
function useOperationProgress(operationPattern, operationId) {
  const [state, setState] = useState(IDLE_STATE);
  const timerRef = useRef(null);
  const startedAtRef = useRef(void 0);
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    };
  }, []);
  useAppEvent(
    operationPattern,
    (event) => {
      const payload = event.payload;
      if (!payload || typeof payload.status !== "string") return;
      if (operationId && payload.operationId !== operationId) return;
      startedAtRef.current = payload.startedAt;
      const newState = {
        status: payload.status,
        progress: payload.progress,
        processedCount: payload.processedCount,
        totalCount: payload.totalCount,
        currentStep: payload.currentStep,
        errors: payload.errors,
        startedAt: payload.startedAt,
        elapsedMs: payload.startedAt ? Date.now() - payload.startedAt : 0
      };
      setState(newState);
      if (payload.status === "running" && !timerRef.current) {
        timerRef.current = setInterval(() => {
          if (startedAtRef.current) {
            setState((prev) => ({
              ...prev,
              elapsedMs: Date.now() - startedAtRef.current
            }));
          }
        }, 1e3);
      }
      if (payload.status !== "running" && timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    },
    [operationId]
  );
  return state;
}
export {
  useOperationProgress
};
//# sourceMappingURL=useOperationProgress.js.map
