import * as React from "react";
import React__default, { createContext, useState, useRef, useEffect, useContext } from "react";
import { j as jsxRuntimeExports } from "./jsx-runtime-ClFauRgV.esm.js";
import { a$ as postV1AuthChangeUserPasswordByAdmin, b0 as postV1AuthChangeUserPassword, b1 as postV1AuthChangePassword, b2 as postV1AuthResetPassword, b3 as postV1AuthForgotPassword, b4 as postV1AuthLogin, u as getV1RoleUserId } from "./api-BQ_tS-9F.esm.js";
import { a as auth, g as getApiConfig } from "./api-config-GOys-syK.esm.js";
import { useNavigate, useLocation, matchRoutes } from "react-router-dom";
import { P as Pathname, aH as PathnameGenerator, f as PathnameRental, aJ as PathnameGenerator$1, b as PathnameCrm, aI as PathnameGenerator$2, e as PathnamePurchase, aN as ROUTES, aK as PathnameGenerator$3, d as PathnameManufacturing, aL as PathnameGenerator$4, c as PathnameInventory, aM as PathnameGenerator$5, a as PathnameAccounting } from "./pathname.rental-VYOFVGX6.esm.js";
import { at as getToken } from "./common-B0qL-cCR.esm.js";
import { useSnackbar, SnackbarContent, enqueueSnackbar } from "notistack";
import { io } from "socket.io-client";
import { styled, Typography as Typography$1, Box, Avatar, IconButton } from "@mui/material";
import { _ as _extends, C as ClassNameGenerator, j as capitalize, k as interopRequireDefaultExports } from "./identifier-u4E_J1of.esm.js";
import { a as getAugmentedNamespace } from "./_commonjsHelpers-CcAunmGO.esm.js";
import { c as createSvgIcon$1, N as Notification } from "./notification-Dr_nE2Dc.esm.js";
import { i as images } from "./images-DvZ6-RV8.esm.js";
/* empty css                             */
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.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 ? _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.useLayoutEffect : React.useEffect;
let globalId = 0;
function useGlobalId(idOverride) {
  const [defaultId, setDefaultId] = React.useState(idOverride);
  const id = idOverride || defaultId;
  React.useEffect(() => {
    if (defaultId == null) {
      globalId += 1;
      setDefaultId(`mui-${globalId}`);
    }
  }, [defaultId]);
  return id;
}
const maybeReactUseId = React["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.useRef(controlled !== void 0);
  const [valueState, setValue] = React.useState(defaultProp);
  const value = isControlled ? controlled : valueState;
  if (process.env.NODE_ENV !== "production") {
    React.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.useRef(defaultProp);
    React.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.useCallback((newValue) => {
    if (!isControlled) {
      setValue(newValue);
    }
  }, []);
  return [value, setValueIfUncontrolled];
}
function useEventCallback(fn) {
  const ref = React.useRef(fn);
  useEnhancedEffect(() => {
    ref.current = fn;
  });
  return React.useRef((...args) => (
    // @ts-expect-error hide `this`
    (0, ref.current)(...args)
  )).current;
}
function useForkRef(...refs) {
  return React.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.useRef(UNINITIALIZED);
  if (ref.current === UNINITIALIZED) {
    ref.current = init(initArg);
  }
  return ref;
}
const EMPTY = [];
function useOnMount(fn) {
  React.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.useCallback((node) => {
    if (node != null) {
      prepare(node.ownerDocument);
    }
  }, []);
  const isFocusVisibleRef = React.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"));
    }
    ClassNameGenerator.configure(generator);
  }
};
const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  capitalize,
  createChainedFunction,
  createSvgIcon: createSvgIcon$1,
  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__ */ getAugmentedNamespace(utils);
