'use strict';

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var neetoAtoms = require('@bigbinary/neeto-atoms');
var utils = require('../../utils-CcTwXoRH.js');
var i18next = require('i18next');
var neetoCist = require('@bigbinary/neeto-cist');
var constants = require('@bigbinary/neeto-commons-frontend/v2/constants');
var reactUtils = require('@bigbinary/neeto-commons-frontend/v2/react-utils');
var Container = require('@bigbinary/neeto-molecules/v2/Container');
var ramda = require('ramda');
var useRolesApi = require('../../useRolesApi-DuL4eCuF.js');
var injectCss = require('../../inject-css-B6qYtOJe.js');
var NeetoHeader = require('@bigbinary/neeto-molecules/v2/Header');
var reactI18next = require('react-i18next');
var initializers = require('@bigbinary/neeto-commons-frontend/v2/initializers');
var jsxRuntime = require('react/jsx-runtime');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var formik = require('@bigbinary/neeto-atoms/formik');
var constants$1 = require('../../constants-D_H6M1Pm.js');
var yup = require('yup');
var v2_Permissions = require('../../Permissions-LWRAefeb.js');
var ActionBlock = require('../../ActionBlock-C9Iy0jGZ.js');
var Select = require('../../Select-CshPoN2b.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('formik');
var index$1 = require('../../index-BOQKf6as.js');
var lucideReact = require('lucide-react');
var classnames = require('classnames');
require('@babel/runtime/helpers/toConsumableArray');
var _typeof = require('@babel/runtime/helpers/typeof');
var HelpPopover = require('@bigbinary/neeto-molecules/v2/HelpPopover');
var MoreDropdown = require('@bigbinary/neeto-molecules/v2/MoreDropdown');
var Search = require('@bigbinary/neeto-molecules/v2/Search');
var withReactQuery = require('../../withReactQuery-DvSkXhEx.js');
require('../../_commonjsHelpers-BJu3ubxk.js');
require('@tanstack/react-query');
require('axios');
require('@bigbinary/neeto-commons-frontend/react-utils');
require('@bigbinary/neeto-commons-frontend/constants');
require('../../queryClient-4vAFE3bx.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var i18next__default = /*#__PURE__*/_interopDefault(i18next);
var Container__default = /*#__PURE__*/_interopDefault(Container);
var NeetoHeader__default = /*#__PURE__*/_interopDefault(NeetoHeader);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);
var _typeof__default = /*#__PURE__*/_interopDefault(_typeof);
var HelpPopover__default = /*#__PURE__*/_interopDefault(HelpPopover);
var MoreDropdown__default = /*#__PURE__*/_interopDefault(MoreDropdown);
var Search__default = /*#__PURE__*/_interopDefault(Search);

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:3rem}.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:var(--background);display:flex;flex-direction:column;gap:.75rem;padding:.4rem 0;position:relative}.ntm-roles-permission__card:after{background-color:var(--border);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__sub-blocks{position:relative}.ntm-roles-permission__sub-blocks:before{background-color:var(--border);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 var(--border);border-radius:.375rem;border-radius:var(--radius,.375rem);padding:.625rem 1.25rem;transition:all .3s}.ntm-roles-permission-category-card--active{border-color:var(--primary);outline:1px solid var(--primary)}.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}@keyframes ntm-roles-permission-blink{0%,to{color:inherit}50%{color:var(--primary);font-weight:700}}.ntm-roles-permission__card--blink label{animation:ntm-roles-permission-blink .6s ease-in-out 0s 3}.ntm-roles-table__wrapper{padding:0 2.5rem;width:100%}.ntm-roles-table__container{border:1px solid var(--border);border-radius:.5rem;border-radius:var(--radius-lg,.5rem);display:flex;max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - 28px);overflow:hidden}.ntm-roles-table__container>*{max-height:inherit}.ntm-roles-table__sidebar{min-width:480px;min-width:var(--ntm-roles-sidebar-width);width:480px;width:var(--ntm-roles-sidebar-width)}.ntm-roles-table-sidebar__search{background-color:var(--muted);border-bottom:thin solid var(--border);border-right:thin solid var(--border);height:3rem;height:var(--ntm-roles-table-header-height);padding:.5rem 1rem}.ntm-roles-table-sidebar__list{border-right:thin solid var(--border);max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - 3rem - 30px);max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - var(--ntm-roles-table-header-height) - 30px);overflow-x:hidden;overflow-y:auto;scrollbar-width:none}.ntm-roles-table-sidebar__list::-webkit-scrollbar{height:0;width:0}.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:var(--border);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:var(--muted);border-bottom:thin solid var(--border);border-top:thin solid var(--border);flex-direction:row;justify-content:space-between;min-height:3rem;min-height:var(--ntm-roles-table-cell-height);padding:.6875rem 1.5rem}.ntm-roles-table__columns{flex-grow:1;overflow:hidden}.ntm-roles-table__cell{align-items:center;border-inline-end:thin solid var(--border);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:last-child{border-inline-end:none}.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{background-color:var(--muted);border-bottom:thin solid var(--border);height:3rem;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) - 3rem - 30px);max-height:calc(100vh - var(--neeto-molecules-main-header-with-breadcrumbs-height) - var(--ntm-roles-table-header-height) - 30px);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:var(--border);border-radius:3.125rem}.ntm-roles-table__rows::-webkit-scrollbar-thumb:hover{border-radius:3.125rem}.ntm-roles-table__rows::-webkit-scrollbar-track{background:var(--border)}.ntm-roles-table__row{align-items:center;display:flex}.ntm-roles-table__row .ntm-roles-table__cell{border-top:thin solid var(--border);overflow:hidden;position:relative}.ntm-roles-table__row--highlighted+.ntm-roles-table__row .ntm-roles-table__cell{border-top:none}.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:var(--muted);border-bottom:thin solid var(--border)}.ntm-roles-table-sidebar__drop-down-button{color:var(--muted-foreground);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: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:var(--border);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,  */";
injectCss.n(css,{});

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

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

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 = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var isUpdatePermissionGranted = config.permissions.update;
  return /*#__PURE__*/jsxRuntime.jsx(NeetoHeader__default.default, {
    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: neetoCist.isNotEmpty(roles) ? renderSearchProps() : null,
    title: t("neetoTeamMembers.common.role", constants.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__*/jsxRuntime.jsxs("div", {
      className: "flex items-center gap-2",
      children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, {
        position: "bottom",
        content: !isUpdatePermissionGranted ? t("neetoTeamMembers.tooltips.noPermissionToEditRoles") : null,
        children: /*#__PURE__*/jsxRuntime.jsx("span", {
          children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
            "data-testid": "ntm-role-submission-button",
            disabled: !isUpdatePermissionGranted,
            type: "submit",
            onClick: handleSubmit,
            children: t("neetoTeamMembers.buttons.saveChanges")
          })
        })
      }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Button, {
        "data-testid": "ntm-role-reset-button",
        type: "reset",
        variant: "ghost",
        onClick: handleReset,
        children: t("neetoTeamMembers.buttons.reset")
      })]
    }) : /*#__PURE__*/jsxRuntime.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 = yup.object({
  name: yup.string().trim().max(ROLE_NAME_MAX_LENGTH,
  // @ts-ignore
  i18next.t("neetoTeamMembers.validations.nameLimitExceeded", {
    limit: ROLE_NAME_MAX_LENGTH
  }))
  // @ts-ignore
  .required(i18next.t("neetoTeamMembers.validations.enterRoleName")),
  description: yup.string().nullable().trim().max(ROLE_DESCRIPTION_MAX_LENGTH,
  // @ts-ignore
  i18next.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__default.default(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 = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var formReference = React.useRef(null);
  var inputReference = React.useRef(null);
  var lastScrollKeyRef = React.useRef(null);
  var _useCreateRole = useRolesApi.useCreateRole({
      onSuccess: onClose
    }),
    createRole = _useCreateRole.mutate,
    isCreatingRole = _useCreateRole.isPending;
  var _useUpdateRole = useRolesApi.useUpdateRole({
      onSuccess: onClose
    }),
    updateRole = _useUpdateRole.mutate,
    isUpdatingRole = _useUpdateRole.isPending;
  var isEdit = neetoCist.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 = constants$1.ADMIN_ROLES.includes(selectedRole.name) && isReadOnly;
  React.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(neetoCist.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;
      }

      // Sheet 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__*/jsxRuntime.jsxs(neetoAtoms.Sheet, {
    isOpen: isOpen,
    onClose: onClose,
    size: "large",
    children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Sheet.Header, {
      children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Sheet.Title, {
        "data-testid": "ntm-add-role-title",
        children: isEdit ? t("neetoTeamMembers.labels.editRole") : t("neetoTeamMembers.labels.addNewRole")
      })
    }), /*#__PURE__*/jsxRuntime.jsx(Select.FormikForm, {
      formikProps: formikProps,
      className: "flex min-h-0 flex-1 flex-col",
      ref: formReference,
      children: function children(_ref3) {
        var _config$permissionRel;
        var dirty = _ref3.dirty;
        return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
          children: [/*#__PURE__*/jsxRuntime.jsx(index$1.ScrollToErrorField, {
            formRef: formReference
          }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Sheet.Body, {
            children: /*#__PURE__*/jsxRuntime.jsxs("div", {
              className: "mb-6 w-full space-y-6",
              children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
                className: "space-y-4",
                children: [/*#__PURE__*/jsxRuntime.jsx(formik.Input, {
                  required: 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: !isEdit ? inputReference : undefined
                }), /*#__PURE__*/jsxRuntime.jsx(formik.Textarea, {
                  "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__*/jsxRuntime.jsx(v2_Permissions.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__*/jsxRuntime.jsx(neetoAtoms.Sheet.Footer, {
            children: /*#__PURE__*/jsxRuntime.jsx(ActionBlock.FormikActionBlock, {
              isSubmitting: isSubmitting,
              className: "flex gap-2",
              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"
};
var SIDEBAR_CELL_SELECTOR = ".ntm-roles-table-sidebar__list-item-cell";
var COLUMN_ROW_SELECTOR = ".ntm-roles-table__rows > div[data-testid], .ntm-roles-table__empty-row";

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__default.default(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") ? i18next.t("neetoTeamMembers.tooltips.adminMustHaveAccess", {
    roleName: roleName
  }) : i18next.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: ramda.not(isUpdatePermissionGranted),
    size: "small",
    tooltipProps: {
      content: i18next.t("neetoTeamMembers.tooltips.noPermissionToEditRoles"),
      disabled: isUpdatePermissionGranted,
      position: "left"
    },
    label: i18next.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: ramda.not(isDeletePermissionGranted),
    size: "small",
    isVisible: ramda.not(isSystemRole),
    tooltipProps: {
      content: i18next.t("neetoTeamMembers.tooltips.noPermissionToRemoveRoles"),
      disabled: isDeletePermissionGranted,
      position: "left"
    },
    label: i18next.t("neetoTeamMembers.common.delete"),
    onClick: function onClick() {
      return setManageRole({
        isDelete: true,
        selectedRole: role,
        scrollTo: null
      });
    }
  }];
};

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 ? neetoCist.noop : _ref$setManageRole;
  var isUpdatePermissionGranted = config.permissions.update;
  var permissions = (allPermissionsOfCategory === null || allPermissionsOfCategory === void 0 ? void 0 : allPermissionsOfCategory.get("permissions")) || [];
  var allPermissionIdsOfCategory = ramda.map(ramda.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 ? ramda.includes(permission === null || permission === void 0 ? void 0 : permission.id, role.permissionIds) : allPermissionIdsOfCategory.every(ramda.includes(ramda.__, role.permissionIds));
  };
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: classnames__default.default("ntm-roles-table__row", {
      "ntm-roles-table__row--highlighted": !!allPermissionsOfCategory
    }),
    children: roles.map(function (role) {
      return /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "ntm-roles-table__cell",
        "data-testid": "".concat(neetoCist.hyphenate(role.name), "-role-cell"),
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Tooltip, {
          position: "top",
          content: !(isUpdatePermissionGranted && !ramda.identical(role.name, "Admin") && !ramda.identical(role.name, "Owner")) ? renderRolesTooltipContent(role.name) : null,
          children: /*#__PURE__*/jsxRuntime.jsx("div", {
            className: "absolute z-10 m-auto size-4",
            children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Checkbox, {
              checked: isCheckboxChecked(role),
              className: "ntm-roles-table-cell__checkbox z-10",
              "data-testid": "ntm-roles-table-permission-checkbox",
              disabled: ramda.identical(role.name, "Admin") || ramda.identical(role.name, "Owner") || !isUpdatePermissionGranted,
              onCheckedChange: function onCheckedChange() {
                return handleSubmit(role);
              }
            })
          })
        })
      }, role.id);
    })
  });
};

var _renderDescription = function renderDescription(permissions, filteredPermissions) {
  var permissionTooltip = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var depth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  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];
    var isChild = depth > 0;
    return /*#__PURE__*/jsxRuntime.jsxs(React.Fragment, {
      children: [filteredPermissions.includes(id) && /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "ntm-roles-table-sidebar__list-item flex min-h-[var(--ntm-roles-table-cell-height)] flex-row items-center gap-1 whitespace-normal break-words",
        "data-name": description,
        children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
          "data-testid": "ntm-permission-category-description",
          variant: isChild ? "body3" : "body2",
          weight: isChild ? "normal" : "medium",
          children: description
        }), tooltipContent && /*#__PURE__*/jsxRuntime.jsx(HelpPopover__default.default, {
          description: tooltipContent,
          icon: lucideReact.Info,
          size: "default"
        })]
      }), /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "ntm-roles-table-sidebar__sub-blocks relative pl-6",
        children: _renderDescription(children, filteredPermissions, permissionTooltip, depth + 1)
      })]
    }, id);
  });
};
var getSearchWrapperStyle = function getSearchWrapperStyle() {
  var scrollBarWidth = utils.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 = 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 = React.useRef(null);
  var getOverflowStatus = React.useCallback(function () {
    if (!scrollSyncElement.current) return;
    var headerElement = scrollSyncElement.current.node;
    var isScrollBarPresent = utils.isOverflown(headerElement);
    setIsScrollPresent(isScrollBarPresent);
  }, [setIsScrollPresent]);
  React.useEffect(function () {
    addEventListener("resize", getOverflowStatus);
    return function () {
      return removeEventListener("resize", getOverflowStatus);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  React.useEffect(getOverflowStatus, [getOverflowStatus, scrollSyncElement, roles]);
  return /*#__PURE__*/jsxRuntime.jsx(utils.distExports.ScrollSyncPane, {
    group: "horizontal",
    ref: scrollSyncElement,
    children: /*#__PURE__*/jsxRuntime.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 = ramda.identical("system", role.kind);
        var isAdminRole = constants$1.ADMIN_ROLES.includes(role.name) && isSystemRole;
        return /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "ntm-roles-table__cell",
          children: /*#__PURE__*/jsxRuntime.jsxs("div", {
            className: "flex w-full items-center justify-between overflow-hidden",
            "data-testid": "ntm-roles-table-role-header",
            children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
              className: "w-full text-center",
              "data-testid": "ntm-roles-table-header-role-title",
              lineClamp: 1,
              variant: "body3",
              weight: "semibold",
              children: role.name
            }), !isAdminRole && /*#__PURE__*/jsxRuntime.jsx(MoreDropdown__default.default, {
              dropdownButtonProps: {
                className: "m-0.5 shrink-0",
                "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$1 = /*#__PURE__*/React.memo(TableHeader);

var Delete = function Delete(_ref) {
  var isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    selectedRole = _ref.selectedRole,
    roles = _ref.roles;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useDestroyRole = useRolesApi.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__*/jsxRuntime.jsx(neetoAtoms.Alert, {
    isOpen: isOpen,
    onClose: onClose,
    cancelButtonLabel: t("neetoTeamMembers.buttons.cancel"),
    isSubmitting: isDeleting,
    submitButtonLabel: t("neetoTeamMembers.buttons.delete"),
    title: t("neetoTeamMembers.labels.deleteRole"),
    message: /*#__PURE__*/jsxRuntime.jsx(reactI18next.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 = React.useState(DEFAULT_MANAGE_ROLE_VALUES),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    manageRole = _useState2[0],
    setManageRole = _useState2[1];
  var categories = React.useMemo(function () {
    return getFilteredCategories(filteredGroupPermissions);
  }, [filteredGroupPermissions]);
  var onClose = function onClose() {
    return setManageRole(DEFAULT_MANAGE_ROLE_VALUES);
  };
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "ntm-roles-table__columns",
    children: [/*#__PURE__*/jsxRuntime.jsx(TableHeader$1, {
      config: config,
      setIsScrollPresent: setIsScrollPresent,
      setManageRole: setManageRole,
      roles: filteredRoles
    }), /*#__PURE__*/jsxRuntime.jsx(utils.distExports.ScrollSyncPane, {
      group: ["horizontal", "vertical"],
      children: /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "ntm-roles-table__rows",
        children: categories.length === 0 ? /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "ntm-roles-table__empty-row",
          children: /*#__PURE__*/jsxRuntime.jsx("div", {
            className: "ntm-roles-table__row",
            children: /*#__PURE__*/jsxRuntime.jsx("div", {
              className: "ntm-roles-table__cell",
              children: /*#__PURE__*/jsxRuntime.jsx("div", {
                children: "\xA0"
              })
            })
          })
        }) : categories.map(function (category, index) {
          var groupedPermissions = filteredGroupPermissions.get(category);
          var isPermissionVisible = groupedPermissions.get("isPermissionVisible");
          var permissions = groupedPermissions.get("permissions");
          return /*#__PURE__*/jsxRuntime.jsxs("div", {
            "data-testid": "".concat(neetoCist.hyphenate(category), "-permission-card"),
            children: [/*#__PURE__*/jsxRuntime.jsx(Row, {
              category: category,
              config: config,
              setManageRole: setManageRole,
              allPermissionsOfCategory: groupedPermissions,
              roles: filteredRoles
            }), isPermissionVisible && permissions.map(function (permission) {
              return /*#__PURE__*/React.createElement(Row, {
                config: config,
                permission: permission,
                setManageRole: setManageRole,
                "data-testid": "".concat(neetoCist.hyphenate(permission), "-permission-row"),
                key: permission.id,
                roles: filteredRoles
              });
            })]
          }, index);
        })
      })
    }), /*#__PURE__*/jsxRuntime.jsx(ManageRoles, {
      config: config,
      onClose: onClose,
      permissions: permissions,
      isOpen: manageRole.isEdit,
      scrollTo: manageRole.scrollTo,
      selectedRole: manageRole.selectedRole
    }), /*#__PURE__*/jsxRuntime.jsx(Delete, {
      onClose: onClose,
      roles: roles,
      isOpen: manageRole.isDelete,
      selectedRole: manageRole.selectedRole
    })]
  });
};

var ToggleDropdown = function ToggleDropdown(_ref) {
  var isVisible = _ref.isVisible;
  return isVisible ? /*#__PURE__*/jsxRuntime.jsx(lucideReact.ChevronUp, {
    className: "ntm-roles-table-sidebar__drop-down-button cursor-pointer text-muted-foreground",
    "data-testid": "ntm-permission-category-hide-button",
    size: 16,
    strokeWidth: 2
  }) : /*#__PURE__*/jsxRuntime.jsx(lucideReact.ChevronDown, {
    className: "ntm-roles-table-sidebar__drop-down-button cursor-pointer text-muted-foreground",
    "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 = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var categories = React.useMemo(function () {
    return getFilteredCategories(filteredGroupPermissions);
  }, [filteredGroupPermissions]);
  var searchWrapperStyle = isScrollPresent ? getSearchWrapperStyle() : {};
  var permissionsNameMap = ramda.groupBy(ramda.prop("name"))(permissions);
  var groupedPermissionsWithChildren = React.useMemo(function () {
    var childrenRemovedFromRoot = v2_Permissions.getChildrenRemovedFromRoot({
      permissions: permissions,
      permissionsNameMap: permissionsNameMap,
      permissionRelationConfig: permissionRelationConfig
    });
    return ramda.groupBy(ramda.prop("category"))(childrenRemovedFromRoot);
  }, [permissions]); // eslint-disable-line react-hooks/exhaustive-deps

  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "ntm-roles-table__sidebar",
    children: [/*#__PURE__*/jsxRuntime.jsx("div", {
      className: "ntm-roles-table-sidebar__search",
      style: searchWrapperStyle,
      children: /*#__PURE__*/jsxRuntime.jsx(Search__default.default, {
        enableUrlSync: true,
        "data-testid": "ntm-search-permissions-input",
        searchParamName: "permission_search_term",
        placeholder: t("neetoTeamMembers.placeholders.searchPermission", constants.PLURAL)
      })
    }), /*#__PURE__*/jsxRuntime.jsx(utils.distExports.ScrollSyncPane, {
      group: "vertical",
      children: /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "ntm-roles-table-sidebar__list",
        children: categories.length === 0 ? /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "ntm-roles-table-sidebar__list-item-cell",
          children: /*#__PURE__*/jsxRuntime.jsxs("div", {
            className: "ntm-roles-table-sidebar__list-item flex flex-col items-start justify-center gap-1 px-6 py-6",
            children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
              "data-testid": "ntm-empty-category-row",
              variant: "body2",
              weight: "medium",
              children: t("neetoTeamMembers.labels.permissionSearchEmpty")
            }), /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
              color: "muted",
              variant: "body3",
              children: t("neetoTeamMembers.labels.permissionSearchEmptyDescription")
            })]
          })
        }) : categories.map(function (category, index) {
          var groupedPermissions = filteredGroupPermissions.get(category);
          var isPermissionVisible = groupedPermissions.get("isPermissionVisible");
          return /*#__PURE__*/jsxRuntime.jsxs("div", {
            className: "ntm-roles-table-sidebar__list-item-cell",
            children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
              className: "ntm-roles-table-sidebar__list-item ntm-roles-table-sidebar__list-item--highlighted flex cursor-pointer items-center justify-between border-t border-border bg-muted px-6 py-2.5",
              onClick: function onClick() {
                return toggleDropdown(category);
              },
              children: [/*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Typography, {
                "data-testid": "ntm-permission-category-title",
                variant: "h6",
                children: category
              }), /*#__PURE__*/jsxRuntime.jsx(ToggleDropdown, {
                isVisible: isPermissionVisible
              })]
            }), isPermissionVisible && /*#__PURE__*/jsxRuntime.jsx("div", {
              className: "ntm-roles-table-sidebar__list-item-spacing-handler ms-3 px-6",
              children: _renderDescription(groupedPermissionsWithChildren[category], ramda.pluck("id", filteredGroupPermissions.get(category).get("permissions") || []), permissionTooltip)
            })]
          }, index);
        })
      })
    })]
  });
};

