import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { memo, useState, Fragment, useRef, useEffect, useCallback, useMemo } from 'react';
import { SidebarMenuItem, SidebarGroup, SidebarGroupContent, SidebarMenu, SidebarMenuButton, SidebarMenuSub, SidebarProvider, useSidebar, Sidebar as Sidebar$1, SidebarHeader, SidebarTrigger, SidebarContent, SidebarRail } from '@bigbinary/neeto-atoms/primitives';
import { capitalize, isPresent, hyphenate, isNotEmpty, isNot } from '@bigbinary/neeto-cist';
import useLocalStorage from '@bigbinary/neeto-commons-frontend/v2/react-utils/useLocalStorage';
import { append, is, findLast } from 'ramda';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useHistory } from 'react-router-dom';
import { u as useKeyboardShortcutsPaneState } from '../useKeyboardShortcutsPaneState-BlyFMEtW.js';
import { S as SPECIAL_APP_NAMES, D as DEFAULT_HOME_PATH, f as filterByPermissions, a as CheckPointNavLinks, P as PINNED_MORE_NAV_LINKS_KEY, b as SubLinkItem, g as getSidebarStateLocalStorageKey, c as SIDEBAR_WIDTH_KEY, d as DEFAULT_SIDEBAR_WIDTH, e as SELECTED_NAV_LINK_ROUTE_STORAGE_KEY, C as ConfigureView, h as getActiveConfigurePageLink, M as MIN_SIDEBAR_WIDTH, i as MAX_SIDEBAR_WIDTH } from '../ConfigureView-CG1M2-3b.js';
import classnames from 'classnames';
import { globalProps as globalProps$1 } from '@bigbinary/neeto-commons-frontend/v2/initializers';
import Neeto from '@bigbinary/neeto-icons/typeface-logos/Neeto';
import * as AppIcons from '@bigbinary/neeto-icons/typeface-logos';
import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import { DropdownMenu, Badge, Tooltip, Button } from '@bigbinary/neeto-atoms';
import { P as Plus } from '../plus-clM1IC_E.js';
import { E as Ellipsis } from '../ellipsis-DpI9xqUK.js';
import { C as ChevronRight } from '../chevron-right-DcaO-Hlu.js';
import { n } from '../inject-css-C2dztUxs.js';
import 'zustand/shallow';
import '@bigbinary/neeto-commons-frontend/v2/react-utils/withImmutableActions';
import 'zustand';
import '@bigbinary/neeto-commons-frontend/v2/utils/general';
import '@bigbinary/neeto-commons-frontend/v2/react-utils/useRegisterNavigationCheckpoint';
import '@bigbinary/neeto-filters-frontend/v2/Segments';
import '../chevron-left-BTVCxPw8.js';
import '../createLucideIcon-mNMhCCpf.js';

var Header = function Header(_ref) {
  var _ProductTypefaceLogos;
  var customLogo = _ref.customLogo,
    clearSettingsNav = _ref.clearSettingsNav;
  var productName = globalProps$1.appName.substr(5);
  var normalizedName = (productName || "").trim().toLowerCase();
  var specialCase = SPECIAL_APP_NAMES[normalizedName];
  var logoName = specialCase ? "Neeto".concat(specialCase) : "Neeto".concat(capitalize(normalizedName));
  var ProductTypefaceLogo = (_ProductTypefaceLogos = AppIcons[logoName]) !== null && _ProductTypefaceLogos !== void 0 ? _ProductTypefaceLogos : Neeto;
  var LogoComponent = customLogo !== null && customLogo !== void 0 ? customLogo : ProductTypefaceLogo;
  var isOnboarded = globalProps$1.user.isOnboarded !== false;
  return /*#__PURE__*/jsx("div", {
    className: "px-4 py-3",
    "data-testid": "sidebar-info",
    children: /*#__PURE__*/jsx(Link, {
      to: DEFAULT_HOME_PATH,
      className: classnames("mt-2 block w-full py-2", {
        "cursor-pointer": isOnboarded,
        "pointer-events-none": !isOnboarded
      }),
      onClick: clearSettingsNav,
      children: globalProps$1.sidebarTitle ? /*#__PURE__*/jsx("span", {
        className: "text-sidebar-foreground text-xl leading-9 font-bold",
        children: globalProps$1.sidebarTitle
      }) : /*#__PURE__*/jsx(LogoComponent, {
        className: "h-9 w-auto max-w-full"
      })
    })
  });
};
var Header$1 = /*#__PURE__*/memo(Header);

