import { useFetch as b } from "../../../../../../hooks/useFetch.js";
import { useRef as T, useState as x, useCallback as l, useEffect as P } from "../../../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { usePollingConfig as y } from "./usePollingConfig.js";
import { useConfigContext as F } from "../../../../../../core/ConfigContext/preact/context.js";
import { EMPTY_OBJECT as R } from "../../../../../../utils/value/constants.js";
const Y = ({ grantId: n, initialMissingActions: t }) => {
  const { getGrants: u } = F().endpoints, {
    pollingConfig: {
      missingActions: { initialIntervalMs: i, maxDurationMs: a, backoffMultiplier: m }
    }
  } = y(), e = t.length <= 1, s = T(0), o = T(0), [r, c] = x(!e), [E, f] = x(t), { data: p, isFetching: g, refetch: d } = b({
    fetchOptions: {
      enabled: !1,
      onSuccess: l(() => {
        s.current += 1;
      }, [])
    },
    queryFn: l(async () => u?.(R), [u])
  });
  P(() => {
    s.current = 0, o.current = 0, c(!e), f(t);
  }, [n, t, e]), P(() => {
    if (!e || r || g) return;
    o.current === 0 && (o.current = Date.now());
    const h = p?.data?.find((D) => D.id === n)?.missingActions ?? t;
    f(h);
    const C = i * Math.pow(m, Math.max(0, s.current)), w = Date.now() - o.current + C >= a;
    if (h.length > 1 || w) {
      c(!0);
      return;
    }
    const A = setTimeout(() => {
      d();
    }, C);
    return () => clearTimeout(A);
  }, [
    p,
    g,
    d,
    n,
    r,
    e,
    t,
    i,
    m,
    a
  ]);
  const M = l(() => c(!0), []);
  return { missingActions: E, isPollingComplete: r, forcePollingComplete: M };
};
export {
  Y as useMissingActionsPolling
};