var hasRequiredCreateSvgIcon;
function requireCreateSvgIcon() {
  if (hasRequiredCreateSvgIcon) return createSvgIcon;
  hasRequiredCreateSvgIcon = 1;
  (function(exports) {
    "use client";
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    Object.defineProperty(exports, "default", {
      enumerable: true,
      get: function() {
        return _utils.createSvgIcon;
      }
    });
    var _utils = require$$0;
  })(createSvgIcon);
  return createSvgIcon;
}
var _interopRequireDefault = interopRequireDefaultExports;
Object.defineProperty(Close, "__esModule", {
  value: true
});
var default_1 = Close.default = void 0;
var _createSvgIcon = _interopRequireDefault(requireCreateSvgIcon());
var _jsxRuntime = jsxRuntimeExports;
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 = styled(Typography$1)(
  ({ 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__ */ jsxRuntimeExports.jsx(StyledTypography, { className: `${type} ${weight} ${className}`, ...rest, children });
}
const mainModuleIcons = {
  rbac: images.user,
  document: images.document,
  "accounts-and-finance": images.accounting,
  inventory: images.inventory,
  manufacturing: images.manufacturing,
  sales: images.crm,
  rental: images.rental,
  user: images.user,
  purchase: images.procurement,
  hrms: 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__default.forwardRef(
  ({ message, variant = "default", linkUrl, snackbarKey, data }, ref) => {
    const { closeSnackbar } = useSnackbar();
    const navigate = 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__ */ jsxRuntimeExports.jsx(
      SnackbarContent,
      {
        ref,
        style: {
          backgroundColor: backgroundColorMap[variant],
          color: textColorMap[variant]
        },
        className: "SnackBar",
        onClick: handleClick,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { display: "flex", alignItems: "center", p: 2, position: "relative", gap: 2, width: "100%", children: [
          (mainModuleIcons == null ? void 0 : mainModuleIcons[data.module]) ? /* @__PURE__ */ jsxRuntimeExports.jsx(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__ */ jsxRuntimeExports.jsx(
            Notification,
            {
              style: {
                color: textColorMap[variant],
                marginTop: 2
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { display: "flex", alignItems: "center", width: "100%", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { flex: "1", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "h5", color: "inherit", weight: "bold", children: "New Notification" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s3", mt: 0.5, color: "inherit", children: message })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              IconButton,
              {
                size: "small",
                onClick: handleCloseClick,
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(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 = createContext(defaultProvider);
const AuthProvider = ({ children, publicRoutes = [] }) => {
  const [user, setUser] = useState(defaultProvider.user);
  const [authToken, setAuthToken] = useState("");
  const [loading, setLoading] = useState(defaultProvider.loading);
  const socketRef = useRef(null);
  const navigate = useNavigate();
  const location = 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(PathnameGenerator$5(PathnameAccounting.VIEW_SALES_INVOICES), moduleId.toString()),
      "asset transfers": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_ASSET_TRANSFER), moduleId.toString()),
      "budgets": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_BUDGET), moduleId.toString()),
      "cash expense": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_CASH_EXPENSE), moduleId.toString()),
      "credit notes": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_CREDIT_NOTE), moduleId.toString()),
      "debit notes": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_DEBIT_NOTE), moduleId.toString()),
      "expense reimbursement": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_EXPENSE_REIMBURSEMENT), moduleId.toString()),
      "journal entries": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_JOURNAL_ENTRY), moduleId.toString()),
      "payment entries": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_PAYMENT_ENTRY), moduleId.toString()),
      "purchase invoice": () => generateRouteWithId(PathnameGenerator$5(PathnameAccounting.VIEW_PURCHASE_INVOICE), moduleId.toString()),
      "stock transfer": () => generateRouteWithId(PathnameGenerator$4(PathnameInventory.VIEW_STOCK_TRANSFER), moduleId.toString()),
      "bills of materials": () => generateRouteWithId(PathnameGenerator$3(PathnameManufacturing.VIEW_BILL_OF_MATERIAL), moduleId.toString()),
      "purchase agreement": () => generateRouteWithId(PathnameGenerator$2(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 ? ROUTES.VIEW : PathnameGenerator$2(PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString());
      },
      "purchase request": () => generateRouteWithId(PathnameGenerator$2(PathnamePurchase.VIEW_PURCHASE_ORDER), moduleId.toString()),
      "vra": () => generateRouteWithId(PathnameGenerator$2(PathnamePurchase.VIEW_VENDOR_RETURNS), moduleId.toString()),
      "sl customer returns": () => generateRouteWithId(PathnameGenerator$1(PathnameCrm.VIEW_CUSTOMER_RETURNS), moduleId.toString()),
      "sales order": () => generateRouteWithId(PathnameGenerator$1(PathnameCrm.VIEW_SALES_ORDER), moduleId.toString()),
      "rental order": () => generateRouteWithId(PathnameGenerator(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),
      "replacement order": () => generateRouteWithId(PathnameGenerator(PathnameRental.VIEW_RENTAL_ORDER), moduleId.toString()),
      "rental agreement": () => generateRouteWithId(PathnameGenerator(PathnameRental.VIEW_AGREEMENT), moduleId.toString()),
      "cross hire order": () => generateRouteWithId(PathnameGenerator(PathnameRental.VIEW_CROSS_HIRE_ORDER), moduleId.toString()),
      "cross hire request": () => generateRouteWithId(PathnameGenerator(PathnameRental.VIEW_CROSS_HIRE_REQUEST), moduleId.toString())
    };
    return ((_a = routeMap[key]) == null ? void 0 : _a.call(routeMap)) || "/dashboard";
  };
  useEffect(() => {
    setLoading(true);
    const storedToken = window.localStorage.getItem(auth.storageTokenKeyName);
    const storedUser = isJsonParse(window.localStorage.getItem(auth.storageUserKeyName)) ?? null;
    const allPublicRoutes = [Pathname.LOGIN, Pathname.FORGOT_PASSWORD, Pathname.RESET_PASSWORD, Pathname.CHANGE_PASSWORD, ...publicRoutes];
    const currentPath = window.location.pathname;
    if (!storedToken && !storedUser) {
      console.log("allPublicRoutes..", allPublicRoutes, "currentPath..", currentPath);
      if (Boolean(!matchRoutes(allPublicRoutes.map((route) => ({ path: route })), location))) {
        navigate(Pathname.LOGIN);
      }
      setLoading(false);
    } else {
      setUser(storedUser);
      setAuthToken(storedToken || "");
      setLoading(false);
    }
  }, []);
  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 = getApiConfig();
    const socket = 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;
          }
        }
      }
      enqueueSnackbar(String(message), {
        variant: "default",
        anchorOrigin: { vertical: "top", horizontal: "center" },
        autoHideDuration: 5e3,
        content: (key) => /* @__PURE__ */ 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) => {
      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 getV1RoleUserId({ id: userId, ...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.DASHBOARD) => {
    var _a;
    setLoading(true);
    const storedToken = window.localStorage.getItem(auth.storageTokenKeyName);
    if (storedToken && user) {
      return navigate(Pathname.DASHBOARD);
    }
    try {
      const loginUser = await postV1AuthLogin({ ...params, ...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(auth.storageTokenKeyName, data.token);
          window.localStorage.setItem(auth.storageUserKeyName, JSON.stringify(userData));
          window.localStorage.setItem(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(auth.storageTokenKeyName);
    window.localStorage.removeItem(auth.storageUserKeyName);
    window.localStorage.removeItem(auth.storageRolePermissionKeyName);
    window.dispatchEvent(new Event("role-permission-changed"));
    setUser(null);
    setAuthToken("");
    navigate(Pathname.LOGIN);
  };
  const handleForgotPassword = async (params, callback) => {
    try {
      await postV1AuthForgotPassword({ ...params, ...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 postV1AuthResetPassword({ ...params, ...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 postV1AuthChangePassword({ ...params, ...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 postV1AuthChangeUserPassword({ ...params, ...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 postV1AuthChangeUserPasswordByAdmin({ ...params, ...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__ */ jsxRuntimeExports.jsx(AuthContext.Provider, { value: values, children });
};
const useAuth = () => useContext(AuthContext);
export {
  AuthContext as A,
  CustomSnackbar as C,
  Typography as T,
  AuthProvider as a,
  updatePathnameWithIdParams as b,
  convertRoutesToUseIdParams as c,
  useEnhancedEffect as d,
  useForkRef as e,
  useTimeout as f,
  generateRouteWithId as g,
  debounce as h,
  default_1 as i,
  useIsFocusVisible as j,
  useEventCallback as k,
  ownerDocument as l,
  createChainedFunction as m,
  navigateToRouteWithId as n,
  ownerWindow as o,
  isMuiElement as p,
  useControlled as q,
  requireCreateSvgIcon as r,
  setRef as s,
  useId as t,
  useAuth as u,
  unsupportedProp as v
};
//# sourceMappingURL=useAuth-CEQTm2rv.esm.js.map
