import { useEffect } from "react";
import { useStore, type StoreApi } from "zustand";
import { useEditorStore } from "@/stores/editorStore";
import type { EditorStore } from "@/stores/editorStore";

export function useUnsavedGuard(storeApi?: StoreApi<EditorStore>) {
  const store = storeApi ?? useEditorStore;
  const isDirty = useStore(store, (s) => s.isDirty);

  useEffect(() => {
    const handler = (e: BeforeUnloadEvent) => {
      if (isDirty) {
        e.preventDefault();
      }
    };
    window.addEventListener("beforeunload", handler);
    return () => window.removeEventListener("beforeunload", handler);
  }, [isDirty]);
}
