import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useRef, useEffect, Fragment as Fragment$1, memo, useCallback, useState, useMemo, createElement } from 'react';
import { g as getScrollBarWidth, i as isOverflown, d as distExports, u as useFetchPermissions } from './utils-CrN1b-Jp.js';
import i18next, { t } from 'i18next';
import { isNotEmpty, isPresent, hyphenate, _findBy, noop } from '@bigbinary/neeto-cist';
import { PLURAL } from '@bigbinary/neeto-commons-frontend/constants';
import { useQueryParams, withTitle } from '@bigbinary/neeto-commons-frontend/react-utils';
import Container from '@bigbinary/neeto-molecules/Container';
import Spinner from '@bigbinary/neetoui/Spinner';
import { not, map, prop, identical, includes, __, groupBy, pluck, isEmpty, filter } from 'ramda';
import { w as withReactQuery } from './withReactQuery-Dia59qcs.js';
import { b as useCreateRole, c as useUpdateRole, d as useDestroyRole, u as useFetchRoles, e as useBulkUpdateRoles } from './useRolesApi-93OoRU1s.js';
import { n } from './inject-css-C2dztUxs.js';
import NeetoHeader from '@bigbinary/neeto-molecules/Header';
import Button from '@bigbinary/neetoui/Button';
import Tooltip from '@bigbinary/neetoui/Tooltip';
import { useTranslation, Trans } from 'react-i18next';
import { taxonomies } from '@bigbinary/neeto-commons-frontend/initializers';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import Pane from '@bigbinary/neetoui/Pane';
import Typography from '@bigbinary/neetoui/Typography';
import ActionBlock from '@bigbinary/neetoui/formik/ActionBlock';
import Form from '@bigbinary/neetoui/formik/Form';
import Input from '@bigbinary/neetoui/formik/Input';
import Textarea from '@bigbinary/neetoui/formik/Textarea';
import { A as ADMIN_ROLES } from './constants-CXdiW8NZ.js';
import { S as ScrollToErrorField } from './index-BISwUwuE.js';
import { object, string } from 'yup';
import { P as Permissions, g as getChildrenRemovedFromRoot, s as sortPermissionsBySequence, a as getPermissionGroups, b as getModifiedPermissions } from './Permissions-BCkBjBNL.js';
import NoData from '@bigbinary/neetoui/NoData';
import classnames from 'classnames';
import Checkbox from '@bigbinary/neetoui/Checkbox';
import '@babel/runtime/helpers/toConsumableArray';
import _typeof from '@babel/runtime/helpers/typeof';
import InfoRound from '@bigbinary/neeto-icons/InfoRound';
import HelpPopover from '@bigbinary/neeto-molecules/HelpPopover';
import MoreDropdown from '@bigbinary/neeto-molecules/MoreDropdown';
import Alert from '@bigbinary/neetoui/Alert';
import Search from '@bigbinary/neeto-molecules/Search';
import Down from '@bigbinary/neeto-icons/Down';
import Up from '@bigbinary/neeto-icons/Up';
import './_commonjsHelpers-BFTU3MAI.js';
import '@tanstack/react-query';
import 'axios';
import './queryClient-Dsu-gu4Y.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'formik';

