import { useState, useRef, useEffect, useCallback } from 'react';

function arrayIdsEqual(a, b) {
  if (a === b) return true;
  if (a.length !== b.length) return false;
  const seen = /* @__PURE__ */ new Set();
  for (const item of a) seen.add(item.id);
  for (const item of b) {
    if (!seen.has(item.id)) return false;
  }
  return true;
}

const defaultEqual = (a, b) => Object.is(a, b);
function useConfirmationDraft({
  value,
  onCommit,
  isOpen,
  enabled,
  isEqual = defaultEqual
}) {
  const [draft, setDraftState] = useState(value);
  const prevOpenRef = useRef(false);
  const prevValueRef = useRef(value);
  useEffect(() => {
    const wasOpen = prevOpenRef.current;
    const prevValue = prevValueRef.current;
    prevOpenRef.current = isOpen;
    prevValueRef.current = value;
    if (!enabled) return;
    const justOpened = isOpen && !wasOpen;
    const valueChangedWhileOpen = isOpen && !isEqual(prevValue, value);
    if (justOpened || valueChangedWhileOpen) {
      setDraftState(value);
    }
  }, [isOpen, enabled, value, isEqual]);
  const setDraft = useCallback(
    (next) => {
      if (!enabled) {
        onCommit(next);
        return;
      }
      setDraftState(next);
    },
    [enabled, onCommit]
  );
  const apply = useCallback(() => {
    if (!enabled) return;
    onCommit(draft);
  }, [enabled, onCommit, draft]);
  const cancel = useCallback(() => {
    if (!enabled) return;
    setDraftState(value);
  }, [enabled, value]);
  const displayValue = enabled ? draft : value;
  const isDirty = enabled && !isEqual(draft, value);
  return { displayValue, setDraft, apply, cancel, isDirty };
}

const resolveConfirmation = (prop) => {
  if (!prop) {
    return { enabled: false, applyLabel: "Apply", cancelLabel: "Cancel" };
  }
  if (prop === true) {
    return { enabled: true, applyLabel: "Apply", cancelLabel: "Cancel" };
  }
  return {
    enabled: true,
    applyLabel: prop.applyLabel ?? "Apply",
    cancelLabel: prop.cancelLabel ?? "Cancel"
  };
};

export { arrayIdsEqual as a, resolveConfirmation as r, useConfirmationDraft as u };
//# sourceMappingURL=confirmationTypes-CG7xl50f.js.map
