import { useState as h, useRef as H, useEffect as K, useCallback as b } from "react";
const k = "active", N = "data-id", O = ".table-checkbox", P = ".table-action", j = (o) => {
  const {
    tableData: e,
    idKey: n,
    initialSelectedRowIds: r = [],
    initialActiveRowId: A = "",
    checkboxQuerySelector: w = '.table-checkbox input[type="checkbox"]',
    dataAttributeName: l = N,
    ref: _
  } = o, [d, u] = h(r), [R, p] = h(A), [f, x] = h(A), D = H(null), a = _ ?? D;
  K(() => {
    E();
  }, [R, f, d]);
  const E = () => {
    if (!a.current)
      return;
    const t = [...a.current.rows];
    f !== R && (q(t, f, l), $(t, R, l)), d.forEach((s) => {
      V(t, s, l, w);
    });
  }, v = b((t) => {
    t.preventDefault(), t.stopPropagation();
    const c = t.currentTarget.getAttribute(l) ?? "", i = t.target, g = i.closest(O), U = i.closest(P);
    g || U || S(c);
  }, []), S = (t = "") => {
    p((s) => {
      const c = s === t ? "" : t;
      return x(s), c;
    });
  }, y = b((t) => {
    t.preventDefault(), t.stopPropagation();
    const c = t.target.closest(`tr[${l}]`)?.getAttribute(l);
    if (!c) {
      console.warn("Could not find row ID for selection event.");
      return;
    }
    u((i) => i.includes(c) ? (T([c]), i.filter((g) => g !== c)) : [...i, c]);
  }, []), B = b(
    (t) => {
      const s = e.map((c) => `${c[n]}`);
      if (u(t ? s : []), t)
        u(s);
      else {
        u([]), T(s);
        for (const c in s) {
          const i = a.current ? [...a.current.rows] : [];
          L([...i], c, l, w);
        }
      }
    },
    [e]
  ), T = (t) => {
    const s = a.current ? [...a.current.rows] : [];
    t.forEach((c) => {
      L(s, c, l, w);
    });
  }, I = d.length > 0, F = I && d.length === e.length && e.length > 0;
  return {
    tableRef: a,
    selectedRowIds: d,
    activeRowId: R,
    onSelection: y,
    onActiveRowChange: v,
    onToggleAll: B,
    updateRowSelection: E,
    setSelectedRowIds: (t) => u(t),
    setActiveRowId: (t) => S(t),
    hasSelection: I,
    isAllSelected: F
  };
}, C = (o, e, n) => {
  if (e)
    return o.find((r) => r.getAttribute(n) === e);
}, $ = (o, e, n) => {
  C(o, e, n)?.classList.add(k);
}, q = (o, e, n) => {
  C(o, e, n)?.classList.remove(k);
}, Q = (o, e) => o.querySelector(e), m = (o, e, n, r, A) => {
  const w = C(o, e, n);
  if (w) {
    const l = Q(w, r);
    l && (l.checked = A);
  }
}, V = (o, e, n, r) => {
  m(o, e, n, r, !0);
}, L = (o, e, n, r) => {
  m(o, e, n, r, !1);
};
export {
  k as ACTIVE_CLASS,
  N as DEFAULT_DATA_ATTRIBUTE,
  P as DEFAULT_TABLE_ACTION_CELL_CLASS,
  O as DEFAULT_TABLE_CHECKBOX_CELL_CLASS,
  j as default,
  L as deselectRow,
  C as getRowByDataAttribute,
  $ as highlightRow,
  q as removeHighlightFromRow,
  V as selectRow,
  m as setRowCheckboxState
};
//# sourceMappingURL=useTableSelection.js.map
