import { onMounted, onUnmounted } from "vue";
import { onBeforeRouteLeave } from "vue-router";
import type { Ref } from "vue";

export function useEditorGuards(
  dirty: Ref<boolean>,
  saveFn: () => void | Promise<void>,
): void {
  function onKeydown(e: KeyboardEvent) {
    if ((e.ctrlKey || e.metaKey) && e.key === "s") {
      e.preventDefault();
      saveFn();
    }
  }

  function onBeforeUnload(e: BeforeUnloadEvent) {
    if (dirty.value) e.preventDefault();
  }

  onMounted(() => {
    document.addEventListener("keydown", onKeydown);
    window.addEventListener("beforeunload", onBeforeUnload);
  });

  onUnmounted(() => {
    document.removeEventListener("keydown", onKeydown);
    window.removeEventListener("beforeunload", onBeforeUnload);
  });

  onBeforeRouteLeave(() => {
    if (dirty.value) return confirm("You have unsaved changes. Leave anyway?");
  });
}
