// packages/editor/src/components/sync-connection-error-modal/use-retry-countdown.ts
import { useState, useEffect, useRef } from "@wordpress/element";
function useRetryCountdown(connectionStatus) {
  const [secondsRemaining, setSecondsRemaining] = useState();
  const hasRetriedRef = useRef(false);
  useEffect(() => {
    if (!connectionStatus) {
      return;
    }
    if ("connected" === connectionStatus.status) {
      setSecondsRemaining(void 0);
      hasRetriedRef.current = false;
      return;
    }
    if ("disconnected" !== connectionStatus.status || !connectionStatus.willAutoRetryInMs) {
      return;
    }
    const { willAutoRetryInMs: retryInMs } = connectionStatus;
    const retryAt = Date.now() + retryInMs;
    const hasRetried = hasRetriedRef.current;
    hasRetriedRef.current = true;
    if (hasRetried) {
      setSecondsRemaining(0);
    }
    let countdownIntervalId = null;
    const startCountdown = () => {
      setSecondsRemaining(Math.ceil((retryAt - Date.now()) / 1e3));
      countdownIntervalId = setInterval(() => {
        const remaining = Math.ceil((retryAt - Date.now()) / 1e3);
        setSecondsRemaining(Math.max(0, remaining));
        if (remaining <= 0 && countdownIntervalId) {
          clearInterval(countdownIntervalId);
        }
      }, 1e3);
    };
    const retryingDelayId = hasRetried ? setTimeout(startCountdown, 500) : null;
    if (!retryingDelayId) {
      startCountdown();
    }
    return () => {
      if (retryingDelayId) {
        clearTimeout(retryingDelayId);
      }
      if (countdownIntervalId) {
        clearInterval(countdownIntervalId);
      }
    };
  }, [connectionStatus]);
  return {
    onManualRetry: () => {
      setSecondsRemaining(0);
    },
    secondsRemaining
  };
}
export {
  useRetryCountdown
};
//# sourceMappingURL=use-retry-countdown.mjs.map
