/**
 * 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 { createOverflowHandler } from "./overflowHandler.js";
import { PageHeaderTitleBreadcrumb } from "./PageHeaderTitleBreadcrumb.js";
import React, { forwardRef, useEffect, useRef } from "react";
import { Breadcrumb, BreadcrumbItem, usePrefix } from "@carbon/react";

//#region src/components/PageHeader/next/PageHeaderBreadcrumbOverflow.tsx
/**
* Copyright IBM Corp. 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.
*/
var import_classnames = /* @__PURE__ */ __toESM(require_classnames());
const PageHeaderBreadcrumbOverflow = forwardRef(({ renderOverflowBreadcrumb, className, children, ...other }, ref) => {
	const [hiddenBreadcrumbs, setHiddenBreadcrumbs] = React.useState([]);
	const fallbackRef = useRef(null);
	const componentRef = ref ?? fallbackRef;
	const carbonPrefix = usePrefix();
	useEffect(() => {
		if (!componentRef) return;
		const breadcrumbList = componentRef?.current.querySelector(`.${carbonPrefix}--breadcrumb`);
		createOverflowHandler({
			container: breadcrumbList,
			onChange: (_, hidden) => {
				setHiddenBreadcrumbs(hidden);
			}
		});
	}, []);
	const renderChildren = () => {
		const filteredBreadcrumbs = React.Children.toArray(children).filter((child) => {
			if (React.isValidElement(child)) return child.type === BreadcrumbItem || child.type === PageHeaderTitleBreadcrumb;
		});
		if (filteredBreadcrumbs) {
			const overflowBreadcrumb = renderOverflowBreadcrumb?.(hiddenBreadcrumbs);
			if (!overflowBreadcrumb) return children;
			const clonedTitleBreadcrumb = React.cloneElement(overflowBreadcrumb, {
				key: "cloned overflow breadcrumb item",
				"data-fixed": true,
				className: (0, import_classnames.default)(`${pkg.prefix}--page-header-breadcrumb-overflow-item`, { [`${pkg.prefix}--page-header-overflow-breadcrumb-item-with-items`]: hiddenBreadcrumbs.length })
			});
			const clonedChildren = [...filteredBreadcrumbs];
			clonedChildren.splice(filteredBreadcrumbs.length - 1, 0, clonedTitleBreadcrumb);
			return clonedChildren;
		}
		return children;
	};
	return /* @__PURE__ */ React.createElement(Breadcrumb, {
		className: (0, import_classnames.default)(className, `${pkg.prefix}--page-header-breadcrumb-overflow`),
		ref: componentRef,
		...other
	}, renderChildren());
});
PageHeaderBreadcrumbOverflow.displayName = "PageHeaderBreadcrumbOverflow";

//#endregion
export { PageHeaderBreadcrumbOverflow };