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