var syncRowHeights = function syncRowHeights() {
  var sidebarCells = document.querySelectorAll(SIDEBAR_CELL_SELECTOR);
  var columnRows = document.querySelectorAll(COLUMN_ROW_SELECTOR);
  var count = Math.min(sidebarCells.length, columnRows.length);
  for (var i = 0; i < count; i++) {
    // Reset heights so we can measure natural size
    sidebarCells[i].style.height = "auto";
    var sidebarChildren = sidebarCells[i].children;
    for (var j = 0; j < sidebarChildren.length; j++) {
      sidebarChildren[j].style.height = "auto";
    }
    var columnChildren = columnRows[i].children;
    for (var _j = 0; _j < columnChildren.length; _j++) {
      var cells = columnChildren[_j].querySelectorAll(".ntm-roles-table__cell");
      cells.forEach(function (cell) {
        cell.style.height = "auto";
      });
    }
  }

  // Force reflow before measuring

  document.body.offsetHeight;
  var _loop = function _loop() {
    // For each row group (category header + its permission rows),
    // sync the sidebar cell block with the column row block.
    var sidebarBlock = sidebarCells[_i];
    var columnBlock = columnRows[_i];

    // Sync the category header row (first child of each block)
    var sidebarHeader = sidebarBlock.querySelector(".ntm-roles-table-sidebar__list-item--highlighted");
    var columnHeader = columnBlock.querySelector(".ntm-roles-table__row--highlighted");
    if (sidebarHeader && columnHeader) {
      var _columnHeaderCells$;
      var columnHeaderCells = columnHeader.querySelectorAll(".ntm-roles-table__cell");
      var sidebarH = sidebarHeader.getBoundingClientRect().height;
      var columnH = ((_columnHeaderCells$ = columnHeaderCells[0]) === null || _columnHeaderCells$ === void 0 ? void 0 : _columnHeaderCells$.getBoundingClientRect().height) || 0;
      var maxH = Math.max(sidebarH, columnH);
      sidebarHeader.style.height = "".concat(maxH, "px");
      columnHeaderCells.forEach(function (cell) {
        cell.style.height = "".concat(maxH, "px");
      });
    }

    // Sync individual permission rows
    var sidebarItems = sidebarBlock.querySelectorAll(".ntm-roles-table-sidebar__list-item:not(.ntm-roles-table-sidebar__list-item--highlighted)");
    var columnPermRows = columnBlock.querySelectorAll(".ntm-roles-table__row:not(.ntm-roles-table__row--highlighted)");
    var permCount = Math.min(sidebarItems.length, columnPermRows.length);
    var _loop2 = function _loop2() {
      var _columnCells$;
      var sidebarH = sidebarItems[_j2].getBoundingClientRect().height;
      var columnCells = columnPermRows[_j2].querySelectorAll(".ntm-roles-table__cell");
      var columnH = ((_columnCells$ = columnCells[0]) === null || _columnCells$ === void 0 ? void 0 : _columnCells$.getBoundingClientRect().height) || 0;
      var maxH = Math.max(sidebarH, columnH);
      sidebarItems[_j2].style.height = "".concat(maxH, "px");
      columnCells.forEach(function (cell) {
        cell.style.height = "".concat(maxH, "px");
      });
    };
    for (var _j2 = 0; _j2 < permCount; _j2++) {
      _loop2();
    }
  };
  for (var _i = 0; _i < count; _i++) {
    _loop();
  }
};
var useRowHeightSync = function useRowHeightSync(filteredGroupPermissions) {
  var sync = React.useCallback(function () {
    requestAnimationFrame(syncRowHeights);
  }, []);
  React.useEffect(function () {
    sync();
  }, [filteredGroupPermissions, sync]);
  React.useEffect(function () {
    var observer = new ResizeObserver(sync);
    var container = document.querySelector(".ntm-roles-table__container");
    if (container) observer.observe(container);
    window.addEventListener("resize", sync);
    return function () {
      observer.disconnect();
      window.removeEventListener("resize", sync);
    };
  }, [sync]);
};

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 = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useQueryParams = reactUtils.useQueryParams(),
    _useQueryParams$permi = _useQueryParams.permissionSearchTerm,
    permissionSearchTerm = _useQueryParams$permi === void 0 ? "" : _useQueryParams$permi;
  var isCreatePermissionGranted = config.permissions.create;
  var _useState = React.useState(permissionGroups),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    filteredGroupPermissions = _useState2[0],
    setFilteredGroupPermissions = _useState2[1];
  var _useState3 = React.useState(false),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    isScrollPresent = _useState4[0],
    setIsScrollPresent = _useState4[1];
  var _useState5 = React.useState(undefined),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    selectedRole = _useState6[0],
    setSelectedRole = _useState6[1];
  var _useState7 = React.useState(false),
    _useState8 = _slicedToArray__default.default(_useState7, 2),
    isDeleteAlertOpen = _useState8[0],
    setIsDeleteAlertOpen = _useState8[1];
  var _useState9 = React.useState(false),
    _useState10 = _slicedToArray__default.default(_useState9, 2),
    isEditPaneOpen = _useState10[0],
    setIsEditPaneOpen = _useState10[1];
  var toggleDropdown = function toggleDropdown(category) {
    var permissions = updatePermissionVisibility(category, filteredGroupPermissions);
    setFilteredGroupPermissions(permissions);
  };
  useRowHeightSync(filteredGroupPermissions);
  React.useEffect(function () {
    var newValue = filterPermissionsBySearch(permissionSearchTerm, permissionGroups);
    setFilteredGroupPermissions(newValue);
  }, [permissionGroups, permissionSearchTerm]);
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsx("div", {
      className: "ntm-roles-table__wrapper flex flex-1 flex-col",
      children: ramda.isEmpty(roles) ? /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "flex w-full flex-1 items-center justify-center",
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Empty, {
          description: t("neetoTeamMembers.labels.roleEmptyDescription"),
          icon: lucideReact.UserCog,
          title: t("neetoTeamMembers.labels.roleEmptyTitle"),
          primaryButtonProps: {
            "data-testid": "ntm-add-role-button",
            disabled: !isCreatePermissionGranted,
            label: t("neetoTeamMembers.labels.addNewRole"),
            onClick: function onClick() {
              return setIsNewRolePaneOpen(true);
            }
          }
        })
      }) : ramda.isEmpty(filteredRoles) ? /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "flex w-full flex-1 items-center justify-center",
        children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Empty, {
          icon: lucideReact.Search,
          title: t("neetoTeamMembers.labels.roleSearchEmptyTitle"),
          description: t("neetoTeamMembers.labels.roleSearchEmptyDescription")
        })
      }) : /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "ntm-roles-table__container",
        children: [/*#__PURE__*/jsxRuntime.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__*/jsxRuntime.jsx(Columns, {
          config: config,
          filteredGroupPermissions: filteredGroupPermissions,
          filteredRoles: filteredRoles,
          permissions: permissions,
          roles: roles,
          setIsScrollPresent: setIsScrollPresent,
          setModifiedRoles: setModifiedRoles
        })]
      })
    }), /*#__PURE__*/jsxRuntime.jsx(ManageRoles, {
      config: config,
      permissions: permissions,
      selectedRole: selectedRole,
      isOpen: isEditPaneOpen,
      onClose: function onClose() {
        setSelectedRole(undefined);
        setIsEditPaneOpen(false);
      }
    }), /*#__PURE__*/jsxRuntime.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 = React.useState([]),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    modifiedRoles = _useState2[0],
    setModifiedRoles = _useState2[1];
  var _useState3 = React.useState(false),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    isNewRolePaneOpen = _useState4[0],
    setIsNewRolePaneOpen = _useState4[1];
  var _useFetchRoles = useRolesApi.useFetchRoles({
      enabled: isViewPermissionGranted
    }),
    _useFetchRoles$data = _useFetchRoles.data,
    roles = _useFetchRoles$data === void 0 ? [] : _useFetchRoles$data,
    isRolesLoading = _useFetchRoles.isLoading,
    status = _useFetchRoles.status;
  var _useQueryParams = reactUtils.useQueryParams(),
    _useQueryParams$searc = _useQueryParams.searchTerm,
    searchTerm = _useQueryParams$searc === void 0 ? "" : _useQueryParams$searc;
  var _useFetchPermissions = utils.useFetchPermissions({
      enabled: isViewPermissionGranted
    }),
    permissionData = _useFetchPermissions.data,
    isPermissionsLoading = _useFetchPermissions.isLoading;
  var _useBulkUpdateRoles = useRolesApi.useBulkUpdateRoles({
      enabled: isUpdatePermissionGranted
    }),
    bulkUpdate = _useBulkUpdateRoles.mutate;
  var permissions = v2_Permissions.sortPermissionsBySequence(permissionData);
  var permissionGroups = v2_Permissions.getPermissionGroups(permissions);
  var filteredRoles = ramda.filter(function (_ref2) {
    var name = _ref2.name;
    return ramda.includes(searchTerm.toLowerCase().trim(), name.toLowerCase().trim());
  }, neetoCist.isNotEmpty(modifiedRoles) ? modifiedRoles : roles);
  var handleSubmit = function handleSubmit() {
    var updatedRoles = v2_Permissions.getModifiedPermissions(roles, modifiedRoles);
    bulkUpdate({
      organizationRoles: {
        updatedRoles: updatedRoles
      }
    });
  };
  var handleReset = function handleReset() {
    return setModifiedRoles(roles);
  };
  React.useEffect(function () {
    if (status !== "success") return;
    setModifiedRoles(roles);
  }, [roles, status]);
  if (isRolesLoading || isPermissionsLoading) {
    return /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "flex h-full min-h-screen w-full items-center justify-center",
      children: /*#__PURE__*/jsxRuntime.jsx(neetoAtoms.Spinner, {})
    });
  }
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsx(utils.distExports.ScrollSync, {
      children: /*#__PURE__*/jsxRuntime.jsxs(Container__default.default, {
        isHeaderFixed: true,
        className: "pb-10",
        children: [/*#__PURE__*/jsxRuntime.jsx(Header, {
          config: config,
          handleReset: handleReset,
          handleSubmit: handleSubmit,
          roles: roles,
          setIsNewRolePaneOpen: setIsNewRolePaneOpen
        }), /*#__PURE__*/jsxRuntime.jsx(Table, {
          config: config,
          filteredRoles: filteredRoles,
          permissionGroups: permissionGroups,
          permissions: permissions,
          roles: roles,
          setIsNewRolePaneOpen: setIsNewRolePaneOpen,
          setModifiedRoles: setModifiedRoles
        })]
      })
    }), /*#__PURE__*/jsxRuntime.jsx(ManageRoles, {
      config: config,
      permissions: permissions,
      isOpen: isNewRolePaneOpen,
      onClose: function onClose() {
        return setIsNewRolePaneOpen(false);
      }
    })]
  });
};
var index = reactUtils.withTitle(withReactQuery.withReactQuery(Roles), i18next__default.default.t("neetoTeamMembers.common.role", constants.PLURAL));

module.exports = index;
//# sourceMappingURL=Roles.js.map