var css = ":root{--ntm-roles-table-default-scroll:0.9375rem;--ntm-roles-table-cell-height:3rem;--ntm-roles-sidebar-width:480px;--ntm-roles-table-header-height:4.5rem}.ntm-scrollbar__inner{height:12.5rem;width:100%}.ntm-scrollbar__outer{height:9.375rem;inset-inline-start:0;overflow:hidden;position:absolute;top:0;visibility:hidden;width:12.5rem}.ntm-empty-state{align-items:center;display:flex;height:100%;justify-content:center;width:100%}.ntm-roles-pane__body{margin-bottom:1.5rem;width:100%}.ntm-roles-pane__body-wrapper>*+*{margin-top:1rem}.ntm-roles-pane__body>*+*{margin-top:1.5rem}.ntm-roles-pane__footer{display:flex;gap:.5rem}.ntm-roles-permission__heading{padding-top:.5rem}.ntm-roles-permission__card{background-color:rgb(var(--neeto-ui-white));display:flex;flex-direction:column;gap:.75rem;padding:.4rem 0;position:relative}.ntm-roles-permission__card:after{background-color:rgb(var(--neeto-ui-gray-300));content:\"\";height:1px;inset-inline-start:-.9375rem;position:absolute;top:.875rem;width:.625rem}.ntm-roles-permission__card--description{flex-grow:1}.ntm-roles-permission__card--checkbox{padding:0 .5rem}.ntm-roles-permission__card .neeto-ui-checkbox__wrapper .neeto-ui-checkbox__container{align-items:flex-start}.ntm-roles-permission__card .neeto-ui-checkbox__wrapper .neeto-ui-checkbox__container .neeto-ui-checkbox[type=checkbox]:disabled+.neeto-ui-label{cursor:not-allowed;opacity:.5}.ntm-roles-permission__sub-blocks{position:relative}.ntm-roles-permission__sub-blocks:before{background-color:rgb(var(--neeto-ui-gray-300));content:\"\";height:calc(100% - .875rem);inset-inline-start:.5rem;position:absolute;top:0;width:.0625rem}.ntm-roles-permission__sub-blocks:empty{display:none}.ntm-roles-permission-category-card{border:1px solid rgb(var(--neeto-ui-gray-200));border-radius:var(--neeto-ui-rounded);padding:.625rem 1.25rem;transition:all .3s}.ntm-roles-permission-category-card--active{background-color:rgba(var(--neeto-ui-primary-50),1);border-color:rgb(var(--neeto-ui-primary-500));outline:1px solid rgb(var(--neeto-ui-primary-500))}.ntm-roles-permission-category-card--active .ntm-roles-permission__card{background-color:transparent}.ntm-roles-permission-category-card>.ntm-roles-permission__card:after{display:none}.ntm-roles-permission__card>.neeto-ui-checkbox__wrapper .neeto-ui-label{font-weight:400}.ntm-roles-permission-category-card>.ntm-roles-permission__card>.neeto-ui-checkbox__wrapper .neeto-ui-label{font-size:.9375rem}@keyframes ntm-roles-permission-blink{0%,to{color:inherit}50%{color:rgb(var(--neeto-ui-primary-500));font-weight:700}}.ntm-roles-permission__card--blink>.neeto-ui-checkbox__wrapper .neeto-ui-label{animation:ntm-roles-permission-blink .6s ease-in-out 0s 3}.ntm-roles-table__wrapper{height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - 24px);padding:0 2.5rem;width:100%}.ntm-roles-table__container{display:flex;height:100%}.ntm-roles-table__sidebar{border-top:thin solid rgb(var(--neeto-ui-gray-200));height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - 28px);min-width:480px;min-width:var(--ntm-roles-sidebar-width);width:480px;width:var(--ntm-roles-sidebar-width)}.ntm-roles-table-sidebar__search{height:4.5rem;height:var(--ntm-roles-table-header-height);padding:1.25rem 1.5rem}.ntm-roles-table-sidebar__list,.ntm-roles-table-sidebar__search{border-bottom:thin solid rgb(var(--neeto-ui-gray-200));border-left:thin solid rgb(var(--neeto-ui-gray-200));border-right:thin solid rgb(var(--neeto-ui-gray-200))}.ntm-roles-table-sidebar__list{max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - 5.4375rem - 28px);max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - var(--ntm-roles-table-header-height) - var(--ntm-roles-table-default-scroll) - 28px);overflow:auto;white-space:nowrap}.ntm-roles-table-sidebar__list-item{display:flex;flex-direction:column;min-height:3rem;min-height:var(--ntm-roles-table-cell-height);overflow-wrap:break-word;position:relative;white-space:normal}.ntm-roles-table-sidebar__list-item:after{background-color:rgb(var(--neeto-ui-gray-300));content:\"\";height:.0625rem;inset-inline-start:-1.125rem;position:absolute;top:1.4375rem;width:.875rem}.ntm-roles-table-sidebar__list-item.ntm-roles-table-sidebar__list-item--highlighted{align-items:center;background-color:rgb(var(--neeto-ui-gray-100));border-top:thin solid rgb(var(--neeto-ui-gray-200));flex-direction:row;justify-content:space-between;padding:.6875rem 1.5rem}.ntm-roles-table__columns{border-top:thin solid rgb(var(--neeto-ui-gray-200));flex-grow:1;overflow:hidden}.ntm-roles-table__cell{align-items:center;border-inline-end:thin solid rgb(var(--neeto-ui-gray-200));display:flex;height:3rem;height:var(--ntm-roles-table-cell-height);justify-content:center;min-height:3rem;min-height:var(--ntm-roles-table-cell-height);min-width:200px;padding:.75rem .5rem;width:100%}.ntm-roles-table-cell__checkbox-wrapper{height:1rem;margin:auto;position:absolute;width:1rem;z-index:10}.ntm-roles-table-cell__checkbox{z-index:10}.ntm-roles-table__header{align-items:center;display:flex;overflow-x:auto}.ntm-roles-table__header .ntm-roles-table__cell{border-bottom:thin solid rgb(var(--neeto-ui-gray-200));height:4.5rem;height:var(--ntm-roles-table-header-height)}.ntm-roles-table-header-cell__container{align-items:center;display:flex;justify-content:space-between;overflow:hidden;width:100%}.ntm-roles-table-header__dropdown{flex-shrink:0;margin:.1875rem}.ntm-roles-table-header__role-name{overflow:hidden;text-align:center;text-overflow:ellipsis;white-space:nowrap;width:100%}.ntm-roles-table__rows{max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - 5.4375rem - 28px);max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - var(--ntm-roles-table-header-height) - var(--ntm-roles-table-default-scroll) - 28px);overflow-y:auto;scrollbar-width:none;width:100%}.ntm-roles-table__rows::-webkit-scrollbar{height:0;width:0}.ntm-roles-table__rows::-webkit-scrollbar-thumb{background:rgb(var(--neeto-ui-gray-300));border-radius:3.125rem}.ntm-roles-table__rows::-webkit-scrollbar-thumb:hover{border-radius:3.125rem}.ntm-roles-table__rows::-webkit-scrollbar-track{background:rgb(var(--neeto-ui-gray-300))}.ntm-roles-table__rows div:last-child .ntm-roles-table__row:last-child .ntm-roles-table__cell{border-bottom:thin solid rgb(var(--neeto-ui-gray-200))}.ntm-roles-table__row{align-items:center;display:flex}.ntm-roles-table__row .ntm-roles-table__cell{border-top:thin solid rgb(var(--neeto-ui-gray-200));overflow:hidden;position:relative}.ntm-roles-table__row .ntm-roles-table__cell p{min-width:340px;opacity:0;width:340px}.ntm-roles-table__row.ntm-roles-table__row--highlighted .ntm-roles-table__cell{background-color:rgb(var(--neeto-ui-gray-100))}.ntm-roles-table-sidebar__drop-down-button{color:rgb(var(--neeto-ui-gray-600));cursor:pointer}.ntm-roles-modal__body>*+*{margin-top:1rem}.ntm-roles-modal__footer{display:flex;gap:.5rem}.ntm-roles-help-url-wrapper{align-items:center;display:flex;justify-content:center;padding:1rem 0;width:100%}.ntm-roles-table-sidebar__list-item-spacing-handler>.ntm-roles-table-sidebar__list-item .neeto-ui-text-body2{font-size:.9375rem;font-weight:500}.ntm-roles-table-sidebar__list-item-spacing-handler>.ntm-roles-table-sidebar__list-item:after,.ntm-roles-table-sidebar__list-item-spacing-handler>.ntm-roles-table-sidebar__list-item:before{display:none}.ntm-roles-table-sidebar__list-item-spacing-handler .ntm-roles-table-sidebar__list-item{align-items:center;flex-direction:row;gap:.25rem}.ntm-roles-table-sidebar__sub-blocks{position:relative}.ntm-roles-table-sidebar__sub-blocks:before{background-color:rgb(var(--neeto-ui-gray-300));content:\"\";height:calc(100% - 1.5rem);inset-inline-start:.375rem;position:absolute;top:0;width:.0625rem}.ntm-roles-table-sidebar__sub-blocks:empty{display:none}@media screen and (max-width:1024px){.ntm-roles-table__wrapper{--neeto-molecules-main-header-with-breadcrumbs-height:216px}.ntm-roles-table__sidebar{--ntm-roles-sidebar-width:260px;height:100%}}@media screen and (max-width:768px){.ntm-roles-table__wrapper{--neeto-molecules-main-header-with-breadcrumbs-height:186px;overflow:hidden;padding:0 1.25rem}.ntm-roles-table__container{height:auto;overflow-y:auto}.ntm-roles-table__sidebar{height:100%}.ntm-roles-table__columns,.ntm-roles-table__header{overflow:visible;overflow:initial}}\n/*# sourceMappingURL=data:application/json;base64,  */";
n(css,{});

var renderSearchProps = function renderSearchProps() {
  return {
    "data-testid": "ntm-search-roles-input",
    placeholder: t("neetoTeamMembers.placeholders.searchRole", PLURAL)
  };
};
var renderBreadcrumbs = function renderBreadcrumbs(breadcrumbs) {
  return breadcrumbs !== null && breadcrumbs !== void 0 ? breadcrumbs : [{
    text: taxonomies.member.plural,
    link: "/members"
  }];
};

var AddRoleButton = function AddRoleButton(_ref) {
  var config = _ref.config,
    onClick = _ref.onClick;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var isCreatePermissionGranted = config.permissions.create;
  return /*#__PURE__*/jsx(Tooltip, {
    content: t("neetoTeamMembers.tooltips.noPermissionToAddRole"),
    disabled: isCreatePermissionGranted,
    position: "bottom",
    children: /*#__PURE__*/jsx("span", {
      children: /*#__PURE__*/jsx(Button, {
        "data-testid": "ntm-add-role-button",
        disabled: !isCreatePermissionGranted,
        label: t("neetoTeamMembers.labels.addNewRole"),
        onClick: onClick
      })
    })
  });
};

