import { jsx as W } from "@emotion/react/jsx-runtime";
import { createContext as x, useRef as d, useCallback as h, useEffect as o } from "react";
import { useStore as a } from "zustand";
import { shallow as u } from "zustand/shallow";
import { useFirstRender as B } from "@m4l/graphics";
import { useHostTools as V, useModuleDictionary as j, useNetwork as q, useFlagsStore as z, CommonFlags as J, EmitEvents as S } from "@m4l/core";
import { createAreasStore as K } from "./store.js";
import { usePopupsStore as Q } from "../../../popups/components/PopupsProvider/hooks/usePopupsStore.js";
const U = x(null);
function se(A) {
  const {
    children: I,
    loadAreasFromNetwork: F,
    loadCookiesFromNetwork: _,
    onLoad: i,
    onReady: c,
    onSelectLayout: l,
    storeId: P,
    storeDevtoolsEnabled: k
  } = A, { events_add_listener: v, events_remove_listener: y } = V(), { getLabel: s } = j(), { networkOperation: M } = q(), g = B([s]), { addFlag: w } = z((e) => e.flagsActions), r = d(null), {
    addPopup: R,
    removePopup: H,
    closePopupsByGroupId: C,
    bringPopupOnFront: N,
    closeAllPopupsByParentId: O,
    setSelectedPopupId: T
  } = Q(
    (e) => e.popupsActions,
    u
  );
  r.current || (r.current = K({
    storeId: P,
    getLabel: s,
    loadAreasFromNetwork: F,
    loadCookiesFromNetwork: _,
    networkOperation: M,
    ownerState: {
      status: "init",
      readyForHooks: !1
    },
    popupsProviderMethods: {
      addPopup: R,
      removePopup: H,
      removePopupsByGroupId: C,
      bringPopupOnFront: N,
      closeAllPopupsByParentId: O,
      setSelectedPopupId: T
    }
  }, k), r.current?.getState().areasActions.init());
  const t = a(r.current, (e) => e.ownerState?.status, u), p = a(r.current, (e) => e.ownerState?.readyForHooks, u), n = a(r.current, (e) => e.currentModuleId), f = d(""), m = d(!1), { setHandlerGetLabel: b, setExternalState: D } = a(
    r.current,
    (e) => e.areasActions,
    u
  ), E = h((e) => {
    const G = r.current?.getState().currentAreaId, L = r.current?.getState().areasIds;
    G && L && r.current?.getState().areaActions.addWindow(e);
  }, []);
  return o(() => {
    t === "loaded" && (i && i(), w(J.FLAG_AREAS_LOADED));
  }, [t]), o(() => {
    !m.current && t === "loaded" && p && (m.current = !0, c && c());
  }, [c, p, t]), o(() => {
    t === "loaded" && n !== f.current && (l && l(n), f.current = n);
  }, [n, t]), o(() => {
    g || b(s);
  }, [s]), o(() => (v(S.EMMIT_EVENT_HOST_EMERGE_WINDOW, E), D({ readyForHooks: !0 }), () => {
    y(S.EMMIT_EVENT_HOST_EMERGE_WINDOW, E);
  }), []), /* @__PURE__ */ W(U.Provider, { value: r.current, children: I });
}
export {
  U as AreasContext,
  se as AreasProvider
};
