/**
 * 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 { useIsomorphicEffect } from "../../global/js/hooks/useIsomorphicEffect.js";
import { getDevtoolsProps } from "../../global/js/utils/devtools.js";
import { CarouselItem } from "./CarouselItem.js";
import React, { useCallback, useEffect, useImperativeHandle, useRef } from "react";
import PropTypes from "prop-types";
import { usePrefix } from "@carbon/react";

//#region src/components/Carousel/Carousel.tsx
/**
* Copyright IBM Corp. 2023, 2023
*
* 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}--carousel`;
const componentName = "Carousel";
const defaults = {
	disableArrowScroll: false,
	onScroll: () => {},
	onChangeIsScrollable: () => {}
};
/**
* The Carousel acts as a scaffold for other Onboarding content.
*
* This component is not intended for general use.
*
* Expected scrolling behavior.
* 1. Scroll the maximum number of visible items at a time.
* 2. The left-most item should always be left-aligned in the viewport.
*
* Exception.
* 1. After scrolling to the last (right-most) item,
*      if some of its content remains hidden,
*      then nudge it to the right until it is right-aligned.
* 2. From the right-aligned position, when scrolling left,
*      the left-most item should again be left-aligned.
*/
const Carousel = React.forwardRef((props, ref) => {
	const { children, className, disableArrowScroll = defaults.disableArrowScroll, fadedEdgeColor, onChangeIsScrollable = defaults.onChangeIsScrollable, onScroll = defaults.onScroll, isScrollMode = false, disableResetOnResize = false, ...rest } = props;
	const carouselRef = useRef(null);
	const scrollRef = useRef(null);
	const leftFadedEdgeRef = useRef(null);
	const rightFadedEdgeRef = useRef(null);
	const childElementsRef = useRef(Array(React.Children.count(children)).fill(useRef(null)));
	const leftFadedEdgeColor = typeof fadedEdgeColor === "object" ? fadedEdgeColor?.left : fadedEdgeColor;
	const rightFadedEdgeColor = typeof fadedEdgeColor === "object" ? fadedEdgeColor?.right : fadedEdgeColor;
	const carbonPrefix = usePrefix();
	const handleOnScroll = useCallback(() => {
		if (!scrollRef.current) return;
		const clientWidth = scrollRef.current?.clientWidth;
		const scrollLeft = parseInt(`${scrollRef.current?.scrollLeft}`, 10);
		const scrollWidth = scrollRef.current?.scrollWidth;
		const scrollLeftMax = scrollWidth - clientWidth;
		const scrollPercent = parseFloat((scrollLeft / scrollLeftMax).toFixed(2)) || 0;
		onChangeIsScrollable(scrollWidth > clientWidth);
		onScroll(scrollPercent);
	}, [onChangeIsScrollable, onScroll]);
	const getElementInView = useCallback((containerRect, elementRect) => {
		const elementLeftIsRightOfContainerLeft = elementRect.left >= containerRect.left;
		const elementRightIsLeftOfContainerRight = elementRect.right <= containerRect.right;
		return elementLeftIsRightOfContainerLeft && elementRightIsLeftOfContainerRight;
	}, []);
	const getElementsInView = useCallback(() => {
		const containerRect = scrollRef?.current?.getBoundingClientRect();
		return childElementsRef.current.filter((el) => getElementInView(containerRect, el.getBoundingClientRect()));
	}, [getElementInView]);
	const getContainerAndChildRectData = useCallback(() => {
		const containerRect = scrollRef?.current?.getBoundingClientRect();
		const elementRectsInView = getElementsInView().map((el) => el.getBoundingClientRect());
		return {
			containerRect,
			elementRectsInView,
			visibleWidth: elementRectsInView.reduce((accumulator, currentValue) => accumulator + currentValue.width, 0)
		};
	}, [getElementsInView]);
	const handleScrollNext = useCallback(() => {
		if (!scrollRef.current) return;
		const { containerRect, visibleWidth } = getContainerAndChildRectData();
		const scrollValue = visibleWidth > 0 ? visibleWidth : containerRect?.width;
		scrollRef.current.scrollLeft += scrollValue;
	}, [getContainerAndChildRectData]);
	const handleScrollPrev = useCallback(() => {
		if (!scrollRef.current) return;
		const { containerRect, elementRectsInView, visibleWidth } = getContainerAndChildRectData();
		const scrollValue = visibleWidth > 0 ? visibleWidth - elementRectsInView[0].left : (containerRect?.width ?? 0) + (containerRect?.left ?? 0);
		scrollRef.current.scrollLeft -= scrollValue;
	}, [getContainerAndChildRectData]);
	const handleScrollReset = useCallback(() => {
		if (!scrollRef.current) return;
		scrollRef.current.scrollLeft = 0;
		handleOnScroll();
	}, [handleOnScroll]);
	const handleScrollToView = useCallback((itemNumber) => {
		updateAriaHiddenTabIndex(itemNumber);
		childElementsRef.current[itemNumber]?.scrollIntoView();
	}, []);
	const getFocusableElements = (container) => {
		const notQuery = `:not(.${carbonPrefix}--visually-hidden,.${carbonPrefix}--btn--disabled,[aria-hidden="true"],[disabled])`;
		const queryButton = `button${notQuery}`;
		const queryInput = `input${notQuery}`;
		const querySelect = `select${notQuery}`;
		const queryTextarea = `textarea${notQuery}`;
		const query = `${queryButton},${`[href]${notQuery}`},${`a${notQuery}`},${queryInput},${querySelect},${queryTextarea},${`[tabindex="0"]${notQuery}`}`;
		return container?.querySelectorAll(`${query}`) ?? [];
	};
	const updateAriaHiddenTabIndex = (itemNumber) => {
		!isScrollMode && childElementsRef.current?.forEach((item, idx) => {
			const isActive = idx === itemNumber;
			item?.setAttribute("aria-hidden", String(!isActive));
			getFocusableElements(item).forEach((el) => {
				el.tabIndex = isActive ? 0 : -1;
			});
		});
	};
	useEffect(() => {
		setTimeout(() => {
			updateAriaHiddenTabIndex(0);
			handleOnScroll();
		}, 0);
	}, []);
	useEffect(() => {
		const handleWindowResize = () => {
			if (!scrollRef.current) return;
			if (!disableResetOnResize) {
				scrollRef.current.scrollLeft = 0;
				handleOnScroll();
			}
		};
		window.addEventListener("resize", handleWindowResize);
		return () => window.removeEventListener("resize", handleWindowResize);
	}, [handleOnScroll]);
	useEffect(() => {
		const handleScrollend = () => {
			handleOnScroll();
		};
		const scrollDiv = scrollRef.current;
		scrollDiv?.addEventListener("scrollend", handleScrollend);
		return () => scrollDiv?.removeEventListener("scrollend", handleScrollend);
	}, [handleOnScroll]);
	useEffect(() => {
		function handleWheel(event) {
			if (event.shiftKey) {
				event.stopPropagation();
				event.preventDefault();
				event.cancelBubble = false;
			}
		}
		const scrollDiv = scrollRef.current;
		if (scrollDiv) {
			scrollDiv.addEventListener("wheel", handleWheel, { passive: false });
			return () => {
				scrollDiv.removeEventListener("wheel", handleWheel);
			};
		}
	}, []);
	useEffect(() => {
		function handleKeydown(event) {
			const { key } = event;
			if ((key === "ArrowLeft" || key === "ArrowRight") && disableArrowScroll) {
				event.stopPropagation();
				event.preventDefault();
				event.cancelBubble = false;
			}
		}
		const carouselDiv = carouselRef.current;
		if (carouselDiv) {
			carouselDiv.addEventListener("keydown", handleKeydown);
			return () => carouselDiv.removeEventListener("keydown", handleKeydown);
		}
	}, [disableArrowScroll]);
	useImperativeHandle(ref, () => ({
		scrollNext() {
			handleScrollNext();
		},
		scrollPrev() {
			handleScrollPrev();
		},
		scrollReset() {
			handleScrollReset();
		},
		scrollToView(itemNumber) {
			handleScrollToView(itemNumber);
		}
	}), [
		handleScrollNext,
		handleScrollPrev,
		handleScrollReset,
		handleScrollToView
	]);
	useIsomorphicEffect(() => {
		if (leftFadedEdgeRef?.current && leftFadedEdgeRef.current.style) leftFadedEdgeRef.current.style.background = `linear-gradient(90deg, ${leftFadedEdgeColor}, transparent)`;
	}, [leftFadedEdgeRef, leftFadedEdgeColor]);
	useIsomorphicEffect(() => {
		if (rightFadedEdgeRef?.current && rightFadedEdgeRef.current.style) rightFadedEdgeRef.current.style.background = `linear-gradient(270deg, ${rightFadedEdgeColor}, transparent)`;
	}, [rightFadedEdgeRef, rightFadedEdgeColor]);
	return /* @__PURE__ */ React.createElement("div", {
		...rest,
		tabIndex: -1,
		className: (0, import_classnames.default)(blockClass, className),
		ref: carouselRef,
		...getDevtoolsProps(componentName)
	}, /* @__PURE__ */ React.createElement("div", { className: (0, import_classnames.default)(`${blockClass}__elements-container`) }, /* @__PURE__ */ React.createElement("div", {
		className: `${blockClass}__elements`,
		ref: scrollRef
	}, React.Children.map(children, (child, index) => {
		return /* @__PURE__ */ React.createElement(CarouselItem, {
			key: index,
			ref: (element) => {
				childElementsRef.current[index] = element;
			}
		}, child);
	})), leftFadedEdgeColor && /* @__PURE__ */ React.createElement("div", {
		ref: leftFadedEdgeRef,
		className: `${blockClass}__elements-container--scrolled`
	}), rightFadedEdgeColor && /* @__PURE__ */ React.createElement("div", {
		ref: rightFadedEdgeRef,
		className: `${blockClass}__elements-container--scroll-max`
	})));
});
Carousel.displayName = componentName;
Carousel.propTypes = {
	children: PropTypes.node.isRequired,
	className: PropTypes.string,
	disableArrowScroll: PropTypes.bool,
	fadedEdgeColor: PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
		left: PropTypes.string,
		right: PropTypes.string
	})]),
	isScrollMode: PropTypes.bool,
	onChangeIsScrollable: PropTypes.func,
	onScroll: PropTypes.func
};

//#endregion
export { Carousel };