var AddAction = function AddAction(_ref) {
  var actions = _ref.actions;
  return /*#__PURE__*/jsx(DropdownMenu, {
    dropdownProps: {
      align: "end",
      side: "bottom"
    },
    customTarget: /*#__PURE__*/jsx("button", {
      className: "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-sidebar-ring absolute end-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden focus-visible:ring-2 md:opacity-0 md:group-focus-within/menu-item:opacity-100 md:group-hover/menu-item:opacity-100",
      "data-testid": "add-dropdown-trigger",
      onClick: function onClick(e) {
        e.preventDefault();
        e.stopPropagation();
      },
      children: /*#__PURE__*/jsx(Plus, {})
    }),
    children: actions.map(function (action) {
      return /*#__PURE__*/jsx(DropdownMenu.MenuItem, {
        onClick: function onClick() {
          var _action$onClick;
          (_action$onClick = action.onClick) === null || _action$onClick === void 0 || _action$onClick.call(action);
        },
        children: action.label
      }, action.key);
    })
  });
};

function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var PinIcon = function PinIcon(_ref) {
  var size = _ref.size,
    otherProps = _ref.otherProps;
  return /*#__PURE__*/jsx("svg", _objectSpread$3(_objectSpread$3({
    fill: "currentColor",
    height: size,
    viewBox: "0 -960 960 960",
    width: size,
    xmlns: "http://www.w3.org/2000/svg"
  }, otherProps), {}, {
    children: /*#__PURE__*/jsx("path", {
      d: "m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40zm-286 80h252l-46-46v-314H400v314zm126 0"
    })
  }));
};

function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var UnpinIcon = function UnpinIcon(_ref) {
  var size = _ref.size,
    otherProps = _ref.otherProps;
  return /*#__PURE__*/jsx("svg", _objectSpread$2(_objectSpread$2({
    fill: "currentColor",
    height: size,
    viewBox: "0 -960 960 960",
    width: size,
    xmlns: "http://www.w3.org/2000/svg"
  }, otherProps), {}, {
    children: /*#__PURE__*/jsx("path", {
      d: "m640-480 80 80v80H520v240l-40 40-40-40v-240H240v-80l80-80v-280h-40v-80h400v80h-40z"
    })
  }));
};

function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var MoreDropdown = function MoreDropdown(_ref) {
  var moreNavLinks = _ref.moreNavLinks,
    isNavLinkPinned = _ref.isNavLinkPinned,
    handleTogglePin = _ref.handleTogglePin;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var isRTL = document.documentElement.dir === "rtl";
  return /*#__PURE__*/jsx(SidebarMenuItem, {
    children: /*#__PURE__*/jsx(DropdownMenu, {
      closeOnSelect: false,
      position: isRTL ? "left-start" : "right-start",
      customTarget: /*#__PURE__*/jsxs("button", {
        className: "text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground flex w-full items-center gap-2 rounded-md p-2 text-sm outline-hidden",
        "data-testid": "more-nav-links-dropdown-button",
        children: [/*#__PURE__*/jsx(Ellipsis, {}), /*#__PURE__*/jsx("span", {
          className: "truncate",
          children: t("neetoMolecules.sidebar.more")
        })]
      }),
      dropdownProps: {
        className: "z-[99999] p-0",
        "data-testid": "more-nav-links-dropdown-menu"
      },
      children: moreNavLinks.filter(filterByPermissions).map(function (navLink, index) {
        var label = navLink.label,
          icon = navLink.icon,
          navLinkKey = navLink.key,
          to = navLink.to,
          onClick = navLink.onClick,
          tag = navLink.tag;
        var IconSVG = icon;
        var isPinned = isNavLinkPinned(navLink);
        return /*#__PURE__*/jsx(DropdownMenu.MenuItem, {
          "data-testid": label,
          onSelect: function onSelect(e) {
            return e.preventDefault();
          },
          children: /*#__PURE__*/jsxs(CheckPointNavLinks, {
            onClick: onClick,
            to: to,
            className: "flex w-full cursor-pointer items-center justify-between gap-2 px-2 py-1",
            children: [/*#__PURE__*/jsxs("span", {
              className: "flex min-w-0 flex-grow items-center gap-2",
              children: [icon && /*#__PURE__*/jsx(IconSVG, {
                className: "flex-shrink-0",
                size: 20
              }), /*#__PURE__*/jsxs("span", {
                className: "flex min-w-0 flex-grow items-center gap-2",
                children: [label, tag && /*#__PURE__*/jsx(Badge, _objectSpread$1({}, tag))]
              })]
            }), /*#__PURE__*/jsx(Tooltip, {
              position: "right",
              content: isPinned ? t("neetoMolecules.sidebar.unpin") : t("neetoMolecules.sidebar.pin"),
              children: /*#__PURE__*/jsx(Button, {
                className: "flex-shrink-0",
                "data-testid": "pin-button",
                size: "icon-sm",
                variant: "ghost",
                onClick: function onClick(event) {
                  return handleTogglePin(navLink, event);
                },
                children: isPinned ? /*#__PURE__*/jsx(UnpinIcon, {
                  otherProps: {},
                  size: 16
                }) : /*#__PURE__*/jsx(PinIcon, {
                  otherProps: {},
                  size: 16
                })
              })
            })]
          })
        }, navLinkKey || index);
      })
    })
  });
};

