import { jsx, jsxs } from "react/jsx-runtime";
import { forwardRef, useRef, useState, useEffect, useMemo, useCallback } from "react";
import { LicenseManager } from "ag-grid-enterprise";
import { AgGridReact } from "ag-grid-react";
import { useForm } from "react-hook-form";
import { getAssetUrl } from "../../utils/assetBase.js";
import AgGridHeader from "./AgGridHeader.js";
import CommentPanel from "./commentPanel.js";
import CommentsPortal from "./CommentsPortal.js";
import { buildAdvanceSearchFilterModel } from "./filterUtils.js";
import { Menu } from "../Menu/index.js";
import NewAdvanceSearchModal from "./NewAdvanceSearchModal/NewAdvanceSearchModal.js";
import { updateFontSizeOnToolPanel, Columns, getMainMenuItems } from "./tableFunctions.js";
/* empty css                                                      */
/* empty css                                                              */
/* empty css                  */
import TableHeader from "./tableHeader.js";
import TablePagination from "./tablePagination.js";
import { withCommentIcon } from "./withCommentIcon.js";
import { convertToOptions } from "../../utils/helper.js";
import { Prompt } from "../Prompt/index.js";
const EditIcon = getAssetUrl("icons/edit-black.svg");
const DeleteIcon = getAssetUrl("icons/deleteIcon.svg");
const UnreadIcon = getAssetUrl("icons/Comment.svg");
const ReadIcon = getAssetUrl("icons/CheckTickAll.svg");
const Table = forwardRef(
  ({
    defaultColDef: defColDef,
    columnDefs: colDefs,
    tableHeader = "",
    rowHeight: rowHei,
    height,
    topRightOptions,
    topLeftOptions,
    onGlobalSearchClick,
    paginationPageSizeSelector = [10, 20, 50, 100],
    defaultPageSize,
    onNumberFormatChange = () => {
    },
    onColumnSearchClick,
    tableActionOptions,
    bottomLeftOptions,
    cardContainer = true,
    hideRowHeightOptionMenu = false,
    onPaginationChanged = () => {
    },
    showDownloadButton = false,
    onDownloadButtonClick = () => {
    },
    nestedTable = false,
    nestedTableComponent = null,
    closeButton = false,
    handleCloseButtonClick,
    additionalButtons,
    applySort,
    onFilterChanged,
    sortModel,
    onSearchApplyClick,
    gridId,
    showHideEditableCells = false,
    handleShowHideEditableCells = () => {
    },
    topCenterOptions,
    bottomCenterOptions,
    toShowDuplicateColumnInAdvanceSearch = false,
    savedAdvanceSearchConfig,
    handleInlineSearch,
    showContentualFilter = false,
    showContentualFilterBadge = false,
    onContentualFilterClick = () => {
    },
    contentualFilterProps,
    contentualFilterComponent,
    onAdvanceSearchClick,
    tableActions,
    customGetMainMenuItems,
    hidePaginationPageSizeSelector = false,
    onTableActionsTabClick,
    hideTableFormat = false,
    hideTableActions = false,
    handleClearSearchInline,
    aboveTableComponent: belowHeaderComponent,
    hideTableSetting = false,
    explicitlyCloseTableSetting = false,
    handleCloseInputField,
    customHeaderComponent,
    debounceTime = 1500,
    hideMarginBottom = false,
    customSystemButton,
    isChatEnabled = false,
    handleChatClick = () => {
    },
    isChatOpen = false,
    handleChatClose = () => {
    },
    chatConfiguration,
    savedViewsOptions,
    handleSaveAndApply = () => {
    },
    maxSavedViews = 50,
    handleSavedViewClick = () => {
    },
    handleEditSaveView = () => {
    },
    isSaveViewEnabled = false,
    isSaveViewLoading = false,
    handleDeleteViewClick = () => {
    },
    isDeleteViewLoading = false,
    handleSetDefaultView = () => {
    },
    isCommentFeatureEnabled = false,
    commentProps,
    hideFontSize = false,
    hideNumericFormat = false,
    onContentDensityChange,
    handleCommentNotification,
    customTabInTableSettings = null,
    closeTableSettingOnOutsideClick = false,
    saveViewCustomFilter = {
      options: [
        { label: "Global", value: "global" },
        { label: "Personal", value: "personal" }
      ],
      selectedOption: "global"
    },
    customRenderSaveViewContent = null,
    hideTableBody = false,
    onTableSettingClick = () => {
    },
    deleteViewPromptText,
    contentualFilterOpenByDefault = false,
    tableSettingsTitle,
    enableHeaderTextWrap = true,
    numericFormatDefault = "full_no",
    defaultFontSize = "medium",
    ...args
  }, ref) => {
    var _a, _b, _c;
    LicenseManager.setLicenseKey(
      "Using_this_{AG_Grid}_Enterprise_key_{AG-072820}_in_excess_of_the_licence_granted_is_not_permitted___Please_report_misuse_to_legal@ag-grid.com___For_help_with_changing_this_key_please_contact_info@ag-grid.com___{Impact_Analytics}_is_granted_a_{Multiple_Applications}_Developer_License_for_{1}_Front-End_JavaScript_developer___All_Front-End_JavaScript_developers_need_to_be_licensed_in_addition_to_the_ones_working_with_{AG_Grid}_Enterprise___This_key_has_not_been_granted_a_Deployment_License_Add-on___This_key_works_with_{AG_Grid}_Enterprise_versions_released_before_{31_December_2025}____[v3]_[01]_MTc2NzEzOTIwMDAwMA==acb63fc998feb69e3a3ca9ad323b2577"
    );
    const tempRef = useRef();
    const actualRef = ref || tempRef;
    const [localPageSize, setLocalPageSize] = useState(
      defaultPageSize || paginationPageSizeSelector[0]
    );
    const [initialFilters, setInitialFilters] = useState([]);
    const [tableSettingOpen, setTableSettingOpen] = useState(false);
    const [rowHeight, setRowHeight] = useState(
      rowHei === "comfort" ? 52 : rowHei === "compact" ? 30 : 46
    );
    useEffect(() => {
      var _a2;
      let newRowHeight;
      if (typeof rowHei === "number") {
        newRowHeight = rowHei;
      } else if (rowHei === "comfort") {
        newRowHeight = 52;
      } else if (rowHei === "compact") {
        newRowHeight = 30;
      } else {
        newRowHeight = 46;
      }
      setRowHeight(newRowHeight);
      if ((_a2 = actualRef.current) == null ? void 0 : _a2.api) {
        setTimeout(() => {
          actualRef.current.api.resetRowHeights();
        }, 0);
      }
    }, [rowHei, actualRef]);
    const [tableFontSize, setTableFontSize] = useState(defaultFontSize || "medium");
    const buttonRef = useRef(null);
    const nestedTableRef = useRef(null);
    const [isAdvanceSearch, setAdvanceSearch] = useState(false);
    const [currentColumnId, setCurrentColumnId] = useState(null);
    const [draftFilter, setDraftFilter] = useState([]);
    const [showCommentPanel, setShowCommentPanel] = useState(false);
    const [selectedThirdOptionDropdownValue, setSelectedThirdOptionDropdownValue] = useState(null);
    const filteredColumnsInitialOptions = useMemo(() => convertToOptions(colDefs || []), [colDefs]);
    const formMethods = useForm({
      defaultValues: { filters: initialFilters }
    });
    const { getValues, setValue, reset } = formMethods;
    const toggleAdvanceSearch = (colId, searchTxt) => {
      setAdvanceSearch((prev) => !prev);
      if ((savedAdvanceSearchConfig == null ? void 0 : savedAdvanceSearchConfig.length) > 0) {
        setInitialFilters(savedAdvanceSearchConfig);
        return;
      }
      if (Array.isArray(colId)) {
        setCurrentColumnId(colId[0] || null);
        setInitialFilters((prev) => {
          const newFilters = [...prev];
          colId.forEach((id) => {
            const isColumnHave = newFilters.find(
              (filter) => {
                var _a2;
                return ((_a2 = filter.column) == null ? void 0 : _a2.value) === id && filter.column !== null;
              }
            );
            if (!isColumnHave) {
              const columnOption = filteredColumnsInitialOptions.find((opt) => opt.value === id);
              if (columnOption) {
                newFilters.push({
                  column: columnOption,
                  operation: null,
                  value: ""
                });
              }
            }
          });
          return newFilters;
        });
      } else if (typeof colId === "string" || typeof colId === "number") {
        setCurrentColumnId(colId || null);
        setInitialFilters((prev) => {
          const cleaned = prev.filter((f) => f.column !== null);
          const isColumnHave = cleaned.find((filter) => {
            var _a2;
            return ((_a2 = filter.column) == null ? void 0 : _a2.value) === colId;
          });
          if (isColumnHave) return cleaned;
          const columnOption = filteredColumnsInitialOptions.find((opt) => opt.value === colId);
          return [
            ...cleaned,
            columnOption ? {
              column: columnOption,
              operation: (searchTxt == null ? void 0 : searchTxt.length) > 0 ? { label: "Contains", value: "contains" } : "",
              value: searchTxt
            } : {}
          ];
        });
      }
    };
    const toggleNewAdvanceSearch = (colId, searchTxt) => {
      setAdvanceSearch((prev) => !prev);
      if ((savedAdvanceSearchConfig == null ? void 0 : savedAdvanceSearchConfig.length) > 0) {
        setInitialFilters(savedAdvanceSearchConfig);
        return;
      }
      if (Array.isArray(colId)) {
        setCurrentColumnId(colId[0] || null);
        setInitialFilters((prev) => {
          const newFilters = [...prev];
          colId.forEach((id) => {
            const isColumnHave = newFilters.find(
              (filter) => {
                var _a2;
                return ((_a2 = filter.column) == null ? void 0 : _a2.value) === id && filter.column !== null;
              }
            );
            if (!isColumnHave) {
              const columnOption = filteredColumnsInitialOptions.find((opt) => opt.value === id);
              if (columnOption) {
                newFilters.push({
                  column: columnOption,
                  operation: null,
                  value: ""
                });
              }
            }
          });
          return newFilters;
        });
      } else if (typeof colId === "string" || typeof colId === "number") {
        setCurrentColumnId(colId || null);
      }
    };
    useEffect(() => {
      if (defaultFontSize) setTableFontSize(defaultFontSize);
    }, [defaultFontSize]);
    const updateExpandState = useCallback(
      (params) => {
        let allExpanded = true;
        let hasGroups = false;
        params.api.forEachNode((node) => {
          if (node.group) {
            hasGroups = true;
            if (!node.expanded) {
              allExpanded = false;
            }
          }
        });
        if (hasGroups) {
          actualRef.current.api.getModel().isExpand = allExpanded;
        }
      },
      [actualRef]
    );
    const selectColumn = useCallback(
      (cols) => {
        actualRef.current.api.clearRangeSelection();
        actualRef.current.api.addCellRange({ columns: cols });
      },
      [actualRef]
    );
    const AgGridHeaderWrapper = useCallback(
      (props) => {
        const {
          selectColumn: selectColumn2,
          onColumnSearchClick: onColumnSearchClick2,
          applySort: applySort2,
          onFilterChanged: onFilterChanged2,
          sortModel: sortModel2,
          toggleAdvanceSearch: toggleAdvanceSearch2,
          onAdvanceSearchClick: onAdvanceSearchClick2,
          handleInlineSearch: handleInlineSearch2,
          handleClearSearchInline: handleClearSearchInline2,
          handleCloseInputField: handleCloseInputField2,
          debounceTime: debounceTime2,
          headerComponent,
          ...rest
        } = props;
        return /* @__PURE__ */ jsx(
          AgGridHeader,
          {
            ...rest,
            applySort: applySort2,
            colDefs,
            debounceTime: debounceTime2,
            enableHeaderTextWrap,
            getValues,
            handleClearSearchInline: handleClearSearchInline2,
            handleCloseInputField: handleCloseInputField2,
            handleInlineSearch: handleInlineSearch2,
            initialFilters,
            setInitialFilters,
            setValue,
            sortModel: sortModel2,
            toggleAdvanceSearch: toggleAdvanceSearch2,
            onAdvanceSearchClick: onAdvanceSearchClick2,
            onClick: () => {
              var _a2;
              return selectColumn2 == null ? void 0 : selectColumn2([(_a2 = rest == null ? void 0 : rest.column) == null ? void 0 : _a2.colId]);
            },
            onColumnSearchClick: onColumnSearchClick2,
            onFilterChanged: onFilterChanged2,
            children: headerComponent ? headerComponent(props) : rest == null ? void 0 : rest.displayName
          }
        );
      },
      [
        getValues,
        setValue,
        initialFilters,
        setInitialFilters,
        colDefs,
        onColumnSearchClick,
        applySort,
        onFilterChanged,
        toggleAdvanceSearch,
        onAdvanceSearchClick,
        handleInlineSearch,
        handleClearSearchInline,
        handleCloseInputField,
        debounceTime,
        selectColumn,
        enableHeaderTextWrap
      ]
    );
    const defaultColDef = useMemo(() => {
      return {
        ...defColDef,
        filter: true,
        resizable: true,
        cellClassRules: {
          "editable-ag-cell": (params) => params.colDef.editable,
          "number-cell": (params) => params.colDef.type === "number",
          "default-cell": () => rowHeight === 46,
          "compact-cell": () => rowHeight === 30,
          "comfort-cell": () => rowHeight !== 46 && rowHeight !== 30
        }
      };
    }, [defColDef, rowHeight]);
    const addSpecialAttributes = useCallback(
      (children) => {
        return children.map((child) => {
          var _a2;
          const obj = {
            ...child,
            headerClass: (child.headerClass || "") + (child.type === "number" ? " number-cell" : ""),
            width: child.checkboxSelection || child.headerCheckboxSelection ? "40px" : child.width || void 0,
            headerComponentParams: {
              ...child == null ? void 0 : child.headerComponentParams,
              selectColumn,
              onColumnSearchClick,
              applySort,
              onFilterChanged,
              sortModel,
              toggleAdvanceSearch,
              onAdvanceSearchClick,
              handleInlineSearch,
              handleClearSearchInline,
              handleCloseInputField,
              debounceTime,
              getValues,
              setValue,
              initialFilters,
              setInitialFilters,
              colDefs,
              headerComponent: child == null ? void 0 : child.headerComponent
            },
            headerComponent: customHeaderComponent ? customHeaderComponent : AgGridHeaderWrapper
          };
          if (child.filter === "agDateColumnFilter" && !((_a2 = child.filterParams) == null ? void 0 : _a2.comparator)) {
            obj.filterParams = {
              ...child.filterParams,
              // Enable all filter buttons/operators
              buttons: ["apply", "clear", "reset"],
              // Explicitly enable all date filter options
              filterOptions: [
                "equals",
                "notEqual",
                "lessThan",
                "lessThanOrEqual",
                "greaterThan",
                "greaterThanOrEqual",
                "inRange"
              ],
              // Suppress the filter options UI (we're using advance search)
              suppressAndOrCondition: true,
              // Add comparator for date comparison
              comparator: (filterLocalDateAtMidnight, cellValue) => {
                if (!cellValue) return -1;
                const cellDate = new Date(cellValue);
                cellDate.setHours(0, 0, 0, 0);
                if (cellDate < filterLocalDateAtMidnight) return -1;
                if (cellDate > filterLocalDateAtMidnight) return 1;
                return 0;
              }
            };
          }
          if (child.children) {
            obj.children = addSpecialAttributes(child.children);
          }
          return obj;
        });
      },
      [rowHeight]
    );
    const [commentMode, setCommentMode] = useState(false);
    const wrapComponentsWithCommentIcon = (components) => {
      if (!components || typeof components !== "object") {
        return components;
      }
      const wrappedComponents2 = {};
      Object.keys(components).forEach((key) => {
        const Component = components[key];
        if (typeof Component === "function") {
          wrappedComponents2[key] = withCommentIcon(Component);
        } else {
          wrappedComponents2[key] = Component;
        }
      });
      return wrappedComponents2;
    };
    const applyCommentIconToColumns = (colDefs2) => {
      if (!isCommentFeatureEnabled) {
        return colDefs2;
      }
      return colDefs2 == null ? void 0 : colDefs2.map((col) => {
        if (col.children) {
          return {
            ...col,
            children: applyCommentIconToColumns(col.children)
          };
        } else {
          const isStringRenderer = typeof col.cellRenderer === "string";
          return {
            ...col,
            cellRenderer: isStringRenderer ? col.cellRenderer : withCommentIcon(col.cellRenderer)
            // Wrap all others (including undefined/null)
          };
        }
      });
    };
    const columnDefs = useMemo(() => {
      return addSpecialAttributes(colDefs);
    }, [colDefs, addSpecialAttributes]);
    const finalColumnDefs = useMemo(() => {
      var _a2, _b2, _c2, _d, _e, _f, _g, _h;
      if (!columnDefs || columnDefs.length === 0) {
        return null;
      }
      const applyStyleRecursively = (columns) => columns == null ? void 0 : columns.map((column) => {
        if (Array.isArray(column.children)) {
          return {
            ...column,
            children: applyStyleRecursively(column.children)
          };
        }
        if ((column == null ? void 0 : column.field) === "Selection") {
          return column;
        }
        const originalCellStyle = column.cellStyle;
        return {
          ...column,
          cellStyle: (params) => {
            const baseStyle = typeof originalCellStyle === "function" ? originalCellStyle(params) : originalCellStyle || {};
            return {
              ...baseStyle,
              fontSize: updateFontSizeOnToolPanel(tableFontSize)
            };
          }
        };
      });
      let computed = ((_b2 = (_a2 = actualRef.current) == null ? void 0 : _a2.api) == null ? void 0 : _b2.getColumnDefs()) || columnDefs;
      if (tableFontSize) {
        computed = applyStyleRecursively(columnDefs);
        const existingAutoGroup = ((_e = (_d = (_c2 = actualRef.current) == null ? void 0 : _c2.api) == null ? void 0 : _d.getGridOption) == null ? void 0 : _e.call(_d, "autoGroupColumnDef")) || {};
        const existingCellStyle = existingAutoGroup == null ? void 0 : existingAutoGroup.cellStyle;
        (_g = (_f = actualRef.current) == null ? void 0 : _f.api) == null ? void 0 : _g.setGridOption("autoGroupColumnDef", {
          ...existingAutoGroup,
          cellStyle: (params) => {
            const baseStyle = typeof existingCellStyle === "function" ? existingCellStyle(params) : existingCellStyle || {};
            return {
              ...baseStyle,
              fontSize: updateFontSizeOnToolPanel(tableFontSize)
            };
          }
        });
      }
      computed = applyCommentIconToColumns(computed);
      if ((_h = actualRef.current) == null ? void 0 : _h.api) actualRef.current.api.getModel().appliedFontSize = tableFontSize;
      return computed;
    }, [columnDefs, tableFontSize]);
    const onFirstDataRendered = (params) => {
      var _a2;
      if (params == null ? void 0 : params.api) params.api.getModel().appliedFontSize = tableFontSize;
      (_a2 = args.onFirstDataRendered) == null ? void 0 : _a2.call(args, params);
    };
    const wrappedComponents = useMemo(() => {
      if (!isCommentFeatureEnabled || !args.components) {
        return args.components;
      }
      return wrapComponentsWithCommentIcon(args.components);
    }, [args.components, isCommentFeatureEnabled]);
    const setDynmaicStyleToButtonComponent = useCallback(() => {
      const span1 = document.querySelector(".ag-paging-row-summary-panel");
      const span2 = document.querySelector(".ag-paging-page-summary-panel");
      if (span1 || span2) {
        const actualWidth = ((span1 == null ? void 0 : span1.offsetWidth) || 0) + ((span2 == null ? void 0 : span2.offsetWidth) || 0) + 20;
        if (buttonRef.current) {
          buttonRef.current.style.right = `${actualWidth}px`;
          if (tableSettingOpen) {
            buttonRef.current.style.right = `${actualWidth + 375}px`;
          } else {
            buttonRef.current.style.right = `${actualWidth}px`;
          }
        }
      }
    }, [buttonRef, tableSettingOpen]);
    const paginationChanged = useCallback(
      (params) => {
        setDynmaicStyleToButtonComponent();
        onPaginationChanged(params);
      },
      [setDynmaicStyleToButtonComponent, onPaginationChanged]
    );
    useEffect(() => {
      setDynmaicStyleToButtonComponent();
      const div = document.querySelector(".ag-root-wrapper-body");
      if (div) {
        const actualHeight = div.offsetHeight;
        const tableContainer = document.querySelector(`#${gridId || "myGrid"}`);
        if (tableSettingOpen || commentMode) {
          if (actualHeight < 480) {
            if (tableContainer) {
              tableContainer.style.height = `551px`;
              if (buttonRef && buttonRef.current)
                buttonRef.current.style.bottom = `${480 - actualHeight - 37}px`;
            }
          } else {
            const panelEl = document.querySelector(
              tableSettingOpen ? ".display-table-setting" : ".display-comment-panel"
            );
            if (panelEl) {
              panelEl.style.height = `${actualHeight}px`;
            }
          }
        } else {
          if (tableContainer) tableContainer.style.height = `unset`;
          if (buttonRef && buttonRef.current) buttonRef.current.style.bottom = `13px`;
        }
      }
    }, [tableSettingOpen, commentMode, cardContainer]);
    useEffect(() => {
      if (nestedTable && nestedTableRef.current) {
        const rect = nestedTableRef.current.getBoundingClientRect();
        setTimeout(() => {
          window.scrollTo({
            top: rect.top,
            behavior: "smooth"
          });
        }, 100);
      }
    }, [nestedTable]);
    const onSearchApplyClicks = (formValues) => {
      if (!formValues || !Array.isArray(formValues)) {
        console.warn("onSearchApplyClicks: formValues is undefined or not an array");
        return;
      }
      if (formValues.length === 0) {
        setInitialFilters([{ column: null, operation: null, value: "" }]);
      } else {
        setInitialFilters([...formValues]);
      }
      const rest = actualRef.current;
      if (!(rest == null ? void 0 : rest.api)) {
        console.warn("onSearchApplyClicks: AG Grid API not available");
        return;
      }
      const filterModel = buildAdvanceSearchFilterModel(formValues, colDefs);
      rest.api.setFilterModel(filterModel);
      if (onSearchApplyClick) {
        onSearchApplyClick(formValues);
      } else {
        rest.api.onFilterChanged();
      }
      setTimeout(() => {
        if (rest == null ? void 0 : rest.api) {
          const displayedRowCount = rest.api.getDisplayedRowCount();
          if (displayedRowCount === 0) {
            rest.api.showNoRowsOverlay();
          } else {
            rest.api.hideOverlay();
          }
        }
      }, 100);
      toggleAdvanceSearch();
    };
    const [comments, setComments] = useState((commentProps == null ? void 0 : commentProps.comments) || {});
    const [resolvedComments, setResolvedComments] = useState((commentProps == null ? void 0 : commentProps.resolvedComments) || []);
    const [isCommentResolvedAlertOpen, setIsCommentResolvedAlertOpen] = useState(false);
    useEffect(() => {
      if (commentProps == null ? void 0 : commentProps.comments) {
        setComments(commentProps.comments);
      }
      if (commentProps == null ? void 0 : commentProps.resolvedComments) {
        setResolvedComments(commentProps.resolvedComments);
      }
    }, [commentProps]);
    const triggerCommentClick = useCallback(
      (cellId, messageId = null) => {
        handleCommentItemClick(cellId, comments[cellId], messageId);
      },
      [comments]
    );
    useEffect(() => {
      if (handleCommentNotification && typeof handleCommentNotification === "function") {
        handleCommentNotification(triggerCommentClick);
      }
    }, [handleCommentNotification, triggerCommentClick]);
    const [popup, setPopup] = useState(null);
    useEffect(() => {
      var _a2;
      if ((_a2 = actualRef.current) == null ? void 0 : _a2.api) {
        actualRef.current.api.refreshCells({
          force: true,
          suppressFlash: true
        });
      }
    }, [popup, resolvedComments]);
    useEffect(() => {
      const scrollableElement = document.querySelector(".ag-body-viewport");
      const bodyElement = document.querySelector("body");
      const preventScroll = (e) => {
        const portalElement = e.target.closest(".comments-portal");
        const portalListElement = e.target.closest(".comments-portal-list");
        const panelListElement = e.target.closest(".comment-panel-content");
        const textareaElement = e.target.closest(".comments-textarea");
        const tiptapEditor = e.target.closest(".ProseMirror") || e.target.closest(".tiptap-editor");
        const scrollEl = tiptapEditor || portalListElement || panelListElement || textareaElement || portalElement;
        if (scrollEl) {
          const deltaY = typeof e.deltaY === "number" ? e.deltaY : 0;
          const scrollTop = scrollEl.scrollTop;
          const maxScrollTop = scrollEl.scrollHeight - scrollEl.clientHeight;
          const atTop = scrollTop <= 0;
          const atBottom = scrollTop >= maxScrollTop - 1;
          if (deltaY < 0 && atTop || deltaY > 0 && atBottom) {
            e.preventDefault();
            return;
          }
          e.stopPropagation();
          return;
        }
        e.preventDefault();
      };
      if (popup && scrollableElement) {
        scrollableElement.addEventListener("wheel", preventScroll, {
          passive: false
        });
      }
      if (popup && bodyElement) {
        bodyElement.addEventListener("wheel", preventScroll, {
          passive: false
        });
      }
      return () => {
        if (scrollableElement) {
          scrollableElement.removeEventListener("wheel", preventScroll);
        }
        if (bodyElement) {
          bodyElement.removeEventListener("wheel", preventScroll);
        }
      };
    }, [popup]);
    const calculatePopupPosition = useCallback((rect, comments2 = [], openedBy = "hover") => {
      const gridEl = document.querySelector(".ag-root");
      const popupWidth = 350;
      const margin = 0;
      const maxPopupHeight = 500;
      const effectivePopupWidth = !comments2 || comments2.length === 0 ? 200 : popupWidth;
      if (!gridEl) {
        if (window.innerWidth - rect.right < effectivePopupWidth) {
          return {
            top: rect.top,
            left: rect.left - effectivePopupWidth - margin,
            side: "left"
          };
        }
        return { top: rect.top, left: rect.right + margin, side: "right" };
      }
      const gridRect = gridEl.getBoundingClientRect();
      let popupHeight;
      if (!comments2 || comments2.length === 0) {
        popupHeight = 20;
      } else if (openedBy === "hover") {
        const firstComment = comments2[0];
        const baseHeight = 30;
        const maxHeight = 150;
        if (firstComment == null ? void 0 : firstComment.text) {
          const textLength = firstComment.text.length;
          const estimatedLines = Math.ceil(textLength / 45);
          const textHeight = estimatedLines * 20;
          popupHeight = Math.min(baseHeight + textHeight, maxHeight);
        } else {
          popupHeight = baseHeight;
        }
      } else {
        const headerHeight = 50;
        const inputSectionHeight = 60;
        const commentHeight = 70;
        const estimatedHeight = headerHeight + comments2.length * commentHeight + inputSectionHeight;
        popupHeight = Math.min(estimatedHeight, maxPopupHeight);
      }
      let left;
      let side = "right";
      const spaceRight = gridRect.right - rect.right - margin;
      const spaceLeft = rect.left - gridRect.left - margin;
      if (spaceRight >= effectivePopupWidth) {
        left = rect.right + margin;
        side = "right";
      } else if (spaceLeft >= effectivePopupWidth) {
        left = rect.left - effectivePopupWidth - margin;
        side = "left";
      } else {
        left = Math.min(rect.right + margin, gridRect.right - effectivePopupWidth - margin);
        left = Math.max(left, gridRect.left + margin);
        side = "clamped";
      }
      let top = rect.top;
      if (!comments2 || comments2.length === 0 || comments2 && comments2.length == 1) {
        const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
        const safePad = 8;
        const rawClampHeight = !comments2 || comments2.length === 0 ? popupHeight : openedBy === "hover" ? popupHeight : maxPopupHeight;
        const clampHeight = Math.max(
          0,
          Math.min(rawClampHeight, Math.max(0, viewportHeight - safePad))
        );
        const maxTop = Math.max(safePad, viewportHeight - clampHeight);
        top = Math.min(Math.max(safePad, rect.top), maxTop);
        return { top, left, side };
      }
      if (top + popupHeight > gridRect.bottom && comments2 && comments2.length > 0) {
        const topAboveCell = rect.top - popupHeight - margin;
        if (topAboveCell >= gridRect.top) {
          top = topAboveCell;
        } else {
          top = gridRect.top + margin;
        }
      }
      top = Math.max(gridRect.top + margin, top);
      return { top, left, side };
    }, []);
    const hoverTimeoutRef = useRef(null);
    const [inputValue, setInputValue] = useState("");
    const [menuAnchorEl, setMenuAnchorEl] = useState(null);
    const [editingComment, setEditingComment] = useState(null);
    const [selectedComment, setSelectedComment] = useState(null);
    const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);
    const [commentToDelete, setCommentToDelete] = useState(null);
    const [threadToDelete, setThreadToDelete] = useState(null);
    const [isDeleteConfirmationLoading, setIsDeleteConfirmationLoading] = useState(false);
    const [isCommentLoading, setIsCommentLoading] = useState(false);
    const [commentError, setCommentError] = useState(null);
    const [currentMenuType, setCurrentMenuType] = useState("commentMenu");
    const getMenuOptions = (menuType) => {
      const config = (commentProps == null ? void 0 : commentProps.configuration) || {};
      if (menuType === "topMenu") {
        const isObj = selectedComment && typeof selectedComment === "object";
        const isRead = isObj ? selectedComment[0].read : selectedComment == null ? void 0 : selectedComment.read;
        const author = isObj ? selectedComment[0].author : selectedComment == null ? void 0 : selectedComment.author;
        const options = [];
        if (!config.disableMarkAsRead) {
          options.push({
            label: isRead ? "Mark as Unread" : "Mark as Read",
            // icon: <DeleteIcon />,
            onClick: async () => {
              if (selectedComment == null ? void 0 : selectedComment.read) {
                await (commentProps == null ? void 0 : commentProps.handleMarkAsUnread(selectedComment.id));
              } else {
                await (commentProps == null ? void 0 : commentProps.handleMarkAsRead(selectedComment.id));
              }
              handleMenuClose();
            },
            value: "mark-as-unread",
            icon: isRead ? /* @__PURE__ */ jsx("img", { alt: "", src: UnreadIcon, style: { width: 20, height: 20, display: "block" } }) : /* @__PURE__ */ jsx("img", { alt: "", src: ReadIcon, style: { width: 20, height: 20, display: "block" } })
          });
        }
        if (!config.disableDeleteThread && author == (commentProps == null ? void 0 : commentProps.author)) {
          options.push({
            label: "Delete Thread",
            icon: /* @__PURE__ */ jsx("img", { alt: "", src: DeleteIcon, style: { width: 20, height: 20, display: "block" } }),
            onClick: handleThreadDeleteClick,
            value: "delete-thread"
          });
        }
        return options;
      } else {
        const options = [];
        if (!config.disableEditComment) {
          options.push({
            label: "Edit",
            icon: /* @__PURE__ */ jsx("img", { alt: "", src: EditIcon, style: { width: 20, height: 20, display: "block" } }),
            onClick: () => {
              if (selectedComment) {
                setEditingComment(selectedComment);
              }
              handleMenuClose();
            },
            value: "edit"
          });
        }
        if (!config.disableDeleteComment) {
          options.push({
            label: "Delete",
            icon: /* @__PURE__ */ jsx("img", { alt: "", src: DeleteIcon, style: { width: 20, height: 20, display: "block" } }),
            onClick: handleDeleteClick,
            value: "delete"
          });
        }
        return options;
      }
    };
    const handleMenuClick = useCallback(
      (event, comment = null, type = "commentMenu") => {
        setMenuAnchorEl(event.currentTarget);
        setCurrentMenuType(type);
        if (typeof comment === "string") {
          const val = comments[comment];
          setSelectedComment({ ...val, id: comment });
        } else {
          setSelectedComment(comment);
        }
      },
      [comments]
    );
    const handleMenuClose = useCallback(() => {
      setMenuAnchorEl(null);
      setSelectedComment(null);
    }, []);
    useMemo(() => {
      if (!popup) {
        setMenuAnchorEl(null);
        setEditingComment(null);
        setSelectedComment(null);
      }
    }, [popup]);
    const toggleCommentMode = () => {
      setCommentMode((prev) => !prev);
      setPopup(null);
      setEditingComment(null);
      setSelectedComment(null);
    };
    useEffect(() => {
      if (tableSettingOpen && commentMode) {
        setCommentMode(false);
      }
    }, [tableSettingOpen]);
    const getEffectiveCellId = useCallback(
      (baseCellId) => {
        const isResolved = Array.isArray(resolvedComments) ? resolvedComments.includes(baseCellId) : false;
        if (!isResolved) return baseCellId;
        const prefix = `${baseCellId}__t`;
        const allKeys = Object.keys(comments || {});
        const threadIndices = allKeys.filter((k) => k === baseCellId || k.startsWith(prefix)).map((k) => {
          const m = k.match(new RegExp(`^${baseCellId}__t(\\d+)$`));
          return m ? parseInt(m[1], 10) : 0;
        }).filter((n) => !Number.isNaN(n));
        const nextIndex = threadIndices.length ? Math.max(...threadIndices) + 1 : 1;
        return `${baseCellId}__t${nextIndex}`;
      },
      [comments, resolvedComments]
    );
    const getLatestUnresolvedThreadId = useCallback(
      (baseCellId) => {
        const prefix = `${baseCellId}__t`;
        const allKeys = Object.keys(comments || {});
        const candidates = allKeys.filter((k) => k === baseCellId || k.startsWith(prefix));
        if (candidates.length === 0) return null;
        const unresolved = candidates.filter((k) => {
          var _a2;
          return !((_a2 = resolvedComments == null ? void 0 : resolvedComments.includes) == null ? void 0 : _a2.call(resolvedComments, k));
        });
        if (unresolved.length === 0) return null;
        const withIndex = unresolved.map((k) => {
          const m = k.match(new RegExp(`^${baseCellId}__t(\\d+)$`));
          return { id: k, idx: m ? parseInt(m[1], 10) : 0 };
        });
        withIndex.sort((a, b) => b.idx - a.idx);
        return withIndex[0].id;
      },
      [comments, resolvedComments]
    );
    const onCellClicked = useCallback(
      (params) => {
        var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i;
        if (!commentMode) return;
        const cellEl = (_a2 = params.event.target) == null ? void 0 : _a2.closest(".ag-cell");
        if (cellEl) {
          const rowEl = cellEl.closest(".ag-row");
          if (((_b2 = rowEl == null ? void 0 : rowEl.classList) == null ? void 0 : _b2.contains("ag-row-group")) || ((_c2 = cellEl.classList) == null ? void 0 : _c2.contains("ag-group-cell"))) {
            return;
          }
          if (((_e = (_d = params == null ? void 0 : params.column) == null ? void 0 : _d.getColId) == null ? void 0 : _e.call(_d)) === "ag-Grid-AutoColumn") {
            return;
          }
          const rect = cellEl.getBoundingClientRect();
          const rowIdentifier = (commentProps == null ? void 0 : commentProps.colIdentifierKey) ? ((_f = params.data) == null ? void 0 : _f[commentProps.colIdentifierKey]) || params.node.id : params.node.id;
          const baseCellId = `${rowIdentifier}__${params.column.getColId()}`;
          let effectiveCellId = baseCellId;
          if (!((_g = commentProps == null ? void 0 : commentProps.configuration) == null ? void 0 : _g.disableMultiCommentThread)) {
            const baseResolved = Array.isArray(resolvedComments) ? resolvedComments.includes(baseCellId) : false;
            if (baseResolved) {
              const latestUnresolved = getLatestUnresolvedThreadId(baseCellId);
              effectiveCellId = latestUnresolved || getEffectiveCellId(baseCellId);
            }
          }
          const commentForCell = ((_h = params.data) == null ? void 0 : _h.comment) || comments[effectiveCellId];
          const position = calculatePopupPosition(rect, commentForCell, "click");
          setPopup({
            position,
            rowId: rowIdentifier,
            colId: params.column.getColId(),
            cellId: effectiveCellId,
            comment: commentForCell,
            author: (commentProps == null ? void 0 : commentProps.author) || "Current User",
            // TODO: You can replace this with actual user info
            openedBy: "click",
            data: (_i = params.node) == null ? void 0 : _i.data
          });
        }
      },
      [
        commentMode,
        (_a = commentProps == null ? void 0 : commentProps.configuration) == null ? void 0 : _a.disableMultiCommentThread,
        resolvedComments,
        getLatestUnresolvedThreadId,
        getEffectiveCellId,
        comments,
        calculatePopupPosition
      ]
    );
    useEffect(() => {
      var _a2;
      if ((_a2 = actualRef.current) == null ? void 0 : _a2.api) {
        actualRef.current.api.refreshCells({
          force: true
          // Force refresh even if data hasn't changed
        });
      }
    }, [comments]);
    const handleCommentIconHover = useCallback(
      (params) => {
        var _a2, _b2;
        if (params.eGridCell) {
          const rect = params.eGridCell.getBoundingClientRect();
          const rowIdentifier = (commentProps == null ? void 0 : commentProps.colIdentifierKey) ? ((_a2 = params.data) == null ? void 0 : _a2[commentProps.colIdentifierKey]) || params.node.id : params.node.id;
          const baseCellId = `${rowIdentifier}__${params.column.getColId()}`;
          const cellId = getLatestUnresolvedThreadId(baseCellId);
          if (!cellId) return;
          const position = calculatePopupPosition(rect, comments[cellId], "hover");
          setPopup({
            position,
            // { top: rect.top, left: rect.right + 5 },
            rowId: rowIdentifier,
            colId: params.column.getColId(),
            cellId,
            comment: comments[cellId],
            author: (commentProps == null ? void 0 : commentProps.author) || "Current User",
            openedBy: "hover",
            data: (_b2 = params.node) == null ? void 0 : _b2.data
          });
        }
      },
      [getLatestUnresolvedThreadId, calculatePopupPosition, comments, commentProps == null ? void 0 : commentProps.author]
    );
    const handleMouseLeave = useCallback(() => {
      if ((popup == null ? void 0 : popup.openedBy) === "hover") {
        hoverTimeoutRef.current = setTimeout(() => {
          if (!menuAnchorEl) {
            setPopup(null);
            setEditingComment(null);
            setSelectedComment(null);
          }
        }, 200);
      } else {
        setPopup(null);
        setEditingComment(null);
        setSelectedComment(null);
      }
    }, [popup, menuAnchorEl]);
    const handleMouseEnter = useCallback(() => {
      if ((popup == null ? void 0 : popup.openedBy) === "hover") {
        clearTimeout(hoverTimeoutRef.current);
      }
    }, [popup]);
    const handleRegisterTableSettingToggle = useCallback(
      (fn) => {
        var _a2;
        const api = (_a2 = actualRef.current) == null ? void 0 : _a2.api;
        if (api && typeof fn === "function") {
          api.showTableSetting = (tabName, options) => fn(true, tabName, options);
          api.hideTableSetting = (options) => fn(false, void 0, options);
          api.toggleTableSetting = (open, tabName, options) => fn(open, tabName, options);
        }
      },
      [actualRef]
    );
    function getCellElementById(gridId2, rowNode, colId) {
      const containerEl = document.querySelector(".impact-table-main-container");
      if (!containerEl || !rowNode) return null;
      let cell = containerEl.querySelector(
        `[role="row"][row-id="${rowNode.id}"] [col-id="${colId}"]`
      );
      if (!cell) {
        const rowIndex = rowNode.rowIndex ?? rowNode.childIndex;
        if (rowIndex != null) {
          cell = containerEl.querySelector(
            `[role="row"][row-index="${rowIndex}"] [col-id="${colId}"]`
          );
        }
      }
      return cell;
    }
    const handleCommentItemClick = useCallback(
      (cellId, comments2, messageId = null) => {
        var _a2;
        const [rowId, colId, threadId] = cellId.split("__");
        const api = (_a2 = actualRef.current) == null ? void 0 : _a2.api;
        if (!api) {
          console.error("AG Grid API not available.");
          return;
        }
        let rowNode;
        if (commentProps == null ? void 0 : commentProps.colIdentifierKey) {
          api.forEachNode((node) => {
            var _a3;
            if (((_a3 = node.data) == null ? void 0 : _a3[commentProps.colIdentifierKey]) === rowId) {
              rowNode = node;
            }
          });
        } else {
          rowNode = api.getRowNode(rowId);
        }
        if (!rowNode) {
          console.error("Could not find row node for rowId:", rowId);
          return;
        }
        api.ensureColumnVisible(colId);
        api.ensureNodeVisible(rowNode, "middle");
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            const cellElement = getCellElementById(gridId || "my-grid", rowNode, colId);
            if (!cellElement) {
              console.error("Could not find cell element for:", cellId);
              return;
            }
            const rect = cellElement.getBoundingClientRect();
            const position = calculatePopupPosition(rect, comments2, "click");
            setPopup({
              position,
              //{ top: rect.top + 11, left: rect.right - 12 },
              cellId,
              comment: comments2,
              author: commentProps == null ? void 0 : commentProps.author,
              openedBy: "click",
              data: (rowNode == null ? void 0 : rowNode.data) || {},
              messageId
            });
          });
        });
      },
      [actualRef, gridId, calculatePopupPosition, commentProps == null ? void 0 : commentProps.author]
    );
    const handleUpdateComment = useCallback(
      async (commentId, newText) => {
        if (commentId === null) {
          setEditingComment(null);
          return;
        }
        if (!(newText == null ? void 0 : newText.trim())) return;
        setIsCommentLoading(true);
        setCommentError(null);
        try {
          const commentToUpdate = editingComment;
          if (!commentToUpdate) return;
          let response;
          if (commentProps == null ? void 0 : commentProps.handleCommentEdit) {
            response = await (commentProps == null ? void 0 : commentProps.handleCommentEdit(
              newText.trim(),
              commentToUpdate,
              commentId
            ));
          }
          if (response) {
            setComments(response);
          }
          setEditingComment(null);
        } catch (error) {
          console.error("Error updating comment:", error);
          setCommentError("Failed to update comment. Please try again.");
        } finally {
          setIsCommentLoading(false);
        }
      },
      [editingComment, commentProps, popup == null ? void 0 : popup.cellId]
    );
    const handleAddComment = useCallback(
      async (cellId, inputValue2, taggedUsers) => {
        if (!(inputValue2 == null ? void 0 : inputValue2.trim())) {
          setCommentError("Comment cannot be empty");
          return;
        }
        const isEditing = editingComment !== null;
        try {
          setIsCommentLoading(true);
          setCommentError(null);
          let response;
          if (isEditing) {
            response = await (commentProps == null ? void 0 : commentProps.handleCommentEdit(
              inputValue2.trim(),
              editingComment,
              editingComment.id,
              taggedUsers
            ));
          } else {
            response = await (commentProps == null ? void 0 : commentProps.handleSaveComment(
              cellId,
              inputValue2.trim(),
              popup == null ? void 0 : popup.data,
              taggedUsers
            ));
          }
          if (response) {
            setComments(response);
          } else {
            if (isEditing) {
              setComments((prev) => {
                var _a2;
                return {
                  ...prev,
                  [cellId]: ((_a2 = prev[cellId]) == null ? void 0 : _a2.map(
                    (comment) => comment.id === editingComment.id ? {
                      ...comment,
                      text: inputValue2.trim(),
                      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                      isEdited: true
                    } : comment
                  )) || []
                };
              });
            } else {
              const newComment = {
                id: Date.now(),
                // Simple ID generation
                text: inputValue2.trim(),
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                author: (commentProps == null ? void 0 : commentProps.author) || "Current User",
                isEdited: false
              };
              setComments((prev) => ({
                ...prev,
                [cellId]: [...prev[cellId] || [], newComment]
              }));
            }
          }
          if (!comments[cellId]) setPopup(null);
          setEditingComment(null);
          setSelectedComment(null);
        } catch (error) {
          console.error("Error saving comment:", error);
          setCommentError(
            (error == null ? void 0 : error.message) || (isEditing ? "Failed to update comment" : "Failed to save comment")
          );
        } finally {
          setIsCommentLoading(false);
        }
      },
      [
        popup == null ? void 0 : popup.data,
        editingComment,
        commentProps == null ? void 0 : commentProps.handleSaveComment,
        commentProps == null ? void 0 : commentProps.handleCommentEdit,
        commentProps == null ? void 0 : commentProps.author
      ]
    );
    const handleMarkAsResolved = useCallback(
      async (cellId, comments2) => {
        const config = (commentProps == null ? void 0 : commentProps.configuration) || {};
        if (config.disableMarkAsResolved) {
          return;
        }
        let response;
        if (commentProps == null ? void 0 : commentProps.handleMarkAsResolved) {
          response = await (commentProps == null ? void 0 : commentProps.handleMarkAsResolved(cellId, comments2));
        }
        if (response) {
          setResolvedComments(response);
        } else {
          setResolvedComments((prev) => [...prev, cellId]);
        }
        setIsCommentResolvedAlertOpen(true);
        setTimeout(() => {
          setIsCommentResolvedAlertOpen(false);
        }, 2e3);
        setPopup(null);
        setEditingComment(null);
        setSelectedComment(null);
      },
      [commentProps == null ? void 0 : commentProps.handleMarkAsResolved, commentProps == null ? void 0 : commentProps.configuration]
    );
    const handleThreadDeleteClick = () => {
      setThreadToDelete({
        cellId: selectedComment.id,
        data: selectedComment
      });
      setShowDeleteConfirmation(true);
      handleMenuClose();
    };
    const handleDeleteClick = () => {
      setCommentToDelete({
        cellId: popup == null ? void 0 : popup.cellId,
        data: popup == null ? void 0 : popup.data,
        comment: selectedComment
      });
      setShowDeleteConfirmation(true);
      handleMenuClose();
    };
    const handleDeleteConfirm = async () => {
      var _a2, _b2, _c2;
      if (commentToDelete) {
        try {
          setIsDeleteConfirmationLoading(true);
          const updatedComment = await ((_b2 = commentProps == null ? void 0 : commentProps.handleCommentDelete) == null ? void 0 : _b2.call(
            commentProps,
            (_a2 = commentToDelete.comment) == null ? void 0 : _a2.id,
            commentToDelete.comment
          ));
          if (updatedComment) {
            setComments(updatedComment);
          }
        } catch (error) {
          console.error("Error deleting comment:", error);
        } finally {
          setIsDeleteConfirmationLoading(false);
        }
      } else if (threadToDelete) {
        try {
          setIsDeleteConfirmationLoading(true);
          const updatedComment = await ((_c2 = commentProps == null ? void 0 : commentProps.handleThreadDelete) == null ? void 0 : _c2.call(
            commentProps,
            threadToDelete.cellId,
            threadToDelete.data
          ));
          if (updatedComment) {
            setComments(updatedComment);
          }
        } catch (error) {
          console.error("Error deleting thread:", error);
        } finally {
          setIsDeleteConfirmationLoading(false);
        }
      }
      setShowDeleteConfirmation(false);
      setCommentToDelete(null);
    };
    const handleDeleteCancel = (e) => {
      e.stopPropagation();
      setShowDeleteConfirmation(false);
      setCommentToDelete(null);
    };
    const clearCommentError = useCallback(() => {
      setCommentError(null);
    }, []);
    const gridContext = useMemo(
      () => ({
        comments,
        popup,
        handleCommentIconHover,
        handleMouseEnter,
        handleMouseLeave,
        resolvedComments,
        getLatestUnresolvedThreadId,
        configuration: commentProps == null ? void 0 : commentProps.configuration,
        colIdentifierKey: commentProps == null ? void 0 : commentProps.colIdentifierKey
      }),
      [
        comments,
        popup,
        handleCommentIconHover,
        handleMouseEnter,
        handleMouseLeave,
        resolvedComments,
        getLatestUnresolvedThreadId,
        commentProps == null ? void 0 : commentProps.configuration,
        commentProps == null ? void 0 : commentProps.colIdentifierKey
      ]
    );
    return /* @__PURE__ */ jsx(
      "div",
      {
        className: `ag-theme-alpine ia-basic-table-layout table-v32 ${height ? "custom-height-override" : ""} ${enableHeaderTextWrap ? "header-wrap-enabled" : ""}`,
        style: {
          width: "100%",
          "--ag-grid-height": height || "500px"
        },
        children: /* @__PURE__ */ jsxs(
          "div",
          {
            className: `impact-table-main-container  ${cardContainer ? "card-container" : ""} ${tableSettingOpen ? "table-setting-open" : ""} ${bottomLeftOptions || bottomCenterOptions ? "footer-button-with-bottom-options" : ""} ${hideMarginBottom ? "hide-margin-bottom" : ""} ${commentMode ? "comment-mode" : ""}`,
            id: gridId || "myGrid",
            children: [
              /* @__PURE__ */ jsx(
                TableHeader,
                {
                  actualRef,
                  additionalButtons,
                  cardContainer,
                  chatConfiguration,
                  closeButton,
                  closeTableSettingOnOutsideClick,
                  colDefs,
                  Columns,
                  commentMode,
                  contentualFilterComponent,
                  contentualFilterOpenByDefault,
                  contentualFilterProps,
                  customRenderSaveViewContent,
                  customSystemButton,
                  customTabInTableSettings,
                  deleteViewPromptText,
                  explicitlyCloseTableSetting,
                  handleChatClick,
                  handleChatClose,
                  handleCloseButtonClick,
                  handleDeleteViewClick,
                  handleEditSaveView,
                  handleSaveAndApply,
                  handleSavedViewClick,
                  handleSetDefaultView,
                  handleShowHideEditableCells,
                  hideFontSize,
                  hideNumericFormat,
                  hideRowHeightOptionMenu,
                  hideTableActions,
                  hideTableFormat,
                  hideTableSetting,
                  isChatEnabled,
                  isChatOpen,
                  isCommentFeatureEnabled,
                  isCommentResolvedAlertOpen,
                  isDeleteViewLoading,
                  isSaveViewEnabled,
                  isSavingViewLoading: isSaveViewLoading,
                  maxSavedViews,
                  numericFormatDefault,
                  registerTableSettingToggle: handleRegisterTableSettingToggle,
                  rowHeight,
                  savedViewsOptions,
                  saveViewCustomFilter,
                  setIsCommentResolvedAlertOpen,
                  setRowHeight,
                  setShowCommentPanel,
                  setTableFontSize,
                  setTableSettingOpen,
                  showCommentBadge: commentProps == null ? void 0 : commentProps.showCommentBadge,
                  showCommentPanel,
                  showContentualFilter,
                  showContentualFilterBadge,
                  showDownloadButton,
                  showHideEditableCells,
                  tableActions,
                  tableFontSize,
                  tableHeader,
                  tableSettingsTitle,
                  toggleCommentMode,
                  topCenterOptions,
                  topLeftOptions,
                  topRightOptions,
                  onContentDensityChange,
                  onContentualFilterClick,
                  onDownloadButtonClick,
                  onGlobalSearchClick,
                  onNumberFormatChange,
                  onTableActionsTabClick,
                  onTableSettingClick
                }
              ),
              belowHeaderComponent && belowHeaderComponent,
              !hideTableBody && (finalColumnDefs == null ? void 0 : finalColumnDefs.length) > 0 && /* @__PURE__ */ jsxs("div", { className: "impact-ag-grid-table", children: [
                /* @__PURE__ */ jsx(
                  AgGridReact,
                  {
                    ...(({ components, ...rest }) => rest)(args),
                    ref: actualRef,
                    enableRangeSelection: true,
                    suppressMenuHide: true,
                    columnDefs: finalColumnDefs,
                    components: wrappedComponents,
                    context: gridContext,
                    defaultColDef,
                    domLayout: "autoHeight",
                    getMainMenuItems: customGetMainMenuItems || getMainMenuItems,
                    headerHeight: 40,
                    pagination: args.pagination,
                    paginationPageSize: localPageSize,
                    popupParent: document.body,
                    rowHeight,
                    onCellClicked,
                    onFirstDataRendered,
                    onPaginationChanged: paginationChanged,
                    onRowGroupOpened: updateExpandState
                  }
                ),
                /* @__PURE__ */ jsx(
                  "div",
                  {
                    className: `${showCommentPanel ? "show-comment-panel" : ""} comment-panel-wrapper`,
                    children: /* @__PURE__ */ jsx(
                      CommentPanel,
                      {
                        commentProps,
                        comments,
                        popup,
                        resolvedComments,
                        setShowCommentPanel,
                        showCommentPanel,
                        onCommentItemClick: handleCommentItemClick,
                        onMarkAsReadClick: commentProps == null ? void 0 : commentProps.handleMarkAsRead,
                        onMarkAsResolvedClick: handleMarkAsResolved,
                        onMenuClick: handleMenuClick,
                        onShowResolvedCommentsRequest: (commentProps == null ? void 0 : commentProps.handleFetchResolvedComments) ? async () => {
                          const result = await commentProps.handleFetchResolvedComments();
                          if (result) {
                            if (result.comments !== void 0) {
                              setComments(result.comments);
                            }
                            if (result.resolvedComments !== void 0) {
                              setResolvedComments(result.resolvedComments);
                            }
                          }
                        } : void 0
                      }
                    )
                  }
                )
              ] }),
              (bottomLeftOptions || bottomCenterOptions || args.pagination) && /* @__PURE__ */ jsxs(
                "div",
                {
                  ref: buttonRef,
                  className: `table-footer-section ${!bottomLeftOptions && !bottomCenterOptions ? "table-footer-section-with-only-pagination" : ""} ${!args.pagination ? "table-footer-section-without-pagination" : ""}`,
                  style: {
                    width: hidePaginationPageSizeSelector && "60%"
                  },
                  children: [
                    bottomLeftOptions && /* @__PURE__ */ jsx("div", { className: "table-footer-left-section", children: bottomLeftOptions }),
                    bottomCenterOptions && /* @__PURE__ */ jsx("div", { className: "table-footer-center-section", children: bottomCenterOptions }),
                    !hidePaginationPageSizeSelector && args.pagination ? /* @__PURE__ */ jsx(
                      TablePagination,
                      {
                        actualRef,
                        defaultPageSize,
                        localPageSize,
                        paginationPageSizeSelector: paginationPageSizeSelector.length > 0 ? paginationPageSizeSelector : [10],
                        setLocalPageSize
                      }
                    ) : null
                  ]
                }
              ),
              nestedTable && /* @__PURE__ */ jsx("div", { ref: nestedTableRef, className: "nested-table-container", children: nestedTableComponent }),
              isAdvanceSearch && /* @__PURE__ */ jsx(
                NewAdvanceSearchModal,
                {
                  actualRef,
                  colDefs,
                  currentColumnId,
                  initialFilters,
                  isAdvanceSearch,
                  setInitialFilters,
                  toggleAdvanceSearch: toggleNewAdvanceSearch,
                  onSearchApplyClick: onSearchApplyClicks
                }
              ),
              /* @__PURE__ */ jsx(
                CommentsPortal,
                {
                  author: popup == null ? void 0 : popup.author,
                  cellId: popup == null ? void 0 : popup.cellId,
                  comments: (comments == null ? void 0 : comments[popup == null ? void 0 : popup.cellId]) ?? (popup == null ? void 0 : popup.comment),
                  configuration: commentProps == null ? void 0 : commentProps.configuration,
                  currentAuthor: commentProps == null ? void 0 : commentProps.author,
                  editCommentText: (editingComment == null ? void 0 : editingComment.text) || "",
                  editingComment,
                  error: commentError,
                  isLoading: isCommentLoading,
                  isOpen: !!popup,
                  loadParticipantsAvatar: commentProps == null ? void 0 : commentProps.loadParticipantsAvatar,
                  messageId: popup == null ? void 0 : popup.messageId,
                  openedBy: popup == null ? void 0 : popup.openedBy,
                  position: popup == null ? void 0 : popup.position,
                  resolvedComments,
                  setEditingComment,
                  onAddComment: handleAddComment,
                  onClearError: clearCommentError,
                  onClose: () => {
                    setPopup(null);
                    setEditingComment(null);
                    setSelectedComment(null);
                    setCommentError(null);
                  },
                  onMarkAsReadClick: ((_b = commentProps == null ? void 0 : commentProps.configuration) == null ? void 0 : _b.disableMarkAsRead) ? null : commentProps == null ? void 0 : commentProps.handleMarkAsRead,
                  onMarkAsResolvedClick: ((_c = commentProps == null ? void 0 : commentProps.configuration) == null ? void 0 : _c.disableMarkAsResolved) ? null : handleMarkAsResolved,
                  onMenuClick: handleMenuClick,
                  onMouseEnter: handleMouseEnter,
                  onMouseLeave: handleMouseLeave,
                  onUpdateComment: handleUpdateComment
                },
                (popup == null ? void 0 : popup.cellId) || "comments-portal"
              ),
              /* @__PURE__ */ jsx(
                Menu,
                {
                  anchorEl: menuAnchorEl,
                  iconPlacement: "left",
                  MenuProps: {
                    sx: {
                      zIndex: 9999
                    }
                  },
                  open: Boolean(menuAnchorEl),
                  options: getMenuOptions(currentMenuType),
                  onClose: handleMenuClose
                }
              ),
              /* @__PURE__ */ jsx(
                Prompt,
                {
                  handleClose: handleDeleteCancel,
                  isOpen: showDeleteConfirmation,
                  primaryButtonLabel: isDeleteConfirmationLoading ? "Deleting..." : "Delete",
                  primaryButtonProps: {
                    type: "destructive"
                  },
                  secondaryButtonLabel: "Cancel",
                  style: { zIndex: 1e4 },
                  title: "Delete Comment",
                  variant: "error",
                  onPrimaryButtonClick: handleDeleteConfirm,
                  onSecondaryButtonClick: handleDeleteCancel,
                  children: "Are you sure you want to delete this comment? This action cannot be undone."
                }
              )
            ]
          }
        )
      }
    );
  }
);
export {
  Table
};
