"use strict";
const React = require("react");
const reactI18next = require("react-i18next");
const translations = require("./translations-QALR4VUa.js");
const modules = require("./modules-BKRTgB3s.js");
const useAuth = require("./useAuth-vPRkzGjO.js");
const reactRedux = require("react-redux");
const useAccountSetting = require("./useAccountSetting-C2ZXqmQw.js");
const reactRouterDom = require("react-router-dom");
const jsxRuntime = require("./jsx-runtime-B6vEU3CM.js");
const notistack = require("notistack");
const store = require("./store-C7nHRIec.js");
const themeImpl = require("./theme-impl-BgGLJiHC.js");
const languageContext = require("./languageContext-pgLo21vX.js");
const pageContext = require("./page-context-PMwS3EGo.js");
const apiConfig = require("./api-config-DXwDMFn-.js");
const common = require("./common-B47boGYI.js");
const moduleRoutesConfig = require("./module-routes-config-B8IucBuj.js");
let globalLastLoadedModules = "";
let globalIsLoading = false;
let globalInitialLoad = false;
const useAppTranslations = () => {
  const [isLoading, setIsLoading] = React.useState(globalInitialLoad);
  const location = window.location;
  const i18nInstance = reactI18next.getI18n();
  const { user, loading } = useAuth.useAuth();
  const { t } = reactI18next.useTranslation();
  React.useEffect(() => {
    const erpModules = modules.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);
        translations.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 } = useAccountSetting.usePages();
  const dispatch = reactRedux.useDispatch();
  const location = reactRouterDom.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] = React.useState(null);
  const [trackedColumns, setTrackedColumns] = React.useState([]);
  React.useEffect(() => {
    if (trackedPath !== (location == null ? void 0 : location.pathname)) {
      setTrackedPath(location == null ? void 0 : location.pathname);
      setTrackedColumns([]);
    }
  }, [location == null ? void 0 : location.pathname, trackedPath]);
  React.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 = React.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 = React.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 } = notistack.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 || notistack.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 = React.createContext({
  useRedux: false,
  themeMode: "light",
  direction: "ltr"
});
const useERPUI = () => React.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.useRef(false);
  if (providedApiConfig && !isInitialized.current) {
    try {
      apiConfig.initializeApiConfig(providedApiConfig);
      common.initializeApiBaseUrls();
      if (additionalApiConfigurations) {
        common.extendApiConfigurations(additionalApiConfigurations);
      }
      if (moduleRoutes) {
        moduleRoutesConfig.setModuleRoutes(moduleRoutes);
      }
      isInitialized.current = true;
    } catch (error) {
      console.error("Failed to initialize API configuration:", error);
    }
  }
  const store$1 = React.useMemo(() => {
    if (!useRedux) return null;
    if (reduxStore) {
      return reduxStore;
    }
    return store.createLibraryStore(additionalReducers, apiClient);
  }, [useRedux, reduxStore, additionalReducers, apiClient]);
  const theme = React.useMemo(() => {
    if (customTheme) {
      return customTheme;
    }
    const themeCreator = themeMode === "dark" ? themeImpl.createDarkTheme : themeImpl.createLightTheme;
    const { theme: generatedTheme } = themeCreator(primaryColor, direction);
    return generatedTheme;
  }, [customTheme, themeMode, primaryColor, direction]);
  const contextValue = {
    useRedux,
    apiClient,
    theme,
    themeMode,
    direction,
    primaryColor
  };
  let content = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(ERPUIContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(themeImpl.MUIThemeWrapper, { theme, enableCssBaseline, children }) });
  if (enableSnackbar) {
    content = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(notistack.SnackbarProvider, { ...snackbarConfig, children: [
      /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(SnackbarRefTracker, {}),
      content
    ] });
  }
  if (enablePermissions) {
    content = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(pageContext.PermissionsProvider, { children: content });
  }
  if (enableLanguage) {
    content = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(languageContext.LanguageProvider, { children: content });
  }
  if (enableAuth) {
    content = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(useAuth.AuthProvider, { publicRoutes, children: content });
  }
  if (enableRouter) {
    content = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(reactRouterDom.BrowserRouter, { children: content });
  }
  if (useRedux && store$1) {
    content = /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(reactRedux.Provider, { store: store$1, children: content });
  }
  return content;
};
exports.ERPUIProvider = ERPUIProvider;
exports.apiHelper = apiHelper;
exports.useAppTranslations = useAppTranslations;
exports.useERPUI = useERPUI;
exports.useGenericDataFetcher = useGenericDataFetcher;
exports.useSnackbarRef = useSnackbarRef;
//# sourceMappingURL=ERPUIProvider-DR08Tj5p.js.map
