import { createStore as m } from "zustand";
import { immer as x } from "zustand/middleware/immer";
import g from "lodash-es/cloneDeep";
import { createDynamicMFStore as l } from "../../../../../WindowBase/contexts/DynamicMFParmsContext/store.js";
import { devtools as y } from "zustand/middleware";
const I = (P, c) => {
  const { enabled: a = !1 } = c;
  return a && process.env.NODE_ENV === "development" ? y(P, c) : P;
}, C = (P, c = !1) => {
  const a = {
    ...P,
    currentZindex: P.baseZindex,
    popupsIds: [],
    hashPopups: {},
    hashGroups: {}
  };
  return m(
    I(
      x((u, e) => ({
        ...a,
        popupsActions: {
          /**
           * init: Inicializa los popups
           */
          init: (o) => {
            u((s) => {
              let h = s.baseZindex;
              for (let p = 0; p < o.length; p++) {
                const r = g(o[p]);
                r.dynamicParams = r.dynamicParams || {}, r.dynamicMFStore = l({
                  dynamicMFParameters: r.dynamicParams
                }), s.hashPopups[o[p].popupId] = {
                  ...r
                }, s.popupsIds.push(o[p].popupId), o[p].zIndex > h && (h = o[p].zIndex), s.hashGroups[o[p].groupId] || (s.hashGroups[o[p].groupId] = {
                  id: o[p].groupId,
                  count: 0
                }), s.hashGroups[o[p].groupId].count += 1;
              }
              s.currentZindex = h + 1;
            });
          },
          /**
           * addPopup: Añade un popup
           */
          addPopup: (o, s) => {
            const { popupId: h, dynamicParams: p, dynamicMFStore: r, groupId: d = "global" } = o;
            if (e().hashPopups[h])
              throw new Error(`Popup with id ${h} already exists`);
            u((n) => {
              s?.closeOthers && n.popupsIds.forEach((i) => {
                n.hashPopups[i].groupId === d && (n.hashPopups[i].status = "closing");
              });
              const f = r || l({
                dynamicMFParameters: p || {}
              });
              n.hashPopups[h] = {
                ...o,
                groupId: d,
                status: "init",
                zIndex: n.currentZindex,
                dynamicMFStore: f
              }, n.popupsIds.push(h), n.currentZindex += 1, n.hashGroups[d] || (n.hashGroups[d] = {
                id: d,
                count: 0
              }), n.hashGroups[d].count += 1, n.hashGroups[d].selectedPopupId = h, n.hashPopups[h].onSelectedPopupIdChange?.(n.hashPopups[h].groupId, h, "add");
            });
          },
          /**
           * removePopup: Elimina un popup
           */
          removePopup: (o) => {
            e().hashPopups[o] && u((s) => {
              s.hashPopups[o]?.onRemove && s.hashPopups[o].onRemove(o), s.popupsIds.splice(s.popupsIds.indexOf(o), 1), s.hashGroups[s.hashPopups[o].groupId].selectedPopupId === o && (s.hashGroups[s.hashPopups[o].groupId].selectedPopupId = void 0, s.hashPopups[o].onSelectedPopupIdChange?.(s.hashPopups[o].groupId, void 0, "remove")), s.hashGroups[s.hashPopups[o].groupId].count -= 1, s.hashGroups[s.hashPopups[o].groupId].count === 0 && delete s.hashGroups[s.hashPopups[o].groupId], delete s.hashPopups[o], s.popupsIds.length === 0 ? s.currentZindex = s.baseZindex : s.currentZindex = s.currentZindex - 1;
            });
          },
          /**
           * bringPopupOnFront: Establece el popup con mayor zindex
           */
          bringPopupOnFront: (o, s) => {
            e().hashPopups[o] && u((h) => {
              const p = h.popupsIds.reduce((r, d, n) => h.hashPopups[h.popupsIds[n]].zIndex > r ? h.hashPopups[h.popupsIds[n]].zIndex : r, h.hashPopups[h.popupsIds[0]].zIndex);
              h.hashPopups[o].zIndex !== p && (h.hashPopups[o].zIndex = h.currentZindex, h.currentZindex = h.currentZindex + 1), s && (h.hashPopups[o].enforceVisibleCount = (h.hashPopups[o].enforceVisibleCount || 0) + 1), h.hashGroups[h.hashPopups[o].groupId].selectedPopupId = o, h.hashPopups[o].onSelectedPopupIdChange?.(h.hashPopups[o].groupId, o, "select");
            });
          },
          /**
           * setFnQueryClose: Establece la función de cierre de la consulta
           */
          setFnQueryClose: (o, s) => {
            u((h) => {
              h.hashPopups[o] && (h.hashPopups[o].fnQueryClose = s);
            });
          },
          /**
           * unColapseLayoutItem
           */
          unColapseLayoutItem: (o) => {
            u((s) => {
              s.hashPopups[o] && (s.hashPopups[o].collapsed = !1);
            });
          },
          /**
           * colapseLayoutItem
           */
          colapseLayoutItem: (o) => {
            u((s) => {
              s.hashPopups[o] && (s.hashPopups[o].collapsed = !0);
            });
          },
          /**
           * removePopupsByGroupId: Elimina los popups de un grupo
           */
          closePopupsByGroupId: (o) => {
            u((s) => {
              s.popupsIds.filter((p) => s.hashPopups[p].groupId === o).forEach((p) => {
                s.hashPopups[p].status = "closing";
              });
            });
          },
          /**
           * removeAllPopupsByGroupId: Elimina todos los popups de un grupo
           */
          removeAllPopupsByGroupId: (o) => {
            u((s) => {
              const h = s.popupsIds.filter((p) => s.hashPopups[p].groupId === o);
              s.popupsIds = s.popupsIds.filter((p) => s.hashPopups[p].groupId !== o), h.forEach((p) => {
                delete s.hashPopups[p];
              }), delete s.hashGroups[o];
            });
          },
          /**
           * closeAllPopupsByParentId: Cierra todos los popups que dependan de un popup padre
           */
          closeAllPopupsByParentId: (o) => {
            u((s) => {
              s.popupsIds.forEach((h) => {
                s.hashPopups[h].parentId === o && (s.hashPopups[h].status = "closing");
              });
            });
          },
          /**
           * setSelectedPopupId: Establece el popup seleccionado
           */
          setSelectedPopupId: (o, s) => {
            u((h) => {
              h.hashGroups[o] && (h.hashGroups[o].selectedPopupId = s);
            });
          }
        },
        popupActions: {
          /**
           * updatePopup: Actualiza un popup
           */
          update: (o, s) => {
            e().hashPopups[o] && u((h) => {
              h.hashPopups[o] = { ...h.hashPopups[o], ...s };
            });
          },
          /**
           * showPopup: Muestra un popup
           */
          show: (o) => {
            e().hashPopups[o] && u((s) => {
              s.hashPopups[o].status = "init";
            });
          },
          /**
           * hidePopup: Oculta un popup
           */
          hide: (o) => {
            e().hashPopups[o] && u((s) => {
              s.hashPopups[o].status = "hidden";
            });
          },
          /**
           * closePopup: Cierra un popup
           */
          close: (o, s = !0) => {
            if (e().hashPopups[o]) {
              if (e().hashPopups[o].fnQueryClose && s) {
                e().hashPopups[o].fnQueryClose?.();
                return;
              }
              u((h) => {
                h.hashPopups[o].status = "closing";
              });
            }
          },
          /**
           * setActions: Establece las acciones del popup
           */
          setActions: (o, s, h, p) => {
            u((r) => {
              r.hashPopups[o] && (r.hashPopups[o].moduleActions = s, r.hashPopups[o].version = h, r.hashPopups[o].buildTime = p);
            });
          },
          /**
           * startProgress: Marca el popup como cargando (loading: true)
           */
          startProgress: (o) => {
            u((s) => {
              s.hashPopups[o] && (s.hashPopups[o].loading = !0);
            });
          },
          /**
           * stopProgress: Marca el popup como finalizado (loading: false)
           */
          stopProgress: (o) => {
            u((s) => {
              s.hashPopups[o] && (s.hashPopups[o].loading = !1);
            });
          }
        }
      })),
      { name: `PopupsStore: ${P.storeId}`, enabled: c }
    )
  );
};
export {
  C as createPopupsStore
};
