/**
 * 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.
 */

const require_runtime = require('../../../_virtual/_rolldown/runtime.js');
const require_index = require('../../../node_modules/classnames/index.js');
const require_settings = require('../../../settings.js');
const require_getNodeTextContent = require('../../../global/js/utils/getNodeTextContent.js');
const require_stateReducer = require('./addons/stateReducer.js');
const require_common_column_ids = require('../common-column-ids.js');
const require_DatagridAiLabel = require('./addons/AiLabel/DatagridAiLabel.js');
const require_useInitialColumnSort = require('../useInitialColumnSort.js');
let react = require("react");
react = require_runtime.__toESM(react);
let _carbon_react = require("@carbon/react");
let _carbon_layout = require("@carbon/layout");

//#region src/components/Datagrid/Datagrid/DatagridHeaderRow.tsx
/**
* Copyright IBM Corp. 2020, 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
var import_classnames = /* @__PURE__ */ require_runtime.__toESM(require_index.default);
const blockClass = `${require_settings.pkg.prefix}--datagrid`;
const getAccessibilityProps = (header) => {
	const props = {};
	if (!require_getNodeTextContent.getNodeTextContent(header.Header)) props["aria-hidden"] = true;
	return props;
};
const ResizeHeader = ({ resizerProps, header, handleOnMouseDownResize, originalCol, columnWidths, datagridState, incrementAmount, minWidth, dispatch, onColResizeEnd, resizerAriaLabel, isFetching }) => {
	const { ...headerProps } = resizerProps;
	const mouseDownHandler = (evt) => {
		handleOnMouseDownResize?.(evt, resizerProps);
	};
	const mouseUpHandler = () => {
		require_stateReducer.handleColumnResizeEndEvent(dispatch, onColResizeEnd, header?.id, true);
	};
	const keyDownHandler = (evt) => {
		const { key } = evt;
		if (key === "ArrowLeft" || key === "ArrowRight") {
			const originalColMinWidth = originalCol?.minWidth || 90;
			const currentColumnWidth = header?.id && columnWidths?.[header?.id] || (datagridState?.isTableSortable && Number(originalCol?.width) < originalColMinWidth ? originalColMinWidth : originalCol?.width);
			if (key === "ArrowLeft") {
				if (currentColumnWidth - incrementAmount > Math.max(Number(minWidth), 50)) require_stateReducer.handleColumnResizingEvent(dispatch, header, currentColumnWidth - incrementAmount, true);
			}
			if (key === "ArrowRight") require_stateReducer.handleColumnResizingEvent(dispatch, header, currentColumnWidth + incrementAmount, true);
		}
	};
	const keyUpHandler = () => {
		require_stateReducer.handleColumnResizeEndEvent(dispatch, onColResizeEnd, header?.id, true);
	};
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("input", {
		...headerProps,
		onMouseDown: mouseDownHandler,
		onMouseUp: mouseUpHandler,
		onKeyDown: keyDownHandler,
		onKeyUp: keyUpHandler,
		className: `${blockClass}__col-resizer-range`,
		type: "range",
		defaultValue: originalCol?.width,
		"aria-label": resizerAriaLabel || "Resize column",
		disabled: isFetching
	}), /* @__PURE__ */ react.default.createElement("span", {
		role: "separator",
		className: `${blockClass}__col-resize-indicator`
	}));
};
const getAriaSortValue = (col, datagridState) => {
	const { ascendingSortableLabelText, descendingSortableLabelText, defaultSortableLabelText } = datagridState;
	if (!col) return;
	const { isSorted, isSortedDesc } = col;
	if (!isSorted) return defaultSortableLabelText;
	if (isSorted && !isSortedDesc) return ascendingSortableLabelText;
	if (isSorted && isSortedDesc) return descendingSortableLabelText;
};
const HeaderRow = (datagridState, headRef, headerGroup) => {
	const { resizerAriaLabel, isTableSortable, rows, isFetching, headers } = datagridState;
	require_useInitialColumnSort.useInitialColumnSort(datagridState);
	(0, react.useEffect)(() => {
		const { tableId } = datagridState;
		const gridElement = document.querySelector(`#${tableId}`);
		const tableElement = gridElement?.querySelector("table");
		const headerRowElement = document.querySelector(`#${tableId} .${blockClass}__head`);
		let scrollBuffer = 2;
		if (tableElement) {
			if (tableElement?.scrollWidth > tableElement?.clientWidth) scrollBuffer = 18;
		}
		const tableToolbarHeight = (gridElement?.querySelector(`.${blockClass}__table-toolbar`) || null)?.offsetHeight || 0;
		const setCustomValues = ({ rowHeight, gridHeight }) => {
			headerRowElement?.style.setProperty(`--${blockClass}--row-height`, (0, _carbon_layout.px)(rowHeight));
			headerRowElement?.style.setProperty(`--${blockClass}--grid-height`, (0, _carbon_layout.px)(gridHeight - scrollBuffer - tableToolbarHeight));
			headerRowElement?.style.setProperty(`--${blockClass}--header-height`, (0, _carbon_layout.px)(headerRowElement.offsetHeight));
		};
		setCustomValues({
			gridHeight: gridElement?.offsetHeight,
			rowHeight: headerRowElement?.clientHeight
		});
	}, [
		datagridState.rowSize,
		datagridState.tableId,
		datagridState
	]);
	const [incrementAmount] = (0, react.useState)(2);
	const handleOnMouseDownResize = (event, resizeProps) => {
		const { onMouseDown = () => {} } = { ...resizeProps };
		if (event.button === 2 || event.ctrlKey) {
			event.target.blur();
			return;
		}
		onMouseDown?.(event);
	};
	const { className: headerGroupClassName, ...headerGroupProps } = headerGroup.getHeaderGroupProps({ role: void 0 });
	const renderAILabel = (aiLabel) => {
		if (isTableSortable) return;
		return /* @__PURE__ */ react.default.createElement(require_DatagridAiLabel.DatagridAILabel, { aiLabel });
	};
	const foundAIRow = rows.some((r) => (0, react.isValidElement)(r?.original?.aiLabel) || (0, react.isValidElement)(r?.original?.slug));
	const { key, ...rowProps } = headerGroupProps;
	const withActionsColumn = headers ? !!headers.filter((header) => header.isAction).length : false;
	return /* @__PURE__ */ react.default.createElement(_carbon_react.TableRow, {
		key,
		...rowProps,
		className: (0, import_classnames.default)(`${blockClass}__head`, headerGroupClassName),
		ref: headRef
	}, foundAIRow ? /* @__PURE__ */ react.default.createElement("th", {
		scope: "col",
		"aria-hidden": "false"
	}) : null, datagridState?.headers?.filter(({ isVisible }) => isVisible)?.map((header, index) => {
		if (header.id === require_common_column_ids.selectionColumnId) return header.render("Header", { key: header.id });
		const { minWidth } = header || 50;
		const { visibleColumns, state, dispatch, onColResizeEnd } = datagridState;
		const { columnResizing } = state;
		const { columnWidths } = columnResizing || {};
		const originalCol = visibleColumns[index];
		const { ...headerProps } = header.getHeaderProps({ role: void 0 });
		const resizerProps = header?.getResizerProps?.({ role: void 0 });
		const headerStyle = headerProps?.style;
		const lastVisibleIndex = withActionsColumn ? 2 : 1;
		const isLastVisibleColumn = index === visibleColumns.length - lastVisibleIndex;
		if (headerStyle) Object.assign(headerStyle, {
			flex: isLastVisibleColumn ? "1 1 0" : "0 0 auto",
			overflow: isLastVisibleColumn ? "hidden" : headerStyle.overflow
		});
		return /* @__PURE__ */ react.default.createElement(_carbon_react.TableHeader, {
			...headerProps,
			className: (0, import_classnames.default)(header?.className, {
				[`${blockClass}__resizableColumn`]: resizerProps,
				[`${blockClass}__isResizing`]: header?.isResizing,
				[`${blockClass}__sortableColumn`]: datagridState.isTableSortable && header.id !== "spacer",
				[`${blockClass}__isSorted`]: header?.isSorted,
				[`${blockClass}__header-actions-column`]: header?.isAction,
				[`${blockClass}__with-slug`]: header.slug && react.default.isValidElement(header?.slug),
				[`${blockClass}__with-ai-label`]: header.aiLabel && react.default.isValidElement(header?.aiLabel)
			}, headerProps.className),
			key: header.id,
			"aria-hidden": header.id === "spacer" && "true",
			"aria-sort": header.canSort ? getAriaSortValue(header, datagridState) : "",
			...getAccessibilityProps(header)
		}, header.render("Header"), renderAILabel(header.aiLabel || header.slug), resizerProps && !header.isAction && /* @__PURE__ */ react.default.createElement(ResizeHeader, {
			resizerProps,
			header,
			handleOnMouseDownResize,
			originalCol,
			columnWidths,
			datagridState,
			incrementAmount,
			minWidth,
			dispatch,
			onColResizeEnd,
			resizerAriaLabel,
			isFetching
		}));
	}));
};
const useHeaderRow = (hooks) => {
	const useInstance = (instance) => {
		Object.assign(instance, { HeaderRow });
	};
	hooks.useInstance.push(useInstance);
};

//#endregion
exports.default = useHeaderRow;