import React__default, { useState, useEffect, useCallback, useContext, createContext } from "react";
import { getI18n, useTranslation } from "react-i18next";
import { l as loadModuleTranslations } from "./translations-3awnZui-.esm.js";
import { m as modules } from "./modules-Bpg0vTA2.esm.js";
import { u as useAuth, a as AuthProvider } from "./useAuth-CEQTm2rv.esm.js";
import { useDispatch, Provider } from "react-redux";
import { f as usePages } from "./useAccountSetting-BqyN2n1w.esm.js";
import { useLocation, BrowserRouter } from "react-router-dom";
import { j as jsxRuntimeExports } from "./jsx-runtime-ClFauRgV.esm.js";
import { useSnackbar, enqueueSnackbar, SnackbarProvider } from "notistack";
import { c as createLibraryStore } from "./store-phvyobMt.esm.js";
import { M as MUIThemeWrapper, c as createDarkTheme, a as createLightTheme } from "./theme-impl-B5ncd0_-.esm.js";
import { a as LanguageProvider } from "./languageContext-BIMozZxS.esm.js";
import { c as PermissionsProvider } from "./page-context-DfhfvGxO.esm.js";
import { i as initializeApiConfig } from "./api-config-GOys-syK.esm.js";
import { a$ as initializeApiBaseUrls, z as extendApiConfigurations } from "./common-B0qL-cCR.esm.js";
import { s as setModuleRoutes } from "./module-routes-config-CCkZEtfg.esm.js";
let globalLastLoadedModules = "";
let globalIsLoading = false;
let globalInitialLoad = false;
const useAppTranslations = () => {
  const [isLoading, setIsLoading] = useState(globalInitialLoad);
  const location = window.location;
  const i18nInstance = getI18n();
  const { user, loading } = useAuth();
  const { t } = useTranslation();
  useEffect(() => {
    const erpModules = modules(t);
    const currentPath = location.pathname.toLowerCase();
    if ((user == null ? void 0 : user.id) && !loading) {
      const matchedModule = erpModules.find(
        (mod) => {
          var _a;
          return mod.link.toLowerCase() === currentPath || ((_a = mod.connectedRoutes) == null ? void 0 : _a.some((route) => currentPath.startsWith(route.toLowerCase())));
        }
      );
      let modulesToLoad = [];
      if (matchedModule == null ? void 0 : matchedModule.translationModule) {
        modulesToLoad = [...matchedModule.translationModule, "common"];
      } else if (!matchedModule && currentPath === "/dashboard") {
        modulesToLoad = ["common"];
      }
      if (modulesToLoad.length > 0) {
        const moduleKey = [...modulesToLoad].sort().join(",");
        if (globalLastLoadedModules === moduleKey || globalIsLoading) {
          if (globalInitialLoad) {
            setIsLoading(false);
            globalInitialLoad = false;
          }
          return;
        }
        globalIsLoading = true;
        globalLastLoadedModules = moduleKey;
        setIsLoading(true);
        loadModuleTranslations(modulesToLoad, i18nInstance).finally(() => {
          globalIsLoading = false;
          setIsLoading(false);
          globalInitialLoad = false;
        });
      } else {
        if (globalInitialLoad) {
          setIsLoading(false);
          globalInitialLoad = false;
        }
      }
    }
  }, [location.pathname, t, user, loading]);
  return { isLoading };
};
const useGenericDataFetcher = (cols, pagination, fetchAction, customeFilter = "", customDeps, showCreatedBy = true, customFields = []) => {
  const { activePage } = usePages();
  const dispatch = useDispatch();
  const location = useLocation();
  const sourceColumns = Array.isArray(cols) ? cols == null ? void 0 : cols.filter((col) => col.visible) : activePage == null ? void 0 : activePage.visible_columns;
  const [trackedPath, setTrackedPath] = useState(null);
  const [trackedColumns, setTrackedColumns] = useState([]);
  useEffect(() => {
    if (trackedPath !== (location == null ? void 0 : location.pathname)) {
      setTrackedPath(location == null ? void 0 : location.pathname);
      setTrackedColumns([]);
    }
  }, [location == null ? void 0 : location.pathname, trackedPath]);
  useEffect(() => {
    if (trackedPath === (location == null ? void 0 : location.pathname) && (sourceColumns == null ? void 0 : sourceColumns.length) > 0) {
      if (JSON.stringify(trackedColumns) !== JSON.stringify(sourceColumns)) {
        setTrackedColumns(sourceColumns);
      }
    }
  }, [location == null ? void 0 : location.pathname, trackedPath, sourceColumns]);
  const getProcessedFilters = useCallback(() => {
    const { filterQueryString } = activePage || {};
    const queryString = (filterQueryString == null ? void 0 : filterQueryString.replaceAll(/[()]/g, "")) || "";
    const extraQueryString = queryString.length ? `&${queryString}` : "";
    let filters = customeFilter;
    if (extraQueryString) {
      filters = filters ? `(${filters}${extraQueryString})` : `(${extraQueryString})`;
    } else if (filters) {
      filters = `(${filters})`;
    }
    return filters || void 0;
  }, [activePage.filterQueryString, customeFilter]);
  const fetchData = useCallback(() => {
    if (!fetchAction) {
      return;
    }
    const { sort = null, search } = activePage;
    if (!trackedColumns || trackedColumns.length === 0) return;
    const filters = getProcessedFilters();
    const visibleColumns = trackedColumns == null ? void 0 : trackedColumns.filter((vc) => vc.visible);
    const selectPayload = (visibleColumns == null ? void 0 : visibleColumns.length) > 0 ? `[${visibleColumns == null ? void 0 : visibleColumns.map(
      (item) => {
        var _a;
        return ((_a = item.accessorKey) == null ? void 0 : _a.includes(".")) ? item.accessorKey.split(".")[0] : item.accessorKey;
      }
    )}${showCreatedBy ? ",created_at,created_by_data" : ""}${(customFields == null ? void 0 : customFields.length) ? `,${customFields == null ? void 0 : customFields.join(",")}` : ""}]` : void 0;
    const payload = {
      skip: (activePage == null ? void 0 : activePage.skip) || (pagination == null ? void 0 : pagination.skip),
      limit: pagination.limit,
      search,
      select: selectPayload,
      ...sort && { order: `${sort.id}:${sort.desc ? -1 : 1}` },
      ...filters && { filters }
    };
    dispatch(fetchAction(payload));
  }, [
    trackedColumns,
    activePage.sort,
    activePage.filterQueryString,
    activePage.search,
    // pagination?.skip intentionally omitted: the Pagination component already
    // mirrors skip into activePage.skip on pageNo change; including pagination.skip
    // here would make fetchData identity change twice per pagination click,
    // triggering the listing useEffect twice and causing duplicate API calls.
    activePage == null ? void 0 : activePage.skip,
    pagination == null ? void 0 : pagination.limit,
    dispatch,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    ...customDeps || []
  ]);
  return fetchData;
};
let globalEnqueueSnackbar = null;
const useSnackbarRef = () => {
  const { enqueueSnackbar: snackbarHook } = useSnackbar();
  globalEnqueueSnackbar = snackbarHook;
};
function apiHelper(res, callBack, enqueueSnackbarOverride) {
  var _a;
  if (((_a = res == null ? void 0 : res.meta) == null ? void 0 : _a.requestStatus) === "rejected") {
    const errorMessage = (() => {
      var _a2, _b, _c, _d;
      try {
        const msg = ((_a2 = res.error) == null ? void 0 : _a2.message) || ((_b = res == null ? void 0 : res.payload) == null ? void 0 : _b.message);
        return msg ? JSON.parse(msg) : null;
      } catch {
        return { message: ((_c = res.error) == null ? void 0 : _c.message) || ((_d = res == null ? void 0 : res.payload) == null ? void 0 : _d.message) || "Something went wrong" };
      }
    })();
    const rawError = errorMessage == null ? void 0 : errorMessage.message;
    let message = "Something went wrong";
    if (typeof rawError === "string") {
      message = rawError.replace("Error:", "").trim();
    } else if (rawError && typeof rawError === "object") {
      message = rawError.message || JSON.stringify(rawError);
    } else if (rawError) {
      message = String(rawError);
    }
    const snackbar = typeof enqueueSnackbarOverride === "function" ? enqueueSnackbarOverride : globalEnqueueSnackbar || enqueueSnackbar;
    if (typeof snackbar === "function") {
      snackbar(message, { variant: "error" });
    }
    return;
  }
  if (callBack) {
    if (typeof callBack === "function") {
      try {
        callBack();
      } catch (err) {
        console.error("[apiHelper] callBack threw an error:", err);
      }
    } else {
      console.warn("[apiHelper] Provided callBack is not a function:", typeof callBack);
    }
  }
}
const SnackbarRefTracker = () => {
  useSnackbarRef();
  return null;
};
const ERPUIContext = createContext({
  useRedux: false,
  themeMode: "light",
  direction: "ltr"
});
const useERPUI = () => useContext(ERPUIContext);
const ERPUIProvider = ({
  children,
  // Redux props
  useRedux = false,
  reduxStore,
  apiClient,
  additionalReducers = {},
  // Theme props
  theme: customTheme,
  themeMode = "light",
  primaryColor,
  direction = "ltr",
  // Context providers configuration
  enableAuth = true,
  enableLanguage = true,
  enablePages = true,
  enablePermissions = true,
  enableRouter = false,
  // Default false since consuming app usually provides router
  enableSnackbar = true,
  // Other props
  enableCssBaseline = true,
  snackbarConfig = {
    maxSnack: 3,
    anchorOrigin: { vertical: "top", horizontal: "right" },
    autoHideDuration: 5e3
  },
  // API configuration
  apiConfig: providedApiConfig,
  additionalApiConfigurations,
  moduleRoutes,
  routeToColumnsMap,
  routeToResourceMap,
  publicRoutes = []
  // Default empty array for public routes in AuthProvider 
}) => {
  console.log("additionalApiConfigurations...........", additionalApiConfigurations);
  const isInitialized = React__default.useRef(false);
  if (providedApiConfig && !isInitialized.current) {
    try {
      initializeApiConfig(providedApiConfig);
      initializeApiBaseUrls();
      if (additionalApiConfigurations) {
        extendApiConfigurations(additionalApiConfigurations);
      }
      if (moduleRoutes) {
        setModuleRoutes(moduleRoutes);
      }
      isInitialized.current = true;
    } catch (error) {
      console.error("Failed to initialize API configuration:", error);
    }
  }
  const store = React__default.useMemo(() => {
    if (!useRedux) return null;
    if (reduxStore) {
      return reduxStore;
    }
    return createLibraryStore(additionalReducers, apiClient);
  }, [useRedux, reduxStore, additionalReducers, apiClient]);
  const theme = React__default.useMemo(() => {
    if (customTheme) {
      return customTheme;
    }
    const themeCreator = themeMode === "dark" ? createDarkTheme : createLightTheme;
    const { theme: generatedTheme } = themeCreator(primaryColor, direction);
    return generatedTheme;
  }, [customTheme, themeMode, primaryColor, direction]);
  const contextValue = {
    useRedux,
    apiClient,
    theme,
    themeMode,
    direction,
    primaryColor
  };
  let content = /* @__PURE__ */ jsxRuntimeExports.jsx(ERPUIContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(MUIThemeWrapper, { theme, enableCssBaseline, children }) });
  if (enableSnackbar) {
    content = /* @__PURE__ */ jsxRuntimeExports.jsxs(SnackbarProvider, { ...snackbarConfig, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(SnackbarRefTracker, {}),
      content
    ] });
  }
  if (enablePermissions) {
    content = /* @__PURE__ */ jsxRuntimeExports.jsx(PermissionsProvider, { children: content });
  }
  if (enableLanguage) {
    content = /* @__PURE__ */ jsxRuntimeExports.jsx(LanguageProvider, { children: content });
  }
  if (enableAuth) {
    content = /* @__PURE__ */ jsxRuntimeExports.jsx(AuthProvider, { publicRoutes, children: content });
  }
  if (enableRouter) {
    content = /* @__PURE__ */ jsxRuntimeExports.jsx(BrowserRouter, { children: content });
  }
  if (useRedux && store) {
    content = /* @__PURE__ */ jsxRuntimeExports.jsx(Provider, { store, children: content });
  }
  return content;
};
export {
  ERPUIProvider as E,
  apiHelper as a,
  useAppTranslations as b,
  useGenericDataFetcher as c,
  useSnackbarRef as d,
  useERPUI as u
};
//# sourceMappingURL=ERPUIProvider-BAD1kSyl.esm.js.map