var Header = function Header(_ref) {
  var _config$header, _config$header$titleH, _config$header2;
  var config = _ref.config,
    handleReset = _ref.handleReset,
    handleSubmit = _ref.handleSubmit,
    _ref$isDirty = _ref.isDirty,
    isDirty = _ref$isDirty === void 0 ? false : _ref$isDirty,
    setIsNewRolePaneOpen = _ref.setIsNewRolePaneOpen,
    roles = _ref.roles;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var isUpdatePermissionGranted = config.permissions.update;
  return /*#__PURE__*/jsx(NeetoHeader, {
    breadcrumbs: renderBreadcrumbs(config === null || config === void 0 || (_config$header = config.header) === null || _config$header === void 0 ? void 0 : _config$header.breadcrumbs),
    className: "ntm-roles-header",
    searchProps: isNotEmpty(roles) ? renderSearchProps() : null,
    title: t("neetoTeamMembers.common.role", PLURAL),
    titleHelpPopoverProps: (_config$header$titleH = config === null || config === void 0 || (_config$header2 = config.header) === null || _config$header2 === void 0 ? void 0 : _config$header2.titleHelpPopoverProps) !== null && _config$header$titleH !== void 0 ? _config$header$titleH : {},
    actionBlock: isDirty ? /*#__PURE__*/jsxs(Fragment, {
      children: [/*#__PURE__*/jsx(Tooltip, {
        content: t("neetoTeamMembers.tooltips.noPermissionToEditRoles"),
        disabled: isUpdatePermissionGranted,
        position: "bottom",
        children: /*#__PURE__*/jsx("span", {
          children: /*#__PURE__*/jsx(Button, {
            "data-testid": "ntm-role-submission-button",
            disabled: !isUpdatePermissionGranted,
            label: t("neetoTeamMembers.buttons.saveChanges"),
            type: "submit",
            onClick: handleSubmit
          })
        })
      }), /*#__PURE__*/jsx(Button, {
        "data-testid": "ntm-role-reset-button",
        label: t("neetoTeamMembers.buttons.reset"),
        style: "text",
        type: "reset",
        onClick: handleReset
      })]
    }) : /*#__PURE__*/jsx(AddRoleButton, {
      config: config,
      onClick: function onClick() {
        return setIsNewRolePaneOpen(true);
      }
    })
  });
};

