import { useState as C, useRef as m, useEffect as h, useCallback as W } from "react";
const j = (n) => JSON.stringify(n, (e, r) => !r || typeof r != "object" || Array.isArray(r) ? r : Object.keys(r).sort().reduce((c, l) => (c[l] = r[l], c), {}));
function O(n, e, r = 300, c = 1e3, l) {
  const [D, f] = C(!1), [I, o] = C(!1), d = m(null), t = m(0), T = m(n), w = m(e), u = l || j;
  h(() => {
    t.current += 1;
    const a = t.current, k = T.current !== n, R = w.current !== e;
    if (T.current = n, w.current = e, e === null) {
      const i = window.setTimeout(() => {
        a === t.current && (f(!1), o(!1));
      }, 0);
      return () => clearTimeout(i);
    }
    if (R && !k) {
      const i = window.setTimeout(() => {
        if (a === t.current) {
          const s = u(n), y = u(e);
          f(s !== y), o(!1);
        }
      }, 0);
      return () => clearTimeout(i);
    }
    const g = k ? window.setTimeout(() => {
      a === t.current && o(!0);
    }, 0) : null, z = setTimeout(() => {
      const i = window.requestIdleCallback || ((s) => window.setTimeout(
        () => s({
          didTimeout: !1,
          timeRemaining: () => 50
        }),
        1
      ));
      d.current = i(
        (s) => {
          if (s.timeRemaining() > 0 || s.didTimeout) {
            if (a !== t.current) return;
            const y = u(n), P = u(e);
            f(y !== P), o(!1);
          }
        },
        { timeout: c }
      );
    }, r);
    return () => {
      g !== null && clearTimeout(g), clearTimeout(z), d.current !== null && ((window.cancelIdleCallback || window.clearTimeout)(d.current), d.current = null);
    };
  }, [n, e, r, c, u]);
  const b = W(() => {
    f(!1), o(!1);
  }, []);
  return {
    isDirty: e === null ? !1 : D,
    isDirtyPending: e === null ? !1 : I,
    resetDirty: b
  };
}
export {
  O as u
};
