import { computed, ref, toValue, watch } from "vue";
import { useDocumentVisibility, useIntervalFn } from "@vueuse/core";
function resolveInterval(raw, def) {
  if (raw === true) return def;
  if (typeof raw === "number" && raw > 0) return raw;
  return 0;
}
export function useAutoRefresh(opts) {
  const documentVisibility = useDocumentVisibility();
  const defaultSeconds = opts.defaultSeconds ?? 60;
  const intervalSeconds = computed(() => resolveInterval(toValue(opts.interval), defaultSeconds));
  const enabled = computed(() => intervalSeconds.value > 0);
  const isUserPaused = ref(false);
  const remainingSeconds = ref(0);
  const isLoadingMirror = computed(() => opts.isLoading?.value === true);
  const paused = computed(
    () => !enabled.value || isUserPaused.value || documentVisibility.value === "hidden" || opts.paused?.value === true || isLoadingMirror.value
  );
  const isActive = computed(() => enabled.value && !paused.value);
  const ticker = useIntervalFn(async () => {
    if (paused.value) return;
    if (remainingSeconds.value <= 1) {
      try {
        await opts.reload();
      } finally {
        remainingSeconds.value = intervalSeconds.value;
      }
    } else {
      remainingSeconds.value -= 1;
    }
  }, 1e3, { immediate: false });
  watch(enabled, (on) => {
    remainingSeconds.value = on ? intervalSeconds.value : 0;
  }, { immediate: true });
  watch(isActive, (active) => {
    if (active && typeof document !== "undefined") ticker.resume();
    else ticker.pause();
  }, { immediate: true });
  watch(intervalSeconds, (s) => {
    if (enabled.value && remainingSeconds.value > s) remainingSeconds.value = s;
  });
  return {
    enabled,
    isActive,
    isLoading: isLoadingMirror,
    intervalSeconds,
    remainingSeconds,
    isUserPaused,
    togglePause: () => {
      isUserPaused.value = !isUserPaused.value;
    },
    reset: () => {
      remainingSeconds.value = intervalSeconds.value;
    },
    reload: opts.reload
  };
}