var ROLE_NAME_MAX_LENGTH = 40;
var ROLE_DESCRIPTION_MAX_LENGTH = 255;
var ADD_ROLE_FORM_VALIDATION_SCHEMA = object({
  name: string().trim().max(ROLE_NAME_MAX_LENGTH,
  // @ts-ignore
  t("neetoTeamMembers.validations.nameLimitExceeded", {
    limit: ROLE_NAME_MAX_LENGTH
  }))
  // @ts-ignore
  .required(t("neetoTeamMembers.validations.enterRoleName")),
  description: string().nullable().trim().max(ROLE_DESCRIPTION_MAX_LENGTH,
  // @ts-ignore
  t("neetoTeamMembers.validations.descriptionLimitExceeded", {
    limit: ROLE_DESCRIPTION_MAX_LENGTH
  }))
});
var ADD_ROLE_FORM_INITIAL_VALUES = {
  name: "",
  description: "",
  permissionIds: []
};
var ROLE_FORMIK_PROPS = {
  validationSchema: ADD_ROLE_FORM_VALIDATION_SCHEMA
};

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 ManageRoles = function ManageRoles(_ref) {
  var _selectedRole$permiss;
  var config = _ref.config,
    _ref$isOpen = _ref.isOpen,
    isOpen = _ref$isOpen === void 0 ? false : _ref$isOpen,
    onClose = _ref.onClose,
    _ref$permissions = _ref.permissions,
    permissions = _ref$permissions === void 0 ? [] : _ref$permissions,
    _ref$selectedRole = _ref.selectedRole,
    selectedRole = _ref$selectedRole === void 0 ? {} : _ref$selectedRole,
    _ref$scrollTo = _ref.scrollTo,
    scrollTo = _ref$scrollTo === void 0 ? null : _ref$scrollTo;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var formReference = useRef(null);
  var inputReference = useRef(null);
  var lastScrollKeyRef = useRef(null);
  var _useCreateRole = useCreateRole({
      onSuccess: onClose
    }),
    createRole = _useCreateRole.mutate,
    isCreatingRole = _useCreateRole.isPending;
  var _useUpdateRole = useUpdateRole({
      onSuccess: onClose
    }),
    updateRole = _useUpdateRole.mutate,
    isUpdatingRole = _useUpdateRole.isPending;
  var isEdit = isPresent(selectedRole);
  var isSubmitting = isCreatingRole || isUpdatingRole;
  var handleSubmit = function handleSubmit(formValues) {
    var payload = {
      organizationRole: _objectSpread(_objectSpread({}, formValues), {}, {
        name: formValues.name.trim(),
        description: formValues.description.trim()
      })
    };
    isEdit ? updateRole({
      payload: payload,
      id: selectedRole.id
    }) : createRole(payload);
  };
  var initialValues = isEdit ? _objectSpread(_objectSpread({}, selectedRole), {}, {
    permissionIds: (_selectedRole$permiss = selectedRole.permissionIds) === null || _selectedRole$permiss === void 0 ? void 0 : _selectedRole$permiss.sort(),
    description: selectedRole.description || ""
  }) : ADD_ROLE_FORM_INITIAL_VALUES;
  var formikProps = _objectSpread(_objectSpread({}, ROLE_FORMIK_PROPS), {}, {
    initialValues: initialValues,
    onSubmit: handleSubmit
  });
  var isReadOnly = selectedRole.kind === "system";
  var isDisabled = ADMIN_ROLES.includes(selectedRole.name) && isReadOnly;
  useEffect(function () {
    var _selectedRole$id, _ref2, _scrollTo$permissionI;
    var activeClassName = "ntm-roles-permission-category-card--active";
    var blinkClassName = "ntm-roles-permission__card--blink";
    var getScrollableParent = function getScrollableParent(node) {
      var current = node === null || node === void 0 ? void 0 : node.parentElement;
      while (current) {
        var style = getComputedStyle(current);
        var overflowY = style.overflowY;
        var isScrollable = (overflowY === "auto" || overflowY === "scroll") && current.scrollHeight > current.clientHeight;
        if (isScrollable) return current;
        current = current.parentElement;
      }
      return document.scrollingElement || document.documentElement;
    };
    if (!isOpen) {
      lastScrollKeyRef.current = null;
      document.querySelectorAll(".".concat(activeClassName)).forEach(function (node) {
        return node.classList.remove(activeClassName);
      });
      document.querySelectorAll(".".concat(blinkClassName)).forEach(function (node) {
        return node.classList.remove(blinkClassName);
      });
      return function () {};
    }
    if (!scrollTo) return function () {};
    var key = "".concat((_selectedRole$id = selectedRole === null || selectedRole === void 0 ? void 0 : selectedRole.id) !== null && _selectedRole$id !== void 0 ? _selectedRole$id : "new", ":").concat(scrollTo.type, ":").concat((_ref2 = (_scrollTo$permissionI = scrollTo.permissionId) !== null && _scrollTo$permissionI !== void 0 ? _scrollTo$permissionI : scrollTo.category) !== null && _ref2 !== void 0 ? _ref2 : "");
    if (lastScrollKeyRef.current === key) return function () {};
    lastScrollKeyRef.current = key;
    var timeoutId;
    var highlightTimeoutId;
    var blinkTimeoutId;
    var scrollEndTimeoutId;
    var attempts = 0;
    var highlightedCard = null;
    var blinkedPermissionCard = null;
    var _attemptScroll = function attemptScroll() {
      attempts += 1;
      var elementId = scrollTo.type === "permission" ? "ntm-role-permission-".concat(scrollTo.permissionId) : "ntm-role-permission-category-".concat(hyphenate(scrollTo.category || ""));
      var el = document.getElementById(elementId);
      if (el) {
        el.scrollIntoView({
          behavior: "smooth",
          block: "center"
        });
        var categoryCard = scrollTo.type === "permission" ? el.closest(".ntm-roles-permission-category-card") : el.querySelector(".ntm-roles-permission-category-card");
        var scrollContainer = getScrollableParent(el);
        var startHighlight = function startHighlight() {
          if (!categoryCard) return;
          document.querySelectorAll(".".concat(activeClassName)).forEach(function (node) {
            return node.classList.remove(activeClassName);
          });
          categoryCard.classList.add(activeClassName);
          highlightedCard = categoryCard;
          clearTimeout(highlightTimeoutId);
          highlightTimeoutId = setTimeout(function () {
            categoryCard.classList.remove(activeClassName);
          }, 3000);
        };
        if (scrollTo.type === "permission") {
          var animationDurationMs = 600;
          var animationIterations = 3;
          var totalDurationMs = animationDurationMs * animationIterations + 100;
          var startBlink = function startBlink() {
            document.querySelectorAll(".".concat(blinkClassName)).forEach(function (node) {
              return node.classList.remove(blinkClassName);
            });
            el.classList.remove(blinkClassName);
            // Restart animation if the class was already present
            void el.offsetWidth;
            el.classList.add(blinkClassName);
            blinkedPermissionCard = el;
            clearTimeout(blinkTimeoutId);
            blinkTimeoutId = setTimeout(function () {
              el.classList.remove(blinkClassName);
            }, totalDurationMs);
          };

          // Start animation only after scroll settles (or after a max wait).
          var started = false;
          var maxWaitTimeoutId = setTimeout(function () {
            if (started) return;
            started = true;
            startHighlight();
            startBlink();
            scrollContainer.removeEventListener("scroll", _scheduleStart);
          }, 1200);
          var _scheduleStart = function scheduleStart() {
            clearTimeout(scrollEndTimeoutId);
            scrollEndTimeoutId = setTimeout(function () {
              if (started) return;
              started = true;
              startHighlight();
              startBlink();
              scrollContainer.removeEventListener("scroll", _scheduleStart);
              clearTimeout(maxWaitTimeoutId);
            }, 150);
          };
          scrollContainer.addEventListener("scroll", _scheduleStart, {
            passive: true
          });
          _scheduleStart();
        } else {
          // Highlight should also start only after scroll settles.
          var _started = false;
          var _maxWaitTimeoutId = setTimeout(function () {
            if (_started) return;
            _started = true;
            startHighlight();
            scrollContainer.removeEventListener("scroll", _scheduleStart2);
          }, 1200);
          var _scheduleStart2 = function scheduleStart() {
            clearTimeout(scrollEndTimeoutId);
            scrollEndTimeoutId = setTimeout(function () {
              if (_started) return;
              _started = true;
              startHighlight();
              scrollContainer.removeEventListener("scroll", _scheduleStart2);
              clearTimeout(_maxWaitTimeoutId);
            }, 150);
          };
          scrollContainer.addEventListener("scroll", _scheduleStart2, {
            passive: true
          });
          _scheduleStart2();
        }
        return;
      }

      // Pane content can mount after open animation; retry briefly.
      if (attempts < 5) timeoutId = setTimeout(_attemptScroll, 100);
    };
    timeoutId = setTimeout(_attemptScroll, 0);
    return function () {
      var _highlightedCard, _blinkedPermissionCar;
      clearTimeout(timeoutId);
      clearTimeout(highlightTimeoutId);
      clearTimeout(blinkTimeoutId);
      clearTimeout(scrollEndTimeoutId);
      (_highlightedCard = highlightedCard) === null || _highlightedCard === void 0 || _highlightedCard.classList.remove(activeClassName);
      (_blinkedPermissionCar = blinkedPermissionCard) === null || _blinkedPermissionCar === void 0 || _blinkedPermissionCar.classList.remove(blinkClassName);
    };
  }, [isOpen, scrollTo, selectedRole === null || selectedRole === void 0 ? void 0 : selectedRole.id]);
  return /*#__PURE__*/jsxs(Pane, {
    isOpen: isOpen,
    onClose: onClose,
    initialFocusRef: !isEdit ? inputReference : undefined,
    size: "large",
    children: [/*#__PURE__*/jsx(Pane.Header, {
      children: /*#__PURE__*/jsx(Typography, {
        "data-testid": "ntm-add-role-title",
        style: "h2",
        children: isEdit ? t("neetoTeamMembers.labels.editRole") : t("neetoTeamMembers.labels.addNewRole")
      })
    }), /*#__PURE__*/jsx(Form, {
      formikProps: formikProps,
      ref: formReference,
      children: function children(_ref3) {
        var _config$permissionRel;
        var dirty = _ref3.dirty;
        return /*#__PURE__*/jsxs(Fragment, {
          children: [/*#__PURE__*/jsx(ScrollToErrorField, {
            formRef: formReference
          }), /*#__PURE__*/jsx(Pane.Body, {
            children: /*#__PURE__*/jsxs("div", {
              className: "ntm-roles-pane__body",
              children: [/*#__PURE__*/jsxs("div", {
                className: "ntm-roles-pane__body-wrapper",
                children: [/*#__PURE__*/jsx(Input, {
                  required: true,
                  unlimitedChars: true,
                  "data-testid": "ntm-add-role-name-text-field",
                  label: t("neetoTeamMembers.common.name"),
                  maxLength: ROLE_NAME_MAX_LENGTH,
                  name: "name",
                  placeholder: t("neetoTeamMembers.placeholders.enterName"),
                  readOnly: isReadOnly,
                  ref: inputReference
                }), /*#__PURE__*/jsx(Textarea, {
                  unlimitedChars: true,
                  "data-testid": "ntm-add-role-description-text-field",
                  label: t("neetoTeamMembers.common.description"),
                  maxLength: ROLE_DESCRIPTION_MAX_LENGTH,
                  name: "description",
                  readOnly: isDisabled,
                  placeholder: t("neetoTeamMembers.placeholders.enterDescription")
                })]
              }), /*#__PURE__*/jsx(Permissions, {
                isDisabled: isDisabled,
                permissions: permissions,
                permissionRelationConfig: (_config$permissionRel = config === null || config === void 0 ? void 0 : config.permissionRelation) !== null && _config$permissionRel !== void 0 ? _config$permissionRel : {}
              })]
            })
          }), /*#__PURE__*/jsx(Pane.Footer, {
            children: /*#__PURE__*/jsx(ActionBlock, {
              isSubmitting: isSubmitting,
              className: "ntm-roles-pane__footer",
              cancelButtonProps: {
                "data-testid": "ntm-add-role-cancel-button",
                onClick: onClose
              },
              submitButtonProps: {
                "data-testid": "ntm-add-role-submit-button",
                disabled: isSubmitting || isDisabled || !dirty
              }
            })
          })]
        });
      }
    })]
  });
};