var _excluded = ["label", "to", "icon", "items", "isConfigureNavLink", "isCountsLoading", "count", "component", "onClick", "addActions", "tag"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var renderCount = function renderCount(count) {
  return count > 999 ? "999+" : count;
};
var NavLinks = function NavLinks(_ref) {
  var navLinks = _ref.navLinks,
    moreNavLinks = _ref.moreNavLinks,
    isCountsLoadingDeprecated = _ref.isCountsLoading,
    setSelectedNavLinkRoute = _ref.setSelectedNavLinkRoute;
  var location = useLocation();
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    expandedNavLinkKeys = _useState2[0],
    setExpandedNavLinkKeys = _useState2[1];
  var _useLocalStorage = useLocalStorage(PINNED_MORE_NAV_LINKS_KEY, []),
    _useLocalStorage2 = _slicedToArray(_useLocalStorage, 2),
    pinnedNavLinks = _useLocalStorage2[0],
    setPinnedNavLinks = _useLocalStorage2[1];
  var handleNavLinkClick = function handleNavLinkClick(_ref2) {
    var event = _ref2.event,
      isActive = _ref2.isActive,
      navLink = _ref2.navLink;
    var isExpandable = isPresent(navLink.items) || isPresent(navLink.component);
    if (!isExpandable) {
      setExpandedNavLinkKeys([]);
      return;
    }
    if (navLink.isConfigureNavLink && isNotEmpty(navLink.items)) {
      setSelectedNavLinkRoute(navLink.to);
    }
    var navLinkKey = navLink.key || navLink.to;
    if (isActive()) {
      var isExpanded = expandedNavLinkKeys.includes(navLinkKey);
      setExpandedNavLinkKeys(isExpanded ? [] : [navLinkKey]);
      navLink.resetPath !== true && event.preventDefault();
      return;
    }
    setExpandedNavLinkKeys([navLinkKey]);
  };
  var handleTogglePin = function handleTogglePin(navLink, event) {
    event.preventDefault();
    event.stopPropagation();
    var navLinkKey = navLink.key || navLink.to;
    var isPinned = pinnedNavLinks.includes(navLinkKey);
    if (isPinned) {
      setPinnedNavLinks(pinnedNavLinks.filter(isNot(navLinkKey)));
    } else {
      setPinnedNavLinks([].concat(_toConsumableArray(pinnedNavLinks), [navLinkKey]));
    }
  };
  var isNavLinkPinned = function isNavLinkPinned(navLink) {
    if (!navLink) return false;
    var navLinkKey = navLink.key || navLink.to;
    return pinnedNavLinks.includes(navLinkKey);
  };
  var pinnedItems = moreNavLinks ? moreNavLinks.filter(isNavLinkPinned) : [];
  var activeMoreNavLink = moreNavLinks ? moreNavLinks.find(function (navLink) {
    return navLink && (location.pathname + location.search).startsWith(navLink.to);
  }) : null;
  var additionalItems = _toConsumableArray(pinnedItems);
  if (activeMoreNavLink && !isNavLinkPinned(activeMoreNavLink)) {
    additionalItems.push(activeMoreNavLink);
  }
  var combinedNavLinks = [].concat(_toConsumableArray(navLinks), _toConsumableArray(additionalItems));
  return /*#__PURE__*/jsx(SidebarGroup, {
    children: /*#__PURE__*/jsx(SidebarGroupContent, {
      children: /*#__PURE__*/jsxs(SidebarMenu, {
        className: "gap-1",
        children: [combinedNavLinks.filter(filterByPermissions).map(function (navLink, index) {
          var label = navLink.label,
            to = navLink.to,
            icon = navLink.icon,
            items = navLink.items,
            isConfigureNavLink = navLink.isConfigureNavLink,
            _navLink$isCountsLoad = navLink.isCountsLoading,
            isCountsLoading = _navLink$isCountsLoad === void 0 ? false : _navLink$isCountsLoad,
            _navLink$count = navLink.count,
            count = _navLink$count === void 0 ? null : _navLink$count,
            Component = navLink.component,
            _onClick = navLink.onClick,
            _navLink$addActions = navLink.addActions,
            addActions = _navLink$addActions === void 0 ? [] : _navLink$addActions,
            tag = navLink.tag,
            otherProps = _objectWithoutProperties(navLink, _excluded);
          var IconSVG = icon;
          var url = new URL(to, window.location.href);
          var isActive = function isActive() {
            return is(Function, otherProps.isActive) ? otherProps.isActive() : location.pathname.startsWith(url.pathname);
          };
          var isExpandable = items || Component;
          var navLinkKey = navLink.key || navLink.to;
          var isMenuExpanded = expandedNavLinkKeys.includes(navLinkKey) && !isCountsLoadingDeprecated;
          var handleCaretClick = function handleCaretClick(event) {
            event.preventDefault();
            event.stopPropagation();
            setExpandedNavLinkKeys(function (keys) {
              return keys.includes(navLinkKey) ? keys.filter(isNot(navLinkKey)) : append(navLinkKey, keys);
            });
          };
          return /*#__PURE__*/jsxs(Fragment, {
            children: [/*#__PURE__*/jsxs(SidebarMenuItem, {
              children: [/*#__PURE__*/jsx(SidebarMenuButton, {
                asChild: true,
                className: "h-10",
                isActive: isActive(),
                children: /*#__PURE__*/jsxs(CheckPointNavLinks, _objectSpread(_objectSpread({
                  activeClassName: "active",
                  className: "font-medium",
                  "data-testid": "navlink-".concat(hyphenate(label)),
                  onClick: function onClick(event) {
                    handleNavLinkClick({
                      event: event,
                      isActive: isActive,
                      navLink: navLink
                    });
                    _onClick === null || _onClick === void 0 || _onClick(event);
                  }
                }, _objectSpread({
                  isActive: isActive,
                  to: to
                }, otherProps)), {}, {
                  children: [icon && /*#__PURE__*/jsxs("span", {
                    className: "relative",
                    "data-testid": label,
                    children: [/*#__PURE__*/jsx(IconSVG, {}), isPresent(count) && !isCountsLoading && /*#__PURE__*/jsx("span", {
                      className: "bg-destructive text-destructive-foreground absolute -end-1.5 -top-1.5 flex h-4 min-w-4 items-center justify-center rounded-full px-0.5 text-[10px]",
                      children: renderCount(count)
                    })]
                  }), /*#__PURE__*/jsx("span", {
                    className: "flex-grow truncate",
                    children: label
                  }), tag && /*#__PURE__*/jsx(Badge, _objectSpread({}, tag)), isExpandable && !isConfigureNavLink && /*#__PURE__*/jsx("span", {
                    className: "ms-auto shrink-0 transition-transform duration-200",
                    role: "button",
                    tabIndex: -1,
                    style: {
                      transform: isMenuExpanded ? "rotate(90deg)" : "rotate(0deg)"
                    },
                    onClick: handleCaretClick,
                    children: /*#__PURE__*/jsx(ChevronRight, {
                      className: "rtl:rotate-180"
                    })
                  })]
                }))
              }), isNotEmpty(addActions) && /*#__PURE__*/jsx(AddAction, {
                actions: addActions
              })]
            }), isExpandable && !isConfigureNavLink && isMenuExpanded && /*#__PURE__*/jsxs(Fragment$1, {
              children: [items && /*#__PURE__*/jsx(SidebarMenuSub, {
                children: items.filter(filterByPermissions).map(function (subItem, subIndex) {
                  var _subItem$to;
                  return /*#__PURE__*/jsx(SubLinkItem, _objectSpread(_objectSpread({}, _objectSpread(_objectSpread({}, subItem), {}, {
                    isCountsLoading: isCountsLoading
                  })), {}, {
                    href: subItem.href,
                    isActive: subItem.isActive,
                    isSectionHeader: isPresent(subItem.item),
                    to: (_subItem$to = subItem.to) !== null && _subItem$to !== void 0 ? _subItem$to : subItem.path,
                    onClick: subItem.onClick
                  }), subIndex);
                })
              }), Component && /*#__PURE__*/jsx(Component, {
                navLink: navLink
              })]
            })]
          }, navLink.key || index);
        }), isNotEmpty(moreNavLinks) && /*#__PURE__*/jsx(MoreDropdown, {
          handleTogglePin: handleTogglePin,
          isNavLinkPinned: isNavLinkPinned,
          moreNavLinks: moreNavLinks
        })]
      })
    })
  });
};

var css = "[data-slot=sidebar][data-mobile=true]:has(.nm-sidebar-shadcn-header){max-width:min(var(--sidebar-width),85vw)!important;width:var(--sidebar-width)!important}";
n(css,{});

var Sidebar = function Sidebar(_ref) {
  var navLinks = _ref.navLinks,
    _ref$moreNavLinks = _ref.moreNavLinks,
    moreNavLinks = _ref$moreNavLinks === void 0 ? [] : _ref$moreNavLinks,
    customLogo = _ref.customLogo,
    _ref$isCountsLoading = _ref.isCountsLoading,
    isCountsLoading = _ref$isCountsLoading === void 0 ? false : _ref$isCountsLoading,
    _ref$showWorkspaceNam = _ref.showWorkspaceName,
    showWorkspaceName = _ref$showWorkspaceNam === void 0 ? false : _ref$showWorkspaceNam,
    _ref$isExpandable = _ref.isExpandable,
    isExpandable = _ref$isExpandable === void 0 ? true : _ref$isExpandable;
  var _useLocalStorage = useLocalStorage(getSidebarStateLocalStorageKey(), false),
    _useLocalStorage2 = _slicedToArray(_useLocalStorage, 2),
    isSidebarCollapsed = _useLocalStorage2[0],
    setIsSidebarCollapsed = _useLocalStorage2[1];
  var _useLocalStorage3 = useLocalStorage(SIDEBAR_WIDTH_KEY, DEFAULT_SIDEBAR_WIDTH),
    _useLocalStorage4 = _slicedToArray(_useLocalStorage3, 2),
    sidebarWidthRaw = _useLocalStorage4[0],
    setSidebarWidth = _useLocalStorage4[1];
  var sidebarWidth = typeof sidebarWidthRaw === "string" ? parseInt(sidebarWidthRaw, 10) || DEFAULT_SIDEBAR_WIDTH : sidebarWidthRaw || DEFAULT_SIDEBAR_WIDTH;
  return /*#__PURE__*/jsx(SidebarProvider, {
    className: "!w-auto",
    open: !isSidebarCollapsed,
    style: {
      "--sidebar-width": "".concat(sidebarWidth / 16, "rem")
    },
    onOpenChange: function onOpenChange(open) {
      return setIsSidebarCollapsed(!open);
    },
    children: /*#__PURE__*/jsx(SidebarBody, {
      customLogo: customLogo,
      isCountsLoading: isCountsLoading,
      isExpandable: isExpandable,
      isSidebarCollapsed: isSidebarCollapsed,
      moreNavLinks: moreNavLinks,
      navLinks: navLinks,
      setIsSidebarCollapsed: setIsSidebarCollapsed,
      setSidebarWidth: setSidebarWidth,
      showWorkspaceName: showWorkspaceName,
      sidebarWidth: sidebarWidth
    })
  });
};
var SidebarBody = function SidebarBody(_ref2) {
  var navLinks = _ref2.navLinks,
    moreNavLinks = _ref2.moreNavLinks,
    customLogo = _ref2.customLogo,
    isCountsLoading = _ref2.isCountsLoading,
    showWorkspaceName = _ref2.showWorkspaceName,
    isExpandable = _ref2.isExpandable,
    isSidebarCollapsed = _ref2.isSidebarCollapsed,
    setIsSidebarCollapsed = _ref2.setIsSidebarCollapsed,
    sidebarWidth = _ref2.sidebarWidth,
    setSidebarWidth = _ref2.setSidebarWidth;
  var _useSidebar = useSidebar(),
    isMobile = _useSidebar.isMobile,
    setOpenMobile = _useSidebar.setOpenMobile,
    openMobile = _useSidebar.openMobile;
  var _useKeyboardShortcuts = useKeyboardShortcutsPaneState(),
    _useKeyboardShortcuts2 = _slicedToArray(_useKeyboardShortcuts, 1),
    isKeyboardShortcutsPaneOpen = _useKeyboardShortcuts2[0];
  var _useLocalStorage5 = useLocalStorage(SELECTED_NAV_LINK_ROUTE_STORAGE_KEY, null),
    _useLocalStorage6 = _slicedToArray(_useLocalStorage5, 2),
    selectedNavLinkRoute = _useLocalStorage6[0],
    setSelectedNavLinkRoute = _useLocalStorage6[1];
  var isDraggingRef = useRef(false);
  var hasDraggedRef = useRef(false);
  var startXRef = useRef(null);
  var startWidthRef = useRef(null);
  var isInitialMountRef = useRef(true);
  var location = useLocation();
  var history = useHistory();
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var isRTL = document.documentElement.dir === "rtl";
  var sidebarSide = isRTL ? "right" : "left";
  useEffect(function () {
    if (isInitialMountRef.current) {
      isInitialMountRef.current = false;
      return;
    }
    if (isMobile) {
      if (isKeyboardShortcutsPaneOpen) setOpenMobile(false);
      return;
    }
    if (isKeyboardShortcutsPaneOpen) setIsSidebarCollapsed(true);else setIsSidebarCollapsed(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps -- setIsSidebarCollapsed / setOpenMobile may not be stable across renders
  }, [isKeyboardShortcutsPaneOpen, isMobile]);
  useEffect(function () {
    if (!isPresent(navLinks)) return;
    var currentLink = findLast(function (_ref3) {
      var to = _ref3.to,
        isActive = _ref3.isActive;
      var url = new URL(to, window.location.href);
      return is(Function, isActive) ? isActive() : location.pathname.includes(url.pathname);
    })(navLinks);
    if (isPresent(currentLink)) {
      setSelectedNavLinkRoute(currentLink.isConfigureNavLink ? currentLink.to : null);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only: sets initial selected route from current URL
  }, []);
  var handleRailMouseDown = useCallback(function (e) {
    if (!isExpandable || isMobile) return;
    isDraggingRef.current = true;
    hasDraggedRef.current = false;
    startXRef.current = e.clientX;
    startWidthRef.current = sidebarWidth;
    var wrapper = document.querySelector("[data-slot='sidebar-wrapper']");
    if (wrapper) wrapper.dataset.resizing = "true";
    document.body.style.cursor = "col-resize";
    document.body.style.userSelect = "none";
    e.preventDefault();
  }, [sidebarWidth, isExpandable, isMobile]);
  var handleRailClick = useCallback(function (e) {
    if (!hasDraggedRef.current) return;
    e.preventDefault();
    e.stopPropagation();
    hasDraggedRef.current = false;
  }, []);
  useEffect(function () {
    if (!isExpandable || isMobile) return undefined;
    var onMouseMove = function onMouseMove(e) {
      if (!isDraggingRef.current) return;
      hasDraggedRef.current = true;
      var dx = e.clientX - startXRef.current;
      var rtl = document.documentElement.dir === "rtl";
      var newWidth = startWidthRef.current + (rtl ? -dx : dx);
      newWidth = Math.max(MIN_SIDEBAR_WIDTH, Math.min(newWidth, MAX_SIDEBAR_WIDTH));
      var widthRem = "".concat(newWidth / 16, "rem");
      var wrapper = document.querySelector("[data-slot='sidebar-wrapper']");
      if (wrapper) wrapper.style.setProperty("--sidebar-width", widthRem);
      document.documentElement.style.setProperty("--nv-sidebar-width", widthRem);
    };
    var onMouseUp = function onMouseUp(e) {
      if (!isDraggingRef.current) return;
      var dx = e.clientX - startXRef.current;
      var rtlUp = document.documentElement.dir === "rtl";
      var finalWidth = startWidthRef.current + (rtlUp ? -dx : dx);
      finalWidth = Math.round(Math.max(MIN_SIDEBAR_WIDTH, Math.min(finalWidth, MAX_SIDEBAR_WIDTH)));
      setSidebarWidth(finalWidth);
      var wrapper = document.querySelector("[data-slot='sidebar-wrapper']");
      if (wrapper) delete wrapper.dataset.resizing;
      isDraggingRef.current = false;
      document.body.style.cursor = "";
      document.body.style.userSelect = "";
    };
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
    return function () {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
    };
  }, [isExpandable, isMobile, setSidebarWidth]);
  useEffect(function () {
    document.documentElement.style.setProperty("--nv-sidebar-width", isMobile ? "0rem" : "".concat(sidebarWidth / 16, "rem"));
  }, [sidebarWidth, isMobile]);
  var handleGoBack = function handleGoBack(event) {
    event.preventDefault();
    setSelectedNavLinkRoute(null);
    var configureNavLink = getActiveConfigurePageLink({
      navLinks: navLinks,
      location: location
    });
    if (configureNavLink !== null && configureNavLink !== void 0 && configureNavLink.to) {
      history.push(configureNavLink.to);
    }
  };
  var activeLink = useMemo(function () {
    return navLinks.find(function (link) {
      if (is(Function, link.isActive)) return link.isActive();
      var url = new URL(link.to, window.location.href);
      return location.pathname.startsWith(url.pathname);
    });
  }, [location.pathname, navLinks]);
  var isSelectedNavLinkVisible = selectedNavLinkRoute && (activeLink === null || activeLink === void 0 ? void 0 : activeLink.to) === selectedNavLinkRoute && isNotEmpty(navLinks);
  return /*#__PURE__*/jsxs(Fragment$1, {
    children: [/*#__PURE__*/jsxs(Sidebar$1, {
      collapsible: "offcanvas",
      side: sidebarSide,
      children: [/*#__PURE__*/jsxs(SidebarHeader, {
        className: "nm-sidebar-shadcn-header relative p-0",
        children: [/*#__PURE__*/jsx(Header$1, {
          customLogo: customLogo,
          clearSettingsNav: function clearSettingsNav() {
            return setSelectedNavLinkRoute(null);
          }
        }), /*#__PURE__*/jsx(SidebarTrigger, {
          className: "absolute end-2 top-3",
          title: t("neetoMolecules.sidebar.hideMenu")
        }), showWorkspaceName && /*#__PURE__*/jsxs("div", {
          className: "border-sidebar-border border-b px-4 py-2",
          children: [/*#__PURE__*/jsx("h5", {
            className: "text-sidebar-foreground mb-1 text-sm font-semibold",
            children: t("neetoMolecules.sidebar.myWorkspace")
          }), /*#__PURE__*/jsx("span", {
            className: "text-sidebar-foreground/70 truncate text-xs",
            children: globalProps.organization.name
          })]
        })]
      }), /*#__PURE__*/jsx(SidebarContent, {
        children: isSelectedNavLinkVisible ? /*#__PURE__*/jsx(ConfigureView, {
          handleGoBack: handleGoBack,
          navLink: activeLink
        }) : /*#__PURE__*/jsx(NavLinks, {
          isCountsLoading: isCountsLoading,
          moreNavLinks: moreNavLinks,
          navLinks: navLinks,
          setSelectedNavLinkRoute: setSelectedNavLinkRoute
        })
      }), !isMobile && isExpandable && !isSidebarCollapsed && /*#__PURE__*/jsx(SidebarRail, {
        onClickCapture: handleRailClick,
        onMouseDown: handleRailMouseDown
      })]
    }), (isMobile && !openMobile || !isMobile && isSidebarCollapsed) && /*#__PURE__*/jsx(SidebarTrigger, {
      className: "bg-background hover:bg-accent fixed start-2 top-2 z-50 size-9 rounded-full border shadow-sm",
      title: t("neetoMolecules.sidebar.showMenu")
    })]
  });
};

export { Sidebar as default };
//# sourceMappingURL=Sidebar.js.map
