import { jsx as D } from "@emotion/react/jsx-runtime";
import { useModuleDictionary as I } from "@m4l/core";
import { forwardRef as b, useRef as O, useImperativeHandle as A, useEffect as u, createContext as T } from "react";
import { useStore as r } from "zustand";
import { shallow as o } from "zustand/shallow";
import { useComponentSize as j } from "../../../hooks/useComponentSize/index.js";
import { formatToInitialSorts as N } from "../helpers/formatToInitialSorts.js";
import { formatToRowSort as P } from "../helpers/formatToRowSort.js";
import { createDynamicSortStore as V } from "./DynamicSortStore.js";
const H = T(null), Q = b(
  (m, l) => {
    const {
      automatic: S = !0,
      fields: d,
      initialAppliedSorts: f = [],
      onChangeSorts: p,
      dataTestId: g = "",
      size: i = "medium",
      storeId: h,
      storeDevtoolsEnabled: v,
      visibleRefresh: n = !0,
      children: y
    } = m, { currentSize: s } = j(i), a = s === "small" || s === "medium" ? s : "medium", { getLabel: C } = I(), t = O(null);
    t.current || (t.current = V(
      {
        fields: d,
        automatic: S,
        getLabel: C,
        dataTestId: g,
        size: i,
        storeId: h,
        visibleRefresh: n,
        ownerState: {
          isDirty: !1,
          inEdition: !1,
          isValid: !0,
          isEmpty: !0,
          size: i
        }
      },
      v
    ), t.current.getState().actions.init(f));
    const x = r(
      t.current,
      (e) => e.actions.fireOnChangeSorts,
      o
    ), E = r(
      t.current,
      (e) => e.actions.addExternalSort,
      o
    ), R = r(
      t.current,
      (e) => e.actions.removeExternalSort,
      o
    ), w = r(
      t.current,
      (e) => e.actions.getNewId,
      o
    ), z = r(
      t.current,
      (e) => () => e.appliedSorts,
      o
    );
    A(l, () => ({
      fireOnChangeSort: x,
      addExternalSort: E,
      removeExternalSort: R,
      getNewId: w,
      getCurrentSorts: z
    }));
    const c = r(
      t.current,
      (e) => e.countOnChangeSortsApplyed,
      o
    );
    return u(() => {
      if (c === 0)
        return;
      const e = t.current?.getState();
      e && p?.(
        N(e.appliedSorts),
        P(e.appliedSorts)
      );
    }, [c]), u(() => {
      t.current?.getState().size !== a && t.current?.getState().actions.setSize(a), t.current?.getState().visibleRefresh !== n && t.current?.getState().actions.setVisibleRefresh(n);
    }, [a, n]), /* @__PURE__ */ D(H.Provider, { value: t.current, children: y });
  }
);
export {
  H as DynamicSortContext,
  Q as DynamicSortProvider
};