var DEFAULT_MANAGE_ROLE_VALUES = {
  isDelete: false,
  isEdit: false,
  selectedRole: {},
  scrollTo: null
};
var MENU_ITEMS = {
  EDIT: "edit",
  DELETE: "delete"
};

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: true } : { done: false, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = true, u = false; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = true, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var _deepClone = function deepClone(object) {
  if (!object || true === object) {
    //this also handles boolean as true and false
    return object;
  }
  var objectType = _typeof(object);
  if ("number" === objectType || "string" === objectType) {
    // add your immutables here
    return object;
  }
  var result = null;
  if (Array.isArray(object)) {
    result = [];
  } else if (!object.constructor) {
    result = {};
  } else {
    result = new object.constructor();
  }
  if (object instanceof Map) {
    var _iterator = _createForOfIteratorHelper(object.keys()),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var key = _step.value;
        result.set(key, _deepClone(object.get(key)));
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }
  Object.keys(object).forEach(function (key) {
    if (Object.prototype.hasOwnProperty.call(object, key)) {
      result[key] = _deepClone(object[key]);
    }
  });
  return result;
};
var renderRolesTooltipContent = function renderRolesTooltipContent(roleName) {
  return Object.is(roleName, "Admin") || Object.is(roleName, "Owner") ? t("neetoTeamMembers.tooltips.adminMustHaveAccess", {
    roleName: roleName
  }) : t("neetoTeamMembers.tooltips.noPermissionToEditRoles");
};
var updatePermissionVisibility = function updatePermissionVisibility(categoryName, permissions) {
  var category = permissions.get(categoryName);
  var isPermissionVisible = category.get("isPermissionVisible");
  category.set("isPermissionVisible", !isPermissionVisible);
  return new Map(permissions.set(categoryName, category));
};
var filterPermissionsBySearch = function filterPermissionsBySearch(searchTerm, permissionGroups) {
  var newValue = _deepClone(permissionGroups);
  newValue.forEach(function (value) {
    var permissions = value.get("permissions");
    var filteredPermissions = permissions.filter(function (permission) {
      var _permission$descripti;
      return permission === null || permission === void 0 || (_permission$descripti = permission.description) === null || _permission$descripti === void 0 || (_permission$descripti = _permission$descripti.toLowerCase()) === null || _permission$descripti === void 0 || (_permission$descripti = _permission$descripti.trim()) === null || _permission$descripti === void 0 ? void 0 : _permission$descripti.includes(searchTerm.toLowerCase().trim());
    });
    value.set("permissions", filteredPermissions);
  });
  return newValue;
};
var getMenuItems = function getMenuItems(_ref) {
  var isDeletePermissionGranted = _ref.isDeletePermissionGranted,
    isUpdatePermissionGranted = _ref.isUpdatePermissionGranted,
    role = _ref.role,
    setManageRole = _ref.setManageRole,
    isSystemRole = _ref.isSystemRole;
  return [{
    key: MENU_ITEMS.EDIT,
    className: "ntm-dropdown__button",
    "data-testid": "ntm-roles-table-edit-role-button",
    isDisabled: not(isUpdatePermissionGranted),
    size: "small",
    tooltipProps: {
      content: t("neetoTeamMembers.tooltips.noPermissionToEditRoles"),
      disabled: isUpdatePermissionGranted,
      position: "left"
    },
    label: t("neetoTeamMembers.common.edit"),
    onClick: function onClick() {
      return setManageRole({
        isEdit: true,
        selectedRole: role,
        scrollTo: null
      });
    }
  }, {
    key: MENU_ITEMS.DELETE,
    className: "ntm-dropdown__button",
    "data-testid": "ntm-roles-table-delete-role-button",
    isDisabled: not(isDeletePermissionGranted),
    size: "small",
    isVisible: not(isSystemRole),
    tooltipProps: {
      content: t("neetoTeamMembers.tooltips.noPermissionToRemoveRoles"),
      disabled: isDeletePermissionGranted,
      position: "left"
    },
    label: t("neetoTeamMembers.common.delete"),
    onClick: function onClick() {
      return setManageRole({
        isDelete: true,
        selectedRole: role,
        scrollTo: null
      });
    }
  }];
};
var getRowClientHeight = function getRowClientHeight(permission) {
  var sidebarItems = Array.from(document.querySelectorAll(".ntm-roles-table-sidebar__list-item:not(.ntm-roles-table-sidebar__list-item--highlighted)"));
  var sidebarItem = _findBy({
    dataset: {
      name: permission === null || permission === void 0 ? void 0 : permission.description
    }
  }, sidebarItems);
  return sidebarItem === null || sidebarItem === void 0 ? void 0 : sidebarItem.clientHeight;
};

var Row = function Row(_ref) {
  var _ref$allPermissionsOf = _ref.allPermissionsOfCategory,
    allPermissionsOfCategory = _ref$allPermissionsOf === void 0 ? null : _ref$allPermissionsOf,
    _ref$category = _ref.category,
    category = _ref$category === void 0 ? "" : _ref$category,
    config = _ref.config,
    _ref$permission = _ref.permission,
    permission = _ref$permission === void 0 ? null : _ref$permission,
    roles = _ref.roles,
    _ref$setManageRole = _ref.setManageRole,
    setManageRole = _ref$setManageRole === void 0 ? noop : _ref$setManageRole;
  var isUpdatePermissionGranted = config.permissions.update;
  var permissions = (allPermissionsOfCategory === null || allPermissionsOfCategory === void 0 ? void 0 : allPermissionsOfCategory.get("permissions")) || [];
  var allPermissionIdsOfCategory = map(prop("id"), permissions);
  var handleSubmit = function handleSubmit(role) {
    var scrollTo = permission !== null && permission !== void 0 && permission.id ? {
      type: "permission",
      permissionId: permission.id
    } : {
      type: "category",
      category: category
    };
    setManageRole({
      isEdit: true,
      selectedRole: role,
      scrollTo: scrollTo
    });
  };
  var isCheckboxChecked = function isCheckboxChecked(role) {
    return !allPermissionsOfCategory ? includes(permission === null || permission === void 0 ? void 0 : permission.id, role.permissionIds) : allPermissionIdsOfCategory.every(includes(__, role.permissionIds));
  };
  return /*#__PURE__*/jsx("div", {
    className: classnames("ntm-roles-table__row", {
      "ntm-roles-table__row--highlighted": !!allPermissionsOfCategory
    }),
    children: roles.map(function (role) {
      return /*#__PURE__*/jsx("div", {
        className: "ntm-roles-table__cell",
        "data-testid": "".concat(hyphenate(role.name), "-role-cell"),
        style: {
          height: getRowClientHeight(permission)
        },
        children: /*#__PURE__*/jsx(Tooltip, {
          content: renderRolesTooltipContent(role.name),
          position: "top",
          disabled: isUpdatePermissionGranted && !identical(role.name, "Admin") && !identical(role.name, "Owner"),
          children: /*#__PURE__*/jsx("div", {
            className: "ntm-roles-table-cell__checkbox-wrapper",
            children: /*#__PURE__*/jsx(Checkbox, {
              checked: isCheckboxChecked(role),
              className: "ntm-roles-table-cell__checkbox",
              "data-testid": "ntm-roles-table-permission-checkbox",
              disabled: identical(role.name, "Admin") || identical(role.name, "Owner") || !isUpdatePermissionGranted,
              onChange: function onChange() {
                return handleSubmit(role);
              }
            })
          })
        })
      }, role.id);
    })
  });
};

var _renderDescription = function renderDescription(permissions, filteredPermissions) {
  var permissionTooltip = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  return permissions === null || permissions === void 0 ? void 0 : permissions.map(function (_ref) {
    var id = _ref.id,
      name = _ref.name,
      description = _ref.description,
      children = _ref.children;
    var tooltipContent = permissionTooltip[name];
    return /*#__PURE__*/jsxs(Fragment$1, {
      children: [filteredPermissions.includes(id) && /*#__PURE__*/jsxs("div", {
        className: "ntm-roles-table-sidebar__list-item",
        "data-name": description,
        children: [/*#__PURE__*/jsx(Typography, {
          "data-testid": "ntm-permission-category-description",
          lineHeight: "normal",
          style: "body2",
          children: description
        }), tooltipContent && /*#__PURE__*/jsx(HelpPopover, {
          description: tooltipContent,
          icon: InfoRound,
          size: "default"
        })]
      }), /*#__PURE__*/jsx("div", {
        className: "neeto-ui-relative neeto-ui-pl-6 ntm-roles-table-sidebar__sub-blocks",
        children: _renderDescription(children, filteredPermissions, permissionTooltip)
      })]
    }, id);
  });
};
var getSearchWrapperStyle = function getSearchWrapperStyle() {
  var scrollBarWidth = getScrollBarWidth();
  document.documentElement.style.setProperty("--ntm-roles-table-default-scroll", "".concat(scrollBarWidth, "px"));
  return {
    marginBottom: "".concat(scrollBarWidth, "px")
  };
};
var getFilteredCategories = function getFilteredCategories(filteredGroupPermissions) {
  return Array.from((filteredGroupPermissions === null || filteredGroupPermissions === void 0 ? void 0 : filteredGroupPermissions.keys()) || []).filter(function (category) {
    var groupedPermissions = filteredGroupPermissions.get(category);
    var permissions = groupedPermissions.get("permissions") || [];
    return permissions.length > 0;
  });
};

var TableHeader$1 = function TableHeader(_ref) {
  var config = _ref.config,
    roles = _ref.roles,
    setManageRole = _ref.setManageRole,
    setIsScrollPresent = _ref.setIsScrollPresent;
  var isUpdatePermissionGranted = config.permissions.update;
  var isDeletePermissionGranted = config.permissions["delete"];
  var scrollSyncElement = useRef(null);
  var getOverflowStatus = useCallback(function () {
    if (!scrollSyncElement.current) return;
    var headerElement = scrollSyncElement.current.node;
    var isScrollBarPresent = isOverflown(headerElement);
    setIsScrollPresent(isScrollBarPresent);
  }, [setIsScrollPresent]);
  useEffect(function () {
    addEventListener("resize", getOverflowStatus);
    return function () {
      return removeEventListener("resize", getOverflowStatus);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(getOverflowStatus, [getOverflowStatus, scrollSyncElement, roles]);
  return /*#__PURE__*/jsx(distExports.ScrollSyncPane, {
    group: "horizontal",
    ref: scrollSyncElement,
    children: /*#__PURE__*/jsx("div", {
      className: "ntm-roles-table__header",
      "data-testid": "ntm-roles-table-header",
      children: roles === null || roles === void 0 ? void 0 : roles.map(function (role, index) {
        var isSystemRole = identical("system", role.kind);
        var isAdminRole = ADMIN_ROLES.includes(role.name) && isSystemRole;
        return /*#__PURE__*/jsx("div", {
          className: "ntm-roles-table__cell",
          children: /*#__PURE__*/jsxs("div", {
            className: "ntm-roles-table-header-cell__container",
            "data-testid": "ntm-roles-table-role-header",
            children: [/*#__PURE__*/jsx(Typography, {
              className: "ntm-roles-table-header__role-name",
              "data-testid": "ntm-roles-table-header-role-title",
              lineHeight: "normal",
              style: "h4",
              weight: "semibold",
              children: role.name
            }), !isAdminRole && /*#__PURE__*/jsx(MoreDropdown, {
              dropdownProps: {
                autoWidth: true
              },
              dropdownButtonProps: {
                className: "ntm-roles-table-header__dropdown",
                "data-testid": "ntm-roles-table-header-role-dropdown-button"
              },
              menuItems: getMenuItems({
                isDeletePermissionGranted: isDeletePermissionGranted,
                isUpdatePermissionGranted: isUpdatePermissionGranted,
                role: role,
                setManageRole: setManageRole,
                isSystemRole: isSystemRole
              })
            })]
          })
        }, "ntm-roles-".concat(index));
      })
    })
  });
};
var TableHeader = /*#__PURE__*/memo(TableHeader$1);

var Delete = function Delete(_ref) {
  var isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    selectedRole = _ref.selectedRole,
    roles = _ref.roles;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useDestroyRole = useDestroyRole({
      onSuccess: onClose
    }),
    deleteRole = _useDestroyRole.mutate,
    isDeleting = _useDestroyRole.isPending;
  var handleDelete = function handleDelete() {
    var _roles$find;
    var id = selectedRole.id;
    var payload = {
      newRoleId: (_roles$find = roles.find(function (role) {
        return role.id !== id;
      })) === null || _roles$find === void 0 ? void 0 : _roles$find.id
    };
    deleteRole({
      id: id,
      payload: payload
    });
  };
  return /*#__PURE__*/jsx(Alert, {
    isOpen: isOpen,
    onClose: onClose,
    cancelButtonLabel: t("neetoTeamMembers.buttons.cancel"),
    isSubmitting: isDeleting,
    submitButtonLabel: t("neetoTeamMembers.buttons.delete"),
    title: t("neetoTeamMembers.labels.deleteRole"),
    message: /*#__PURE__*/jsx(Trans, {
      i18nKey: "neetoTeamMembers.alerts.messages.deletingRole",
      values: {
        name: selectedRole === null || selectedRole === void 0 ? void 0 : selectedRole.name
      }
    }),
    onSubmit: handleDelete
  });
};

var Columns = function Columns(_ref) {
  var config = _ref.config,
    filteredGroupPermissions = _ref.filteredGroupPermissions,
    filteredRoles = _ref.filteredRoles,
    permissions = _ref.permissions,
    roles = _ref.roles,
    setIsScrollPresent = _ref.setIsScrollPresent;
  var _useState = useState(DEFAULT_MANAGE_ROLE_VALUES),
    _useState2 = _slicedToArray(_useState, 2),
    manageRole = _useState2[0],
    setManageRole = _useState2[1];
  var categories = useMemo(function () {
    return getFilteredCategories(filteredGroupPermissions);
  }, [filteredGroupPermissions]);
  var onClose = function onClose() {
    return setManageRole(DEFAULT_MANAGE_ROLE_VALUES);
  };
  return /*#__PURE__*/jsxs("div", {
    className: "ntm-roles-table__columns",
    children: [/*#__PURE__*/jsx(TableHeader, {
      config: config,
      setIsScrollPresent: setIsScrollPresent,
      setManageRole: setManageRole,
      roles: filteredRoles
    }), /*#__PURE__*/jsx(distExports.ScrollSyncPane, {
      group: ["horizontal", "vertical"],
      children: /*#__PURE__*/jsx("div", {
        className: "ntm-roles-table__rows",
        children: categories.length === 0 ? /*#__PURE__*/jsx("div", {
          className: "ntm-roles-table__empty-row",
          children: /*#__PURE__*/jsx("div", {
            className: "ntm-roles-table__row",
            children: /*#__PURE__*/jsx("div", {
              className: "ntm-roles-table__cell",
              children: /*#__PURE__*/jsx("div", {
                className: "ntm-roles-table__cell-content",
                children: "\xA0"
              })
            })
          })
        }) : categories.map(function (category, index) {
          var groupedPermissions = filteredGroupPermissions.get(category);
          var isPermissionVisible = groupedPermissions.get("isPermissionVisible");
          var permissions = groupedPermissions.get("permissions");
          return /*#__PURE__*/jsxs("div", {
            "data-testid": "".concat(hyphenate(category), "-permission-card"),
            children: [/*#__PURE__*/jsx(Row, {
              category: category,
              config: config,
              setManageRole: setManageRole,
              allPermissionsOfCategory: groupedPermissions,
              roles: filteredRoles
            }), isPermissionVisible && permissions.map(function (permission) {
              return /*#__PURE__*/createElement(Row, {
                config: config,
                permission: permission,
                setManageRole: setManageRole,
                "data-testid": "".concat(hyphenate(permission), "-permission-row"),
                key: permission.id,
                roles: filteredRoles
              });
            })]
          }, index);
        })
      })
    }), /*#__PURE__*/jsx(ManageRoles, {
      config: config,
      onClose: onClose,
      permissions: permissions,
      isOpen: manageRole.isEdit,
      scrollTo: manageRole.scrollTo,
      selectedRole: manageRole.selectedRole
    }), /*#__PURE__*/jsx(Delete, {
      onClose: onClose,
      roles: roles,
      isOpen: manageRole.isDelete,
      selectedRole: manageRole.selectedRole
    })]
  });
};

var ToggleDropdown = function ToggleDropdown(_ref) {
  var isVisible = _ref.isVisible;
  return isVisible ? /*#__PURE__*/jsx(Up, {
    className: "ntm-roles-table-sidebar__drop-down-button",
    "data-testid": "ntm-permission-category-hide-button",
    size: 16,
    strokeWidth: 2
  }) : /*#__PURE__*/jsx(Down, {
    className: "ntm-roles-table-sidebar__drop-down-button",
    "data-testid": "ntm-permission-category-show-button",
    size: 16,
    strokeWidth: 2
  });
};

var Sidebar = function Sidebar(_ref) {
  var filteredGroupPermissions = _ref.filteredGroupPermissions,
    toggleDropdown = _ref.toggleDropdown,
    isScrollPresent = _ref.isScrollPresent,
    _ref$permissions = _ref.permissions,
    permissions = _ref$permissions === void 0 ? [] : _ref$permissions,
    _ref$permissionRelati = _ref.permissionRelationConfig,
    permissionRelationConfig = _ref$permissionRelati === void 0 ? {} : _ref$permissionRelati,
    _ref$permissionToolti = _ref.permissionTooltip,
    permissionTooltip = _ref$permissionToolti === void 0 ? {} : _ref$permissionToolti;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var categories = useMemo(function () {
    return getFilteredCategories(filteredGroupPermissions);
  }, [filteredGroupPermissions]);
  var searchWrapperStyle = isScrollPresent ? getSearchWrapperStyle() : {};
  var permissionsNameMap = groupBy(prop("name"))(permissions);
  var groupedPermissionsWithChildren = useMemo(function () {
    var childrenRemovedFromRoot = getChildrenRemovedFromRoot({
      permissions: permissions,
      permissionsNameMap: permissionsNameMap,
      permissionRelationConfig: permissionRelationConfig
    });
    return groupBy(prop("category"))(childrenRemovedFromRoot);
  }, [permissions]);
  return /*#__PURE__*/jsxs("div", {
    className: "ntm-roles-table__sidebar",
    children: [/*#__PURE__*/jsx("div", {
      className: "ntm-roles-table-sidebar__search",
      style: searchWrapperStyle,
      children: /*#__PURE__*/jsx(Search, {
        enableUrlSync: true,
        "data-testid": "ntm-search-permissions-input",
        searchParamName: "permission_search_term",
        placeholder: t("neetoTeamMembers.placeholders.searchPermission", PLURAL)
      })
    }), /*#__PURE__*/jsx(distExports.ScrollSyncPane, {
      group: "vertical",
      children: /*#__PURE__*/jsx("div", {
        className: "ntm-roles-table-sidebar__list",
        children: categories.length === 0 ? /*#__PURE__*/jsx("div", {
          className: "ntm-roles-table-sidebar__list-item-cell",
          children: /*#__PURE__*/jsx("div", {
            className: "ntm-roles-table-sidebar__list-item ntm-roles-table-sidebar__list-item--highlighted",
            children: /*#__PURE__*/jsx(Typography, {
              "data-testid": "ntm-empty-category-row",
              lineHeight: "normal",
              style: "body2",
              weight: "semibold",
              children: t("neetoTeamMembers.labels.permissionsNotFound")
            })
          })
        }) : categories.map(function (category, index) {
          var groupedPermissions = filteredGroupPermissions.get(category);
          var isPermissionVisible = groupedPermissions.get("isPermissionVisible");
          return /*#__PURE__*/jsxs("div", {
            className: "ntm-roles-table-sidebar__list-item-cell",
            children: [/*#__PURE__*/jsxs("div", {
              className: "ntm-roles-table-sidebar__list-item ntm-roles-table-sidebar__list-item--highlighted cursor-pointer",
              onClick: function onClick() {
                return toggleDropdown(category);
              },
              children: [/*#__PURE__*/jsx(Typography, {
                className: "ntm-roles-table-sidebar__list-item-title",
                "data-testid": "ntm-permission-category-title",
                lineHeight: "normal",
                style: "h4",
                weight: "semibold",
                children: category
              }), /*#__PURE__*/jsx(ToggleDropdown, {
                isVisible: isPermissionVisible
              })]
            }), isPermissionVisible && /*#__PURE__*/jsx("div", {
              className: "ntm-roles-table-sidebar__list-item-spacing-handler ms-[12px] px-[24px]",
              children: _renderDescription(groupedPermissionsWithChildren[category], pluck("id", filteredGroupPermissions.get(category).get("permissions") || []), permissionTooltip)
            })]
          }, index);
        })
      })
    })]
  });
};

var Table = function Table(_ref) {
  var _config$permissionRel, _config$permissionToo;
  var config = _ref.config,
    filteredRoles = _ref.filteredRoles,
    roles = _ref.roles,
    permissionGroups = _ref.permissionGroups,
    permissions = _ref.permissions,
    setModifiedRoles = _ref.setModifiedRoles,
    setIsNewRolePaneOpen = _ref.setIsNewRolePaneOpen;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useQueryParams = useQueryParams(),
    _useQueryParams$permi = _useQueryParams.permissionSearchTerm,
    permissionSearchTerm = _useQueryParams$permi === void 0 ? "" : _useQueryParams$permi;
  var isCreatePermissionGranted = config.permissions.create;
  var _useState = useState(permissionGroups),
    _useState2 = _slicedToArray(_useState, 2),
    filteredGroupPermissions = _useState2[0],
    setFilteredGroupPermissions = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isScrollPresent = _useState4[0],
    setIsScrollPresent = _useState4[1];
  var _useState5 = useState(undefined),
    _useState6 = _slicedToArray(_useState5, 2),
    selectedRole = _useState6[0],
    setSelectedRole = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    isDeleteAlertOpen = _useState8[0],
    setIsDeleteAlertOpen = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    isEditPaneOpen = _useState10[0],
    setIsEditPaneOpen = _useState10[1];
  var toggleDropdown = function toggleDropdown(category) {
    var permissions = updatePermissionVisibility(category, filteredGroupPermissions);
    setFilteredGroupPermissions(permissions);
  };
  useEffect(function () {
    var newValue = filterPermissionsBySearch(permissionSearchTerm, permissionGroups);
    setFilteredGroupPermissions(newValue);
  }, [permissionGroups, permissionSearchTerm]);
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsx("div", {
      className: "ntm-roles-table__wrapper",
      children: /*#__PURE__*/jsx("div", {
        className: "ntm-roles-table__container",
        children: isEmpty(filteredRoles) ? /*#__PURE__*/jsx("div", {
          className: "ntm-empty-state",
          children: /*#__PURE__*/jsx(NoData, {
            title: t("neetoTeamMembers.labels.roleNotFound", PLURAL),
            primaryButtonProps: {
              "data-testid": "ntm-add-role-button",
              disabled: !isCreatePermissionGranted,
              label: t("neetoTeamMembers.labels.addNewRole"),
              onClick: function onClick() {
                return setIsNewRolePaneOpen(true);
              }
            }
          })
        }) : /*#__PURE__*/jsxs(Fragment, {
          children: [/*#__PURE__*/jsx(Sidebar, {
            filteredGroupPermissions: filteredGroupPermissions,
            isScrollPresent: isScrollPresent,
            permissions: permissions,
            toggleDropdown: toggleDropdown,
            permissionRelationConfig: (_config$permissionRel = config === null || config === void 0 ? void 0 : config.permissionRelation) !== null && _config$permissionRel !== void 0 ? _config$permissionRel : {},
            permissionTooltip: (_config$permissionToo = config === null || config === void 0 ? void 0 : config.permissionTooltip) !== null && _config$permissionToo !== void 0 ? _config$permissionToo : {}
          }), /*#__PURE__*/jsx(Columns, {
            config: config,
            filteredGroupPermissions: filteredGroupPermissions,
            filteredRoles: filteredRoles,
            permissions: permissions,
            roles: roles,
            setIsScrollPresent: setIsScrollPresent,
            setModifiedRoles: setModifiedRoles
          })]
        })
      })
    }), /*#__PURE__*/jsx(ManageRoles, {
      config: config,
      permissions: permissions,
      selectedRole: selectedRole,
      isOpen: isEditPaneOpen,
      onClose: function onClose() {
        setSelectedRole(undefined);
        setIsEditPaneOpen(false);
      }
    }), /*#__PURE__*/jsx(Delete, {
      roles: roles,
      selectedRole: selectedRole,
      isOpen: isDeleteAlertOpen,
      onClose: function onClose() {
        setSelectedRole(undefined);
        setIsDeleteAlertOpen(false);
      }
    })]
  });
};

var Roles = function Roles(_ref) {
  var config = _ref.config;
  var isViewPermissionGranted = config.permissions.view;
  var isUpdatePermissionGranted = config.permissions.update;
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    modifiedRoles = _useState2[0],
    setModifiedRoles = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isNewRolePaneOpen = _useState4[0],
    setIsNewRolePaneOpen = _useState4[1];
  var _useFetchRoles = useFetchRoles({
      enabled: isViewPermissionGranted
    }),
    _useFetchRoles$data = _useFetchRoles.data,
    roles = _useFetchRoles$data === void 0 ? [] : _useFetchRoles$data,
    isRolesLoading = _useFetchRoles.isLoading,
    status = _useFetchRoles.status;
  var _useQueryParams = useQueryParams(),
    _useQueryParams$searc = _useQueryParams.searchTerm,
    searchTerm = _useQueryParams$searc === void 0 ? "" : _useQueryParams$searc;
  var _useFetchPermissions = useFetchPermissions({
      enabled: isViewPermissionGranted
    }),
    permissionData = _useFetchPermissions.data,
    isPermissionsLoading = _useFetchPermissions.isLoading;
  var _useBulkUpdateRoles = useBulkUpdateRoles({
      enabled: isUpdatePermissionGranted
    }),
    bulkUpdate = _useBulkUpdateRoles.mutate;
  var permissions = sortPermissionsBySequence(permissionData);
  var permissionGroups = getPermissionGroups(permissions);
  var filteredRoles = filter(function (_ref2) {
    var name = _ref2.name;
    return includes(searchTerm.toLowerCase().trim(), name.toLowerCase().trim());
  }, isNotEmpty(modifiedRoles) ? modifiedRoles : roles);
  var handleSubmit = function handleSubmit() {
    var updatedRoles = getModifiedPermissions(roles, modifiedRoles);
    bulkUpdate({
      organizationRoles: {
        updatedRoles: updatedRoles
      }
    });
  };
  var handleReset = function handleReset() {
    return setModifiedRoles(roles);
  };
  useEffect(function () {
    if (status !== "success") return;
    setModifiedRoles(roles);
  }, [roles, status]);
  if (isRolesLoading || isPermissionsLoading) {
    return /*#__PURE__*/jsx("div", {
      className: "flex h-full min-h-screen w-full items-center justify-center",
      children: /*#__PURE__*/jsx(Spinner, {})
    });
  }
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsx(distExports.ScrollSync, {
      children: /*#__PURE__*/jsxs(Container, {
        isHeaderFixed: true,
        children: [/*#__PURE__*/jsx(Header, {
          config: config,
          handleReset: handleReset,
          handleSubmit: handleSubmit,
          roles: roles,
          setIsNewRolePaneOpen: setIsNewRolePaneOpen
        }), /*#__PURE__*/jsx(Table, {
          config: config,
          filteredRoles: filteredRoles,
          permissionGroups: permissionGroups,
          permissions: permissions,
          roles: roles,
          setIsNewRolePaneOpen: setIsNewRolePaneOpen,
          setModifiedRoles: setModifiedRoles
        })]
      })
    }), /*#__PURE__*/jsx(ManageRoles, {
      config: config,
      permissions: permissions,
      isOpen: isNewRolePaneOpen,
      onClose: function onClose() {
        return setIsNewRolePaneOpen(false);
      }
    })]
  });
};
var index = withTitle(withReactQuery(Roles), i18next.t("neetoTeamMembers.common.role", PLURAL));

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