/**
 * 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 { getNodeTextContent } from "../../../global/js/utils/getNodeTextContent.js";
import { handleColumnResizeEndEvent, handleColumnResizingEvent } from "./addons/stateReducer.js";
import "../common-column-ids.js";
import { DatagridAILabel } from "./addons/AiLabel/DatagridAiLabel.js";
import { useInitialColumnSort } from "../useInitialColumnSort.js";
import React, { isValidElement, useEffect, useState } from "react";
import { TableHeader, TableRow } from "@carbon/react";
import { px } from "@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__ */ __toESM(require_classnames());
const blockClass = `${pkg.prefix}--datagrid`;
const getAccessibilityProps = (header) => {
	const props = {};
	if (!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 = () => {
		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)) handleColumnResizingEvent(dispatch, header, currentColumnWidth - incrementAmount, true);
			}
			if (key === "ArrowRight") handleColumnResizingEvent(dispatch, header, currentColumnWidth + incrementAmount, true);
		}
	};
	const keyUpHandler = () => {
		handleColumnResizeEndEvent(dispatch, onColResizeEnd, header?.id, true);
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.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.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;
	useInitialColumnSort(datagridState);
	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`, px(rowHeight));
			headerRowElement?.style.setProperty(`--${blockClass}--grid-height`, px(gridHeight - scrollBuffer - tableToolbarHeight));
			headerRowElement?.style.setProperty(`--${blockClass}--header-height`, px(headerRowElement.offsetHeight));
		};
		setCustomValues({
			gridHeight: gridElement?.offsetHeight,
			rowHeight: headerRowElement?.clientHeight
		});
	}, [
		datagridState.rowSize,
		datagridState.tableId,
		datagridState
	]);
	const [incrementAmount] = 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.createElement(DatagridAILabel, { aiLabel });
	};
	const foundAIRow = rows.some((r) => isValidElement(r?.original?.aiLabel) || isValidElement(r?.original?.slug));
	const { key, ...rowProps } = headerGroupProps;
	const withActionsColumn = headers ? !!headers.filter((header) => header.isAction).length : false;
	return /* @__PURE__ */ React.createElement(TableRow, {
		key,
		...rowProps,
		className: (0, import_classnames.default)(`${blockClass}__head`, headerGroupClassName),
		ref: headRef
	}, foundAIRow ? /* @__PURE__ */ React.createElement("th", {
		scope: "col",
		"aria-hidden": "false"
	}) : null, datagridState?.headers?.filter(({ isVisible }) => isVisible)?.map((header, index) => {
		if (header.id === "datagridSelection") 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.createElement(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.isValidElement(header?.slug),
				[`${blockClass}__with-ai-label`]: header.aiLabel && React.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.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
export { useHeaderRow as default };
