import { useEffect } from "react";

/**
 * Registers Ctrl/Cmd+S (save) and optionally Ctrl/Cmd+P (publish) keyboard shortcuts.
 * Pass `enabled = false` to temporarily disable (e.g. when a window is not focused).
 */
export function useKeyboardSave(
  onSave: () => void,
  onPublish?: () => void,
  enabled = true,
) {
  useEffect(() => {
    if (!enabled) return;
    const handler = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "s") {
        e.preventDefault();
        onSave();
      }
      if (onPublish && (e.metaKey || e.ctrlKey) && e.key === "p") {
        e.preventDefault();
        onPublish();
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [onSave, onPublish, enabled]);
}
