/**
 * Copyright IBM Corp. 2020, 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { __toESM } from "../../../_virtual/_rolldown/runtime.js";
import { require_classnames } from "../../../node_modules/classnames/index.js";
import { pkg } from "../../../settings.js";
import { useClickOutside } from "../../../global/js/hooks/useClickOutside.js";
import { useFeatureFlag as useFeatureFlag$1 } from "../../FeatureFlags/index.js";
import { useMultipleKeyTracking } from "../../DataSpreadsheet/hooks/useMultipleKeyTracking.js";
import { InlineEditContext } from "./addons/InlineEdit/InlineEditContext/InlineEditContext.js";
import { CLEAR_SINGLE_FILTER } from "./addons/Filtering/constants.js";
import { FilterContext, clearSingleFilter } from "./addons/Filtering/FilterProvider.js";
import useSubscribeToEventEmitter from "./addons/Filtering/hooks/useSubscribeToEventEmitter.js";
import FilterPanel from "./addons/Filtering/FilterPanel.js";
import DatagridHead from "./DatagridHead.js";
import DatagridBody from "./DatagridBody.js";
import DatagridToolbar from "./DatagridToolbar.js";
import FilterSummary from "../../FilterSummary/FilterSummary.js";
import { handleGridFocus } from "./addons/InlineEdit/handleGridFocus.js";
import { handleGridKeyPress } from "./addons/InlineEdit/handleGridKeyPress.js";
import React, { useContext, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { Table, TableContainer, usePrefix } from "@carbon/react";
import { px } from "@carbon/layout";
//#region src/components/Datagrid/Datagrid/DatagridContent.tsx
var import_classnames = /* @__PURE__ */ __toESM(require_classnames());
const blockClass = `${pkg.prefix}--datagrid`;
const gcClass = `${blockClass}__grid-container`;
const DatagridContent = ({ datagridState, ariaToolbarLabel, title }) => {
	const { state: inlineEditState, dispatch } = useContext(InlineEditContext);
	const { filterTags, EventEmitter, panelOpen, tableId: contextTableId } = useContext(FilterContext);
	const { activeCellId, gridActive, editId, featureFlags } = inlineEditState;
	const { getTableProps, getFilterFlyoutProps, withVirtualScroll, DatagridPagination, isFetching, CustomizeColumnsTearsheet, filterProps, fullHeightDatagrid, verticalAlign = "center", variableRowHeight, gridTitle, gridDescription, useDenseHeader, withInlineEdit, tableId, DatagridActions, totalColumnsWidth, gridRef, setAllFilters, state, page, rows } = datagridState;
	const { columnResizing } = state;
	const contentRows = DatagridPagination && page || rows;
	const gridAreaRef = useRef(null);
	const multiKeyTrackingRef = useRef(null);
	const carbonPrefix = usePrefix();
	const enableEditableCell = useFeatureFlag$1("enable-datagrid-useEditableCell");
	const enableInlineEdit = useFeatureFlag$1("enable-datagrid-useInlineEdit");
	const enableCustomizeCols = useFeatureFlag$1("enable-datagrid-useCustomizeColumns");
	useEffect(() => {
		dispatch({
			type: "SET_FEATURE_FLAGS",
			payload: {
				"enable-datagrid-useEditableCell": enableEditableCell,
				"enable-datagrid-useInlineEdit": enableInlineEdit,
				"enable-datagrid-useCustomizeColumns": enableCustomizeCols
			}
		});
	}, [
		dispatch,
		enableEditableCell,
		enableCustomizeCols,
		enableInlineEdit
	]);
	useEffect(() => {
		if (featureFlags && (featureFlags?.["enable-datagrid-useEditableCell"] || featureFlags?.["enable-datagrid-useInlineEdit"])) console.error(`Datagrid useEditableCell/useInlineEdit extension has not been enabled via feature flag.`);
	}, [featureFlags]);
	useClickOutside(gridAreaRef, (target) => {
		if (!withInlineEdit) return;
		if (target.closest(`.${blockClass}__inline-edit-button`) || target.closest(`.${blockClass}__inline-edit--select`)) return;
		dispatch({
			type: "REMOVE_GRID_ACTIVE_FOCUS",
			payload: activeCellId
		});
	});
	const renderTable = () => {
		return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Table, {
			...getTableProps?.(),
			className: (0, import_classnames.default)(withVirtualScroll ? `${blockClass}__table-virtual-scroll` : `${blockClass}__table-simple`, `${blockClass}__vertical-align-${verticalAlign}`, { [`${blockClass}__variable-row-height`]: variableRowHeight }, { [`${blockClass}__table-with-inline-edit`]: withInlineEdit }, { [`${blockClass}__table-grid-active`]: gridActive }, { [`${blockClass}__table-is-resizing`]: typeof columnResizing?.isResizingColumn === "string" }, getTableProps?.().className),
			role: withInlineEdit ? "grid" : void 0,
			tabIndex: withInlineEdit ? 0 : -1,
			onKeyDown: withInlineEdit && ((event) => handleGridKeyPress({
				event,
				dispatch,
				instance: datagridState,
				keysPressedList,
				state: inlineEditState,
				usingMac,
				ref: multiKeyTrackingRef,
				carbonPrefix
			})),
			onFocus: withInlineEdit && (() => handleGridFocus(inlineEditState, dispatch)),
			title
		}, (!withVirtualScroll || withVirtualScroll && !isFetching && !contentRows.length) && /* @__PURE__ */ React.createElement(DatagridHead, datagridState), /* @__PURE__ */ React.createElement(DatagridBody, {
			...datagridState,
			rows: contentRows
		})), filterProps?.variation === "panel" && renderPagination());
	};
	const { keysPressedList, usingMac } = useMultipleKeyTracking({
		ref: withInlineEdit ? multiKeyTrackingRef : null,
		containerHasFocus: gridActive,
		isEditing: !!editId
	});
	useEffect(() => {
		if (!withInlineEdit) return;
		const gridElement = document.querySelector(`#${tableId}`);
		const tableHeader = gridElement?.querySelector(`.${carbonPrefix}--data-table-header`);
		gridElement?.style?.setProperty(`--${blockClass}--grid-width`, px((totalColumnsWidth || 0) + 32));
		if (gridActive) gridElement?.style.setProperty(`--${blockClass}--grid-header-height`, px(tableHeader?.clientHeight || 0));
	}, [
		withInlineEdit,
		tableId,
		totalColumnsWidth,
		datagridState,
		gridActive,
		carbonPrefix
	]);
	useSubscribeToEventEmitter(CLEAR_SINGLE_FILTER, (id) => clearSingleFilter(id, setAllFilters, state, contextTableId));
	const renderFilterSummary = () => state.filters.length > 0 && /* @__PURE__ */ React.createElement(FilterSummary, {
		className: `${blockClass}__filter-summary`,
		filters: filterTags,
		clearFilters: () => {
			EventEmitter.dispatch("clearFilters", tableId);
			if (typeof filterProps?.onClearFilters === "function") filterProps.onClearFilters();
		},
		renderLabel: filterProps?.renderLabel,
		overflowType: "tag",
		clearFiltersText: filterProps?.clearFiltersText
	});
	const renderPagination = () => {
		if (contentRows?.length > 0 && !isFetching && DatagridPagination) return /* @__PURE__ */ React.createElement(DatagridPagination, datagridState);
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(TableContainer, {
		className: (0, import_classnames.default)(`${gcClass}`, {
			[`${gcClass}-active`]: gridActive,
			[`${gcClass}-active--without-toolbar`]: withInlineEdit && !DatagridActions,
			[`${gcClass}-inline-edit`]: withInlineEdit,
			[`${blockClass}__full-height`]: withVirtualScroll || fullHeightDatagrid,
			[`${blockClass}__with-pagination`]: DatagridPagination,
			[`${blockClass}__dense-header`]: useDenseHeader
		}),
		title: gridTitle,
		description: gridDescription
	}, /* @__PURE__ */ React.createElement(DatagridToolbar, {
		...datagridState,
		ariaToolbarLabel
	}), /* @__PURE__ */ React.createElement("div", {
		className: (0, import_classnames.default)(`${blockClass}__table-container`, { [`${blockClass}__table-container--filter-open`]: panelOpen }),
		ref: gridAreaRef
	}, filterProps?.variation === "panel" && /* @__PURE__ */ React.createElement(FilterPanel, {
		updateMethod: void 0,
		setAllFilters: void 0,
		...getFilterFlyoutProps?.(),
		title: filterProps.panelTitle,
		filterSections: filterProps.sections,
		autoHideFilters: filterProps.autoHideFilters,
		isFetching
	}), /* @__PURE__ */ React.createElement("div", { className: `${blockClass}__table-container-inner` }, renderFilterSummary(), withInlineEdit ? /* @__PURE__ */ React.createElement("div", { ref: multiKeyTrackingRef }, renderTable()) : withVirtualScroll ? /* @__PURE__ */ React.createElement("div", {
		className: `${blockClass}__virtualScrollContainer`,
		ref: gridRef
	}, renderTable()) : renderTable()))), filterProps?.variation !== "panel" && renderPagination(), CustomizeColumnsTearsheet && /* @__PURE__ */ React.createElement(CustomizeColumnsTearsheet, { instance: datagridState }));
};
DatagridContent.propTypes = {
	ariaToolbarLabel: PropTypes.string,
	datagridState: PropTypes.shape({
		getTableProps: PropTypes.func,
		getFilterFlyoutProps: PropTypes.func,
		withVirtualScroll: PropTypes.bool,
		DatagridActions: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
		DatagridPagination: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
		CustomizeColumnsTearsheet: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
		isFetching: PropTypes.bool,
		skeletonRowCount: PropTypes.number,
		fullHeightDatagrid: PropTypes.bool,
		filterProps: PropTypes.object,
		variableRowHeight: PropTypes.bool,
		useDenseHeader: PropTypes.bool,
		withInlineEdit: PropTypes.bool,
		verticalAlign: PropTypes.string,
		gridTitle: PropTypes.node,
		gridDescription: PropTypes.node,
		page: PropTypes.arrayOf(PropTypes.object),
		rows: PropTypes.arrayOf(PropTypes.object),
		tableId: PropTypes.string,
		totalColumnsWidth: PropTypes.number,
		gridRef: PropTypes.object,
		setAllFilters: PropTypes.func,
		getFilterProps: PropTypes.func,
		state: PropTypes.object
	}),
	title: PropTypes.string
};
//#endregion
export { DatagridContent };
