"use strict";
const React = require("react");
const jsxRuntime = require("./jsx-runtime-B6vEU3CM.js");
const api = require("./api-BygscvSz.js");
const apiConfig = require("./api-config-DXwDMFn-.js");
const reactRouterDom = require("react-router-dom");
const pathname_rental = require("./pathname.rental-C9fm1WTq.js");
const common = require("./common-B47boGYI.js");
const notistack = require("notistack");
const socket_ioClient = require("socket.io-client");
const material = require("@mui/material");
const identifier = require("./identifier-B8P9ZGxG.js");
const _commonjsHelpers = require("./_commonjsHelpers-Cq6wktVC.js");
const notification = require("./notification-lAbbtOBF.js");
const images = require("./images-CY-_BlWh.js");
;/* empty css                          */
function _interopNamespaceDefault(e) {
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
  if (e) {
    for (const k in e) {
      if (k !== "default") {
        const d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: () => e[k]
        });
      }
    }
  }
  n.default = e;
  return Object.freeze(n);
}
const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
const convertRoutesToUseIdParams = (routes) => {
  const updatedRoutes = { ...routes };
  Object.keys(updatedRoutes).forEach((key) => {
    if (key.startsWith("VIEW_") || key.startsWith("EDIT_") || key.startsWith("DETAIL_") || key.includes("_VIEW_") || key.includes("_EDIT_") || key.includes("_DETAIL_")) {
      if (!updatedRoutes[key].includes(":")) {
        updatedRoutes[key] = `${updatedRoutes[key]}/:id`;
      }
    }
  });
  return updatedRoutes;
};
const generateRouteWithId = (basePath, id) => {
  if (id && typeof id === "object") {
    Object.entries(id).map(([key, value]) => {
      basePath = basePath.replace(`:${key}`, value == null ? void 0 : value.toString());
    });
  } else if (basePath.includes(":id")) {
    return basePath.replace(":id", id == null ? void 0 : id.toString());
  }
  return `${basePath}`;
};
const updatePathnameWithIdParams = (pathnameObject) => {
  return convertRoutesToUseIdParams(pathnameObject);
};
const navigateToRouteWithId = (navigate, route, id, state) => {
  const path = generateRouteWithId(route, id);
  navigate(path, { state });
};
var Close = {};
var createSvgIcon = {};
function createChainedFunction(...funcs) {
  return funcs.reduce((acc, func) => {
    if (func == null) {
      return acc;
    }
    return function chainedFunction(...args) {
      acc.apply(this, args);
      func.apply(this, args);
    };
  }, () => {
  });
}
function debounce(func, wait = 166) {
  let timeout;
  function debounced(...args) {
    const later = () => {
      func.apply(this, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  }
  debounced.clear = () => {
    clearTimeout(timeout);
  };
  return debounced;
}
function deprecatedPropType(validator, reason) {
  if (process.env.NODE_ENV === "production") {
    return () => null;
  }
  return (props, propName, componentName, location, propFullName) => {
    const componentNameSafe = componentName || "<<anonymous>>";
    const propFullNameSafe = propFullName || propName;
    if (typeof props[propName] !== "undefined") {
      return new Error(`The ${location} \`${propFullNameSafe}\` of \`${componentNameSafe}\` is deprecated. ${reason}`);
    }
    return null;
  };
}
function isMuiElement(element, muiNames) {
  var _muiName, _element$type;
  return /* @__PURE__ */ React__namespace.isValidElement(element) && muiNames.indexOf(
    // For server components `muiName` is avaialble in element.type._payload.value.muiName
    // relevant info - https://github.com/facebook/react/blob/2807d781a08db8e9873687fccc25c0f12b4fb3d4/packages/react/src/ReactLazy.js#L45
    // eslint-disable-next-line no-underscore-dangle
    (_muiName = element.type.muiName) != null ? _muiName : (_element$type = element.type) == null || (_element$type = _element$type._payload) == null || (_element$type = _element$type.value) == null ? void 0 : _element$type.muiName
  ) !== -1;
}
function ownerDocument(node) {
  return node && node.ownerDocument || document;
}
function ownerWindow(node) {
  const doc = ownerDocument(node);
  return doc.defaultView || window;
}
function requirePropFactory(componentNameInError, Component) {
  if (process.env.NODE_ENV === "production") {
    return () => null;
  }
  const prevPropTypes = Component ? identifier._extends({}, Component.propTypes) : null;
  const requireProp = (requiredProp) => (props, propName, componentName, location, propFullName, ...args) => {
    const propFullNameSafe = propFullName || propName;
    const defaultTypeChecker = prevPropTypes == null ? void 0 : prevPropTypes[propFullNameSafe];
    if (defaultTypeChecker) {
      const typeCheckerResult = defaultTypeChecker(props, propName, componentName, location, propFullName, ...args);
      if (typeCheckerResult) {
        return typeCheckerResult;
      }
    }
    if (typeof props[propName] !== "undefined" && !props[requiredProp]) {
      return new Error(`The prop \`${propFullNameSafe}\` of \`${componentNameInError}\` can only be used together with the \`${requiredProp}\` prop.`);
    }
    return null;
  };
  return requireProp;
}
function setRef(ref, value) {
  if (typeof ref === "function") {
    ref(value);
  } else if (ref) {
    ref.current = value;
  }
}
const useEnhancedEffect = typeof window !== "undefined" ? React__namespace.useLayoutEffect : React__namespace.useEffect;
let globalId = 0;
function useGlobalId(idOverride) {
  const [defaultId, setDefaultId] = React__namespace.useState(idOverride);
  const id = idOverride || defaultId;
  React__namespace.useEffect(() => {
    if (defaultId == null) {
      globalId += 1;
      setDefaultId(`mui-${globalId}`);
    }
  }, [defaultId]);
  return id;
}
const maybeReactUseId = React__namespace["useId".toString()];
function useId(idOverride) {
  if (maybeReactUseId !== void 0) {
    const reactId = maybeReactUseId();
    return idOverride != null ? idOverride : reactId;
  }
  return useGlobalId(idOverride);
}
function unsupportedProp(props, propName, componentName, location, propFullName) {
  if (process.env.NODE_ENV === "production") {
    return null;
  }
  const propFullNameSafe = propFullName || propName;
  if (typeof props[propName] !== "undefined") {
    return new Error(`The prop \`${propFullNameSafe}\` is not supported. Please remove it.`);
  }
  return null;
}
function useControlled({
  controlled,
  default: defaultProp,
  name,
  state = "value"
}) {
  const {
    current: isControlled
  } = React__namespace.useRef(controlled !== void 0);
  const [valueState, setValue] = React__namespace.useState(defaultProp);
  const value = isControlled ? controlled : valueState;
  if (process.env.NODE_ENV !== "production") {
    React__namespace.useEffect(() => {
      if (isControlled !== (controlled !== void 0)) {
        console.error([`MUI: A component is changing the ${isControlled ? "" : "un"}controlled ${state} state of ${name} to be ${isControlled ? "un" : ""}controlled.`, "Elements should not switch from uncontrolled to controlled (or vice versa).", `Decide between using a controlled or uncontrolled ${name} element for the lifetime of the component.`, "The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.", "More info: https://fb.me/react-controlled-components"].join("\n"));
      }
    }, [state, name, controlled]);
    const {
      current: defaultValue
    } = React__namespace.useRef(defaultProp);
    React__namespace.useEffect(() => {
      if (!isControlled && !Object.is(defaultValue, defaultProp)) {
        console.error([`MUI: A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. To suppress this warning opt to use a controlled ${name}.`].join("\n"));
      }
    }, [JSON.stringify(defaultProp)]);
  }
  const setValueIfUncontrolled = React__namespace.useCallback((newValue) => {
    if (!isControlled) {
      setValue(newValue);
    }
  }, []);
  return [value, setValueIfUncontrolled];
}
function useEventCallback(fn) {
  const ref = React__namespace.useRef(fn);
  useEnhancedEffect(() => {
    ref.current = fn;
  });
  return React__namespace.useRef((...args) => (
    // @ts-expect-error hide `this`
    (0, ref.current)(...args)
  )).current;
}
function useForkRef(...refs) {
  return React__namespace.useMemo(() => {
    if (refs.every((ref) => ref == null)) {
      return null;
    }
    return (instance) => {
      refs.forEach((ref) => {
        setRef(ref, instance);
      });
    };
  }, refs);
}
const UNINITIALIZED = {};
function useLazyRef(init, initArg) {
  const ref = React__namespace.useRef(UNINITIALIZED);
  if (ref.current === UNINITIALIZED) {
    ref.current = init(initArg);
  }
  return ref;
}
const EMPTY = [];
function useOnMount(fn) {
  React__namespace.useEffect(fn, EMPTY);
}
class Timeout {
  constructor() {
    this.currentId = null;
    this.clear = () => {
      if (this.currentId !== null) {
        clearTimeout(this.currentId);
        this.currentId = null;
      }
    };
    this.disposeEffect = () => {
      return this.clear;
    };
  }
  static create() {
    return new Timeout();
  }
  /**
   * Executes `fn` after `delay`, clearing any previously scheduled call.
   */
  start(delay, fn) {
    this.clear();
    this.currentId = setTimeout(() => {
      this.currentId = null;
      fn();
    }, delay);
  }
}
function useTimeout() {
  const timeout = useLazyRef(Timeout.create).current;
  useOnMount(timeout.disposeEffect);
  return timeout;
}
let hadKeyboardEvent = true;
let hadFocusVisibleRecently = false;
const hadFocusVisibleRecentlyTimeout = new Timeout();
const inputTypesWhitelist = {
  text: true,
  search: true,
  url: true,
  tel: true,
  email: true,
  password: true,
  number: true,
  date: true,
  month: true,
  week: true,
  time: true,
  datetime: true,
  "datetime-local": true
};
function focusTriggersKeyboardModality(node) {
  const {
    type,
    tagName
  } = node;
  if (tagName === "INPUT" && inputTypesWhitelist[type] && !node.readOnly) {
    return true;
  }
  if (tagName === "TEXTAREA" && !node.readOnly) {
    return true;
  }
  if (node.isContentEditable) {
    return true;
  }
  return false;
}
function handleKeyDown(event) {
  if (event.metaKey || event.altKey || event.ctrlKey) {
    return;
  }
  hadKeyboardEvent = true;
}
function handlePointerDown() {
  hadKeyboardEvent = false;
}
function handleVisibilityChange() {
  if (this.visibilityState === "hidden") {
    if (hadFocusVisibleRecently) {
      hadKeyboardEvent = true;
    }
  }
}
function prepare(doc) {
  doc.addEventListener("keydown", handleKeyDown, true);
  doc.addEventListener("mousedown", handlePointerDown, true);
  doc.addEventListener("pointerdown", handlePointerDown, true);
  doc.addEventListener("touchstart", handlePointerDown, true);
  doc.addEventListener("visibilitychange", handleVisibilityChange, true);
}
function isFocusVisible(event) {
  const {
    target
  } = event;
  try {
    return target.matches(":focus-visible");
  } catch (error) {
  }
  return hadKeyboardEvent || focusTriggersKeyboardModality(target);
}
function useIsFocusVisible() {
  const ref = React__namespace.useCallback((node) => {
    if (node != null) {
      prepare(node.ownerDocument);
    }
  }, []);
  const isFocusVisibleRef = React__namespace.useRef(false);
  function handleBlurVisible() {
    if (isFocusVisibleRef.current) {
      hadFocusVisibleRecently = true;
      hadFocusVisibleRecentlyTimeout.start(100, () => {
        hadFocusVisibleRecently = false;
      });
      isFocusVisibleRef.current = false;
      return true;
    }
    return false;
  }
  function handleFocusVisible(event) {
    if (isFocusVisible(event)) {
      isFocusVisibleRef.current = true;
      return true;
    }
    return false;
  }
  return {
    isFocusVisibleRef,
    onFocus: handleFocusVisible,
    onBlur: handleBlurVisible,
    ref
  };
}
const unstable_ClassNameGenerator = {
  configure: (generator) => {
    if (process.env.NODE_ENV !== "production") {
      console.warn(["MUI: `ClassNameGenerator` import from `@mui/material/utils` is outdated and might cause unexpected issues.", "", "You should use `import { unstable_ClassNameGenerator } from '@mui/material/className'` instead", "", "The detail of the issue: https://github.com/mui/material-ui/issues/30011#issuecomment-1024993401", "", "The updated documentation: https://mui.com/guides/classname-generator/"].join("\n"));
    }
    identifier.ClassNameGenerator.configure(generator);
  }
};
const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  capitalize: identifier.capitalize,
  createChainedFunction,
  createSvgIcon: notification.createSvgIcon,
  debounce,
  deprecatedPropType,
  isMuiElement,
  ownerDocument,
  ownerWindow,
  requirePropFactory,
  setRef,
  unstable_ClassNameGenerator,
  unstable_useEnhancedEffect: useEnhancedEffect,
  unstable_useId: useId,
  unsupportedProp,
  useControlled,
  useEventCallback,
  useForkRef,
  useIsFocusVisible
}, Symbol.toStringTag, { value: "Module" }));
const require$$0 = /* @__PURE__ */ _commonjsHelpers.getAugmentedNamespace(utils);
var hasRequiredCreateSvgIcon;
function requireCreateSvgIcon() {
  if (hasRequiredCreateSvgIcon) return createSvgIcon;
  hasRequiredCreateSvgIcon = 1;
  (function(exports2) {
    "use client";
    Object.defineProperty(exports2, "__esModule", {
      value: true
    });
    Object.defineProperty(exports2, "default", {
      enumerable: true,
      get: function() {
        return _utils.createSvgIcon;
      }
    });
    var _utils = require$$0;
  })(createSvgIcon);
  return createSvgIcon;
}
var _interopRequireDefault = identifier.interopRequireDefaultExports;
Object.defineProperty(Close, "__esModule", {
  value: true
});
exports.default_1 = Close.default = void 0;
var _createSvgIcon = _interopRequireDefault(requireCreateSvgIcon());
var _jsxRuntime = jsxRuntime.jsxRuntimeExports;
exports.default_1 = Close.default = (0, _createSvgIcon.default)(/* @__PURE__ */ (0, _jsxRuntime.jsx)("path", {
  d: "M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
}), "Close");
const StyledTypography = material.styled(material.Typography)(
  ({ theme: { palette }, color }) => {
    var _a;
    return {
      color: color || ((_a = palette.theme) == null ? void 0 : _a.primary[800])
    };
  }
);
function Typography(props) {
  const {
    children,
    type = "h5",
    weight = "normal",
    className,
    ...rest
  } = props;
  return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(StyledTypography, { className: `${type} ${weight} ${className}`, ...rest, children });
}
const mainModuleIcons = {
  rbac: images.images.user,
  document: images.images.document,
  "accounts-and-finance": images.images.accounting,
  inventory: images.images.inventory,
  manufacturing: images.images.manufacturing,
  sales: images.images.crm,
  rental: images.images.rental,
  user: images.images.user,
  purchase: images.images.procurement,
  hrms: images.images.hrms
};
const mainModuleBgColors = {
  rbac: "#F3E5F5",
  document: "#FFF8E1",
  "accounts-and-finance": "#E8F5E8",
  inventory: "#E3F2FD",
  manufacturing: "#FFF3E0",
  sales: "#F3E5F5",
  rental: "#E8F5E8",
  user: "#F3E5F5",
  purchase: "#FCE4EC",
  hrms: "#fcfcfc"
};
const CustomSnackbar = React.forwardRef(
  ({ message, variant = "default", linkUrl, snackbarKey, data }, ref) => {
    const { closeSnackbar } = notistack.useSnackbar();
    const navigate = reactRouterDom.useNavigate();
    const backgroundColorMap = {
      success: "#f0fdf4",
      error: "#fef2f2",
      warning: "#fff7ed",
      info: "#eff6ff",
      default: "#fff"
    };
    const textColorMap = {
      success: "#166534",
      error: "#991b1b",
      warning: "#92400e",
      info: "#1e40af",
      default: "#27272a"
    };
    const handleClick = () => {
      if (linkUrl) navigate(linkUrl);
      closeSnackbar(snackbarKey);
    };
    const handleCloseClick = (e) => {
      e.stopPropagation();
      closeSnackbar(snackbarKey);
    };
    return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
      notistack.SnackbarContent,
      {
        ref,
        style: {
          backgroundColor: backgroundColorMap[variant],
          color: textColorMap[variant]
        },
        className: "SnackBar",
        onClick: handleClick,
        children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(material.Box, { display: "flex", alignItems: "center", p: 2, position: "relative", gap: 2, width: "100%", children: [
          (mainModuleIcons == null ? void 0 : mainModuleIcons[data.module]) ? /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(material.Avatar, { sx: {
            width: 45,
            height: 45,
            fontSize: "0.875rem",
            bgcolor: mainModuleBgColors[data.module] || "primary.main",
            color: "white",
            borderRadius: "8px",
            "& img": {
              width: "35px",
              height: "35px",
              objectFit: "contain"
            }
          }, src: mainModuleIcons == null ? void 0 : mainModuleIcons[data.module] }) : /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
            notification.Notification,
            {
              style: {
                color: textColorMap[variant],
                marginTop: 2
              }
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(material.Box, { display: "flex", alignItems: "center", width: "100%", children: [
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsxs(material.Box, { flex: "1", children: [
              /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(Typography, { type: "h5", color: "inherit", weight: "bold", children: "New Notification" }),
              /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(Typography, { type: "s3", mt: 0.5, color: "inherit", children: message })
            ] }),
            /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(
              material.IconButton,
              {
                size: "small",
                onClick: handleCloseClick,
                children: /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(exports.default_1, { fontSize: "small" })
              }
            )
          ] })
        ] })
      }
    );
  }
);
const defaultProvider = {
  user: null,
  loading: true,
  authToken: "",
  setUser: () => null,
  setLoading: () => Boolean,
  login: () => Promise.resolve(),
  logout: () => Promise.resolve(),
  forgotPassword: () => Promise.resolve(),
  resetPassword: () => Promise.resolve(),
  changePassword: () => Promise.resolve(),
  changeUserPassword: () => Promise.resolve()
};
const AuthContext = React.createContext(defaultProvider);
const AuthProvider = ({ children, publicRoutes = [] }) => {
  const [user, setUser] = React.useState(defaultProvider.user);
  const [authToken, setAuthToken] = React.useState("");
  const [loading, setLoading] = React.useState(defaultProvider.loading);
  const socketRef = React.useRef(null);
  const navigate = reactRouterDom.useNavigate();
  const location = reactRouterDom.useLocation();
  const isJsonParse = (string) => {
    if (!string) return false;
    try {
      return JSON.parse(string);
    } catch (error) {
      return false;
    }
  };
  const getNotificationUrl = (data) => {
    var _a;
    const { moduleName = "", moduleId = "", notificationData = {} } = data;
    const key = moduleName.toLowerCase();
    const routeMap = {
      "sales invoice": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_SALES_INVOICES), moduleId.toString()),
      "asset transfers": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_ASSET_TRANSFER), moduleId.toString()),
      "budgets": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_BUDGET), moduleId.toString()),
      "cash expense": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_CASH_EXPENSE), moduleId.toString()),
      "credit notes": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_CREDIT_NOTE), moduleId.toString()),
      "debit notes": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_DEBIT_NOTE), moduleId.toString()),
      "expense reimbursement": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_EXPENSE_REIMBURSEMENT), moduleId.toString()),
      "journal entries": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_JOURNAL_ENTRY), moduleId.toString()),
      "payment entries": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_PAYMENT_ENTRY), moduleId.toString()),
      "purchase invoice": () => generateRouteWithId(pathname_rental.PathnameGenerator$5(pathname_rental.PathnameAccounting.VIEW_PURCHASE_INVOICE), moduleId.toString()),
      "stock transfer": () => generateRouteWithId(pathname_rental.PathnameGenerator$4(pathname_rental.PathnameInventory.VIEW_STOCK_TRANSFER), moduleId.toString()),
      "bills of materials": () => generateRouteWithId(pathname_rental.PathnameGenerator$3(pathname_rental.PathnameManufacturing.VIEW_BILL_OF_MATERIAL), moduleId.toString()),
      "purchase agreement": () => generateRouteWithId(pathname_rental.PathnameGenerator$1(pathname_rental.PathnamePurchase.VIEW_PURCHASE_AGREEMENT), moduleId.toString()),
      "purchase orders": () => {
        var _a2;
        return generateRouteWithId(((_a2 = notificationData == null ? void 0 : notificationData.data) == null ? void 0 : _a2.is_rental) == 1 ? pathname_rental.ROUTES.VIEW : pathname_rental.PathnameGenerator$1(pathname_rental.PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString());
      },
      "purchase request": () => generateRouteWithId(pathname_rental.PathnameGenerator$1(pathname_rental.PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString()),
      "vra": () => generateRouteWithId(pathname_rental.PathnameGenerator$1(pathname_rental.PathnamePurchase.VIEW_VENDOR_RETURNS), moduleId.toString()),
      "sl customer returns": () => generateRouteWithId(pathname_rental.PathnameGenerator$2(pathname_rental.PathnameCrm.VIEW_CUSTOMER_RETURNS), moduleId.toString()),
      "sales order": () => generateRouteWithId(pathname_rental.PathnameGenerator$2(pathname_rental.PathnameCrm.VIEW_SALES_ORDER), moduleId.toString()),
      "rental order": () => generateRouteWithId(pathname_rental.PathnameGenerator(pathname_rental.PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),
      "replacement order": () => generateRouteWithId(pathname_rental.PathnameGenerator(pathname_rental.PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),
      "rental agreement": () => generateRouteWithId(pathname_rental.PathnameGenerator(pathname_rental.PathnameRental.VIEW_AGREEMENT), moduleId.toString()),
      "cross hire order": () => generateRouteWithId(pathname_rental.PathnameGenerator(pathname_rental.PathnameRental.VIEW_CROSS_HIRE_ORDER), moduleId.toString()),
      "cross hire request": () => generateRouteWithId(pathname_rental.PathnameGenerator(pathname_rental.PathnameRental.VIEW_CROSS_HIRE_REQUEST), moduleId.toString())
    };
    return ((_a = routeMap[key]) == null ? void 0 : _a.call(routeMap)) || "/dashboard";
  };
  React.useEffect(() => {
    setLoading(true);
    const storedToken = window.localStorage.getItem(apiConfig.auth.storageTokenKeyName);
    const storedUser = isJsonParse(window.localStorage.getItem(apiConfig.auth.storageUserKeyName)) ?? null;
    const allPublicRoutes = [pathname_rental.Pathname.LOGIN, pathname_rental.Pathname.FORGOT_PASSWORD, pathname_rental.Pathname.RESET_PASSWORD, pathname_rental.Pathname.CHANGE_PASSWORD, ...publicRoutes];
    const currentPath = window.location.pathname;
    if (!storedToken && !storedUser) {
      console.log("allPublicRoutes..", allPublicRoutes, "currentPath..", currentPath);
      if (Boolean(!reactRouterDom.matchRoutes(allPublicRoutes.map((route) => ({ path: route })), location))) {
        navigate(pathname_rental.Pathname.LOGIN);
      }
      setLoading(false);
    } else {
      setUser(storedUser);
      setAuthToken(storedToken || "");
      setLoading(false);
    }
  }, []);
  React.useEffect(() => {
    var _a;
    if (!authToken) {
      if (socketRef.current) {
        (_a = socketRef.current) == null ? void 0 : _a.disconnect();
        socketRef.current = null;
      }
      console.warn("No auth token found, not connecting to socket.");
      return;
    }
    const config = apiConfig.getApiConfig();
    const socket = socket_ioClient.io(config.socketBaseUrl, {
      transports: ["websocket"],
      auth: { token: authToken },
      path: "/socket.io/"
    });
    socketRef.current = socket;
    socket.on("connect", () => {
      console.log("Socket connected:", socket.id);
      socket.onAny((event, ...args) => {
        console.log(`Received event: ${event}`, args);
      });
    });
    socket.on("notification", (data) => {
      const { message, notificationData } = data || {};
      let notificationContent = message;
      const url = getNotificationUrl(data);
      if (notificationData) {
        const { notification_type } = notificationData;
        switch (notification_type) {
          case "addApprovers": {
            notificationContent = message;
            break;
          }
          case "change_approval_status": {
            notificationContent = message;
            break;
          }
          default: {
            notificationContent = message;
            break;
          }
        }
      }
      notistack.enqueueSnackbar(String(message), {
        variant: "default",
        anchorOrigin: { vertical: "top", horizontal: "center" },
        autoHideDuration: 5e3,
        content: (key) => /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(CustomSnackbar, { snackbarKey: key, message: notificationContent, data: notificationData, variant: "default", linkUrl: url })
      });
    });
    socket.on("sales_invoice_viewed", (data) => {
      console.log("Invoice viewed:", data.invoiceId, "by user:", data.userId);
    });
    socket.on("error", (errMsg) => {
      notistack.enqueueSnackbar(`Socket error: ${errMsg}`, { variant: "error" });
      console.error("Socket error:", errMsg);
    });
    return () => {
      if (socketRef.current) {
        socketRef.current.disconnect();
        socketRef.current = null;
      }
    };
  }, [authToken]);
  const fetchRolesByUserId = async (userId, token) => {
    var _a;
    const response = await api.getV1RoleUserId({ id: userId, ...common.getToken(token) });
    const perm = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.role) || [];
    return JSON.stringify(perm);
  };
  const handleLogin = async (params, callback, shoudRedirect = true, redirectPath = pathname_rental.Pathname.DASHBOARD) => {
    var _a;
    setLoading(true);
    const storedToken = window.localStorage.getItem(apiConfig.auth.storageTokenKeyName);
    if (storedToken && user) {
      return navigate(pathname_rental.Pathname.DASHBOARD);
    }
    try {
      const loginUser = await api.postV1AuthLogin({ ...params, ...common.getToken() });
      if (loginUser.success) {
        const data = ((_a = loginUser == null ? void 0 : loginUser.data) == null ? void 0 : _a.login) || null;
        if (data) {
          const userData = {
            ...data,
            full_name: `${data.first_name} ${data.last_name}`
          };
          const rolePermission = await fetchRolesByUserId(userData.id, data.token);
          globalThis.localStorage.setItem(apiConfig.auth.storageTokenKeyName, data.token);
          window.localStorage.setItem(apiConfig.auth.storageUserKeyName, JSON.stringify(userData));
          window.localStorage.setItem(apiConfig.auth.storageRolePermissionKeyName, rolePermission);
          window.dispatchEvent(new Event("role-permission-changed"));
          setUser(userData);
          setAuthToken(data.token);
          setTimeout(() => {
            shoudRedirect && navigate(redirectPath);
            setLoading(false);
            delete data.token;
          }, 1e3);
        }
      }
    } catch (error) {
      let message = "Something went wrong";
      if (error instanceof Error) {
        message = isJsonParse(error.message).message || error.message;
      }
      setLoading(false);
      callback(message);
    }
  };
  const handleLogout = async () => {
    window.localStorage.removeItem(apiConfig.auth.storageTokenKeyName);
    window.localStorage.removeItem(apiConfig.auth.storageUserKeyName);
    window.localStorage.removeItem(apiConfig.auth.storageRolePermissionKeyName);
    window.dispatchEvent(new Event("role-permission-changed"));
    setUser(null);
    setAuthToken("");
    navigate(pathname_rental.Pathname.LOGIN);
  };
  const handleForgotPassword = async (params, callback) => {
    try {
      await api.postV1AuthForgotPassword({ ...params, ...common.getToken() });
      callback(true, "Reset Link sent to your email");
    } catch (error) {
      let message = "Something went wrong";
      if (error instanceof Error) {
        message = isJsonParse(error.message).message || error.message;
      }
      callback(false, message);
    }
  };
  const handleResetPassword = async (params, callback) => {
    try {
      const response = await api.postV1AuthResetPassword({ ...params, ...common.getToken() });
      callback(response);
    } catch (error) {
      let message = "Something went wrong";
      console.log("Error ", error);
      if (error instanceof Error) {
        message = isJsonParse(error.message).message || error.message;
        callback(message);
      }
    }
  };
  const handleChangePassword = async (params, callback) => {
    try {
      await api.postV1AuthChangePassword({ ...params, ...common.getToken() });
      callback(null);
    } catch (error) {
      let message = "Something went wrong";
      console.log("Error ", error);
      if (error instanceof Error) {
        message = isJsonParse(error.message).message || error.message;
        callback(message);
      }
    }
    callback("reset");
  };
  const handleChangeUserPassword = async (params, callback) => {
    try {
      await api.postV1AuthChangeUserPassword({ ...params, ...common.getToken() });
      callback("Password Changed Successfully", true);
    } catch (error) {
      let message = "Something went wrong";
      if (error instanceof Error) {
        message = isJsonParse(error.message).message || error.message;
        callback(message, false);
      }
    }
  };
  const handleChangeUserPasswordByAdmin = async (params, callback) => {
    try {
      await api.postV1AuthChangeUserPasswordByAdmin({ ...params, ...common.getToken() });
      callback("Password Changed Successfully", true);
    } catch (error) {
      let message = "Something went wrong";
      if (error instanceof Error) {
        message = isJsonParse(error.message).message || error.message;
        callback(message, false);
      }
    }
  };
  const values = {
    user,
    authToken,
    loading,
    setUser,
    setLoading,
    login: handleLogin,
    logout: handleLogout,
    forgotPassword: handleForgotPassword,
    resetPassword: handleResetPassword,
    changePassword: handleChangePassword,
    changeUserPassword: handleChangeUserPassword,
    changeUserPasswordByAdmin: handleChangeUserPasswordByAdmin
  };
  return /* @__PURE__ */ jsxRuntime.jsxRuntimeExports.jsx(AuthContext.Provider, { value: values, children });
};
const useAuth = () => React.useContext(AuthContext);
exports.AuthContext = AuthContext;
exports.AuthProvider = AuthProvider;
exports.CustomSnackbar = CustomSnackbar;
exports.Typography = Typography;
exports.convertRoutesToUseIdParams = convertRoutesToUseIdParams;
exports.createChainedFunction = createChainedFunction;
exports.debounce = debounce;
exports.generateRouteWithId = generateRouteWithId;
exports.isMuiElement = isMuiElement;
exports.navigateToRouteWithId = navigateToRouteWithId;
exports.ownerDocument = ownerDocument;
exports.ownerWindow = ownerWindow;
exports.requireCreateSvgIcon = requireCreateSvgIcon;
exports.setRef = setRef;
exports.unsupportedProp = unsupportedProp;
exports.updatePathnameWithIdParams = updatePathnameWithIdParams;
exports.useAuth = useAuth;
exports.useControlled = useControlled;
exports.useEnhancedEffect = useEnhancedEffect;
exports.useEventCallback = useEventCallback;
exports.useForkRef = useForkRef;
exports.useId = useId;
exports.useIsFocusVisible = useIsFocusVisible;
exports.useTimeout = useTimeout;
//# sourceMappingURL=useAuth-vPRkzGjO.js.map
