import { useState as p, useRef as y, useMemo as M, useCallback as b, useEffect as Q } from "react";
function W(f, n, s) {
  const d = (s == null ? void 0 : s.selectedKeys) !== void 0, [N, k] = p({}), [T, I] = p([]), [q, w] = p(void 0), l = y({}), S = y([]), O = y(s);
  O.current = s;
  const F = JSON.stringify((s == null ? void 0 : s.selectedKeys) ?? []), v = M(() => d ? Object.fromEntries(((s == null ? void 0 : s.selectedKeys) ?? []).map((t) => [t, !0])) : {}, [d, F]), G = M(() => !d || !n ? [] : f.filter((t) => v[String(t[n])]), [d, n, f, v]), h = b(
    (t, e) => String(n ? t[n] : e),
    [n]
  ), C = b(
    (t) => t.map((e) => f.find((r, o) => h(r, o) === e)).filter((e) => e !== void 0),
    [f, h]
  ), E = b((t, e) => Object.keys(e).filter((r) => !t[r]), []), x = b((t, e) => Object.keys(t).filter((r) => !e[r]), []);
  Q(() => {
    if (d || !n || Object.keys(l.current).length === 0) return;
    const t = new Set(f.map((c) => String(c[n]))), e = l.current;
    if (Object.keys(e).filter((c) => !t.has(c)).length === 0) return;
    const o = Object.fromEntries(Object.entries(e).filter(([c]) => t.has(c))), i = S.current.filter((c) => t.has(String(c[n])));
    l.current = o, S.current = i, k(o), I(i);
  }, [d, f, n]);
  const H = b(
    (t) => {
      var A, B, J;
      const e = O.current;
      if ((e == null ? void 0 : e.selectedKeys) !== void 0) {
        const R = Object.fromEntries((e.selectedKeys ?? []).map((j) => [j, !0])), g = typeof t == "function" ? t(R) : t, L = Object.keys(g), P = n ? f.filter((j) => g[String(j[n])]) : [];
        (A = e.onSelectedKeysChange) == null || A.call(e, L), (B = e.onSelect) == null || B.call(e, P);
        return;
      }
      const r = l.current, o = typeof t == "function" ? t(r) : t, i = E(r, o), c = x(r, o);
      let u = S.current;
      i.length > 0 && (u = [...u, ...C(i)]), c.length > 0 && (u = u.filter((R) => {
        if (n)
          return !c.includes(String(R[n]));
        const g = f.indexOf(R);
        return g < 0 ? !0 : !c.includes(h(R, g));
      })), l.current = o, S.current = u, k(o), I(u), (J = e == null ? void 0 : e.onSelect) == null || J.call(e, u);
    },
    [C, E, x, f, h, n]
  );
  return {
    selectedRow: d ? v : N,
    selectedRows: d ? G : T,
    sorting: q,
    setSorting: w,
    handleRowSelectionChange: H
  };
}
export {
  W as default
};
//# sourceMappingURL=useTableState.js.map
