'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "HorizontalBarChartWithAxis", {
    enumerable: true,
    get: function() {
        return HorizontalBarChartWithAxis;
    }
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _d3array = require("d3-array");
const _d3scale = require("d3-scale");
const _Legends = require("../../components/Legends/Legends");
const _reactutilities = require("@fluentui/react-utilities");
const _CartesianChart = require("../CommonComponents/CartesianChart");
const _ChartPopover = require("../CommonComponents/ChartPopover");
const _index = require("../../utilities/index");
const _vbcutils = require("../../utilities/vbc-utils");
const _hooks = require("../../utilities/hooks");
const HorizontalBarChartWithAxis = /*#__PURE__*/ _react.forwardRef((props = {
    yAxisCategoryOrder: 'default'
}, forwardedRef)=>{
    var _props_legendProps, _props_legendProps1, _props_legendProps2, _props_legendProps3;
    const _refArray = [];
    const _calloutId = (0, _reactutilities.useId)('callout');
    const _isRtl = (0, _index.useRtl)();
    const _xAxisType = props.data && props.data.length > 0 ? (0, _index.getTypeOfAxis)(props.data[0].x, true) : _index.XAxisTypes.NumericAxis;
    const _yAxisType = props.data && props.data.length > 0 ? (0, _index.getTypeOfAxis)(props.data[0].y, false) : _index.YAxisType.StringAxis;
    const _emptyChartId = (0, _reactutilities.useId)('_HBCWithAxis_empty');
    let _points = [];
    let _barHeight = 0;
    let _colors = [];
    let _margins;
    let _bars;
    let _yAxisLabels;
    let _xMax;
    let _calloutAnchorPoint;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let _longestBarPositiveTotalValue;
    let _longestBarNegativeTotalValue;
    let _domainMargin = _index.MIN_DOMAIN_MARGIN;
    var _props_yAxisPadding;
    let _yAxisPadding = (_props_yAxisPadding = props.yAxisPadding) !== null && _props_yAxisPadding !== void 0 ? _props_yAxisPadding : 0.5;
    const { cartesianChartRef, legendsRef: _legendsRef } = (0, _hooks.useImageExport)(props.componentRef, props.hideLegend);
    const X_ORIGIN = 0;
    const [color, setColor] = _react.useState('');
    const [dataForHoverCard, setDataForHoverCard] = _react.useState(0);
    const [isLegendSelected, setIsLegendSelected] = _react.useState(((_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.selectedLegends) && props.legendProps.selectedLegends.length > 0 || ((_props_legendProps1 = props.legendProps) === null || _props_legendProps1 === void 0 ? void 0 : _props_legendProps1.selectedLegend) !== undefined);
    const [isLegendHovered, setIsLegendHovered] = _react.useState(false);
    var _props_legendProps_selectedLegend;
    const [selectedLegendTitle, setSelectedLegendTitle] = _react.useState((_props_legendProps_selectedLegend = (_props_legendProps2 = props.legendProps) === null || _props_legendProps2 === void 0 ? void 0 : _props_legendProps2.selectedLegend) !== null && _props_legendProps_selectedLegend !== void 0 ? _props_legendProps_selectedLegend : '');
    const [xCalloutValue, setXCalloutValue] = _react.useState('');
    const [yCalloutValue, setYCalloutValue] = _react.useState('');
    const [selectedLegends, setSelectedLegends] = _react.useState(((_props_legendProps3 = props.legendProps) === null || _props_legendProps3 === void 0 ? void 0 : _props_legendProps3.selectedLegends) || []);
    const [dataPointCalloutProps, setDataPointCalloutProps] = _react.useState();
    const [callOutAccessibilityData, setCallOutAccessibilityData] = _react.useState();
    const [isPopoverOpen, setPopoverOpen] = _react.useState(false);
    const [clickPosition, setClickPosition] = _react.useState({
        x: 0,
        y: 0
    });
    const prevPropsRef = _react.useRef(null);
    _react.useEffect(()=>{
        if (prevPropsRef.current) {
            var _prevProps_legendProps, _props_legendProps;
            const prevProps = prevPropsRef.current;
            if (!(0, _index.areArraysEqual)((_prevProps_legendProps = prevProps.legendProps) === null || _prevProps_legendProps === void 0 ? void 0 : _prevProps_legendProps.selectedLegends, (_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.selectedLegends)) {
                var _props_legendProps1;
                setSelectedLegends(((_props_legendProps1 = props.legendProps) === null || _props_legendProps1 === void 0 ? void 0 : _props_legendProps1.selectedLegends) || []);
            }
        }
        prevPropsRef.current = props;
    }, [
        props
    ]);
    function _adjustProps() {
        _points = props.data || [];
        _barHeight = props.barHeight || 32;
        const defaultPalette = [
            (0, _index.getColorFromToken)(_index.DataVizPalette.color6),
            (0, _index.getColorFromToken)(_index.DataVizPalette.color1),
            (0, _index.getColorFromToken)(_index.DataVizPalette.color5),
            (0, _index.getColorFromToken)(_index.DataVizPalette.color7)
        ];
        _colors = props.colors || defaultPalette;
    }
    function _getMargins(margins) {
        _margins = margins;
    }
    function _renderContentForOnlyBars(point) {
        const { useSingleColor = false } = props;
        let selectedPointIndex = 0;
        props.data.forEach((yDataPoint, index)=>{
            if (yDataPoint.y === point.y) {
                selectedPointIndex = index;
            }
        });
        let color;
        if (useSingleColor) {
            //if useSingle color , then check if user has given a palette or not
            // and pick the first color from that or else from our paltette.
            color = props.colors ? _createColors()(1) : (0, _index.getNextColor)(1, 0);
        } else {
            color = point.color ? point.color : props.colors ? _createColors()(point.x) : (0, _index.getNextColor)(selectedPointIndex, 0);
        }
        return /*#__PURE__*/ _react.createElement(_react.Fragment, null, /*#__PURE__*/ _react.createElement(_ChartPopover.ChartPopover, {
            XValue: point.xAxisCalloutData || point.x.toString(),
            legend: point.legend,
            YValue: point.yAxisCalloutData || point.y,
            color: color,
            culture: props.culture,
            clickPosition: clickPosition,
            isPopoverOpen: isPopoverOpen
        }));
    }
    function _renderCallout(props) {
        return props ? _renderContentForOnlyBars(props) : null;
    }
    function _getCustomizedCallout() {
        return props.onRenderCalloutPerDataPoint ? props.onRenderCalloutPerDataPoint(dataPointCalloutProps, _renderCallout) : null;
    }
    function _getGraphData(xScale, yScale, containerHeight, containerWidth, xElement, yElement) {
        const stackedChartData = (0, _index.groupChartDataByYValue)(_points);
        const longestBars = (0, _index.computeLongestBars)(stackedChartData, X_ORIGIN);
        _longestBarPositiveTotalValue = longestBars.longestPositiveBar;
        _longestBarNegativeTotalValue = longestBars.longestNegativeBar;
        const { xBarScale, yBarScale } = _yAxisType === _index.YAxisType.NumericAxis ? _getScales(containerHeight, containerWidth, true) : _getScales(containerHeight, containerWidth, false);
        const xRange = xBarScale.range();
        let allBars = [];
        // when the chart mounts, the xRange[1] is sometimes seen to be < 0 (like -40) while xRange[0] > 0.
        if (xRange[0] < xRange[1]) {
            allBars = stackedChartData.map((singleBarData)=>_yAxisType === _index.YAxisType.NumericAxis ? _createNumericBars(containerHeight, containerWidth, xElement, yElement, singleBarData, xBarScale, yBarScale) : _createStringBars(containerHeight, containerWidth, xElement, yElement, singleBarData, xBarScale, yBarScale)).flat();
        }
        return _bars = allBars;
    }
    function _createColors() {
        const increment = _colors.length <= 1 ? 1 : 1 / (_colors.length - 1);
        const { useSingleColor = false } = props;
        if (useSingleColor) {
            return (_p)=>{
                const { colors } = props;
                return colors && colors.length > 0 ? colors[0] : (0, _index.getColorFromToken)(_index.DataVizPalette.color16);
            };
        }
        const domainValues = [];
        for(let i = 0; i < _colors.length; i++){
            domainValues.push(increment * i * _xMax);
        }
        const colorScale = (0, _d3scale.scaleLinear)().domain(domainValues).range(_colors);
        return colorScale;
    }
    function _refCallback(element, legendTitle) {
        _refArray.push({
            index: legendTitle,
            refElement: element
        });
    }
    function _onBarHover(point, color, mouseEvent) {
        mouseEvent.persist();
        if ((isLegendSelected === false || _isLegendHighlighted(point.legend)) && _calloutAnchorPoint !== point) {
            _calloutAnchorPoint = point;
            setPopoverOpen(true);
            _updatePosition(mouseEvent.clientX, mouseEvent.clientY);
            setDataForHoverCard(point.x);
            setSelectedLegendTitle(point.legend);
            setColor(props.useSingleColor || props.enableGradient ? color : point.color);
            // To display callout value, if no callout value given, taking given point.x value as a string.
            setXCalloutValue(point.yAxisCalloutData || point.y.toString());
            setYCalloutValue(point.xAxisCalloutData || point.x.toString());
            setDataPointCalloutProps(point);
            setCallOutAccessibilityData(point.callOutAccessibilityData);
        }
    }
    function _onBarLeave() {
        setPopoverOpen(false);
    }
    function _handleChartMouseLeave() {
        _calloutAnchorPoint = null;
        setPopoverOpen(false);
    }
    function _onBarFocus(event, point, refArrayIndexNumber, color) {
        let cx = 0;
        let cy = 0;
        const targetRect = event.target.getBoundingClientRect();
        cx = targetRect.left + targetRect.width / 2;
        cy = targetRect.top + targetRect.height / 2;
        _updatePosition(cx, cy);
        if ((isLegendSelected === false || _isLegendHighlighted(point.legend)) && _calloutAnchorPoint !== point) {
            _refArray.forEach((obj, index)=>{
                if (refArrayIndexNumber === index) {
                    setPopoverOpen(true);
                    setSelectedLegendTitle(point.legend);
                    setDataForHoverCard(point.x);
                    setColor(props.useSingleColor ? color : point.color);
                    setXCalloutValue(point.yAxisCalloutData || point.y.toString());
                    setYCalloutValue(point.xAxisCalloutData || point.x.toString());
                    setDataPointCalloutProps(point);
                    setCallOutAccessibilityData(point.callOutAccessibilityData);
                }
            });
        }
    }
    function _getScales(containerHeight, containerWidth, isNumericScale) {
        const xMax = _longestBarPositiveTotalValue;
        const xMin = _longestBarNegativeTotalValue;
        const xDomain = [
            Math.min(X_ORIGIN, xMin),
            Math.max(X_ORIGIN, xMax)
        ];
        if (isNumericScale) {
            const yMax = (0, _d3array.max)(_points, (point)=>point.y);
            const yMin = (0, _d3array.min)(_points, (point)=>point.y);
            const yDomainMax = Math.max(yMax, props.yMaxValue || 0);
            // Default to 0 if yMinValue is not provided.
            const yMinProp = props.yMinValue || 0;
            const yDomainMin = Math.min(yMin, yMinProp);
            const xBarScale = (0, _d3scale.scaleLinear)().domain(xDomain).nice().range([
                _margins.left,
                containerWidth - _margins.right
            ]);
            const yBarScale = (0, _d3scale.scaleLinear)().domain([
                yDomainMin,
                yDomainMax
            ]).range([
                containerHeight - (_margins.bottom + _domainMargin),
                _margins.top + _domainMargin
            ]);
            return {
                xBarScale,
                yBarScale
            };
        } else {
            // please note these padding default values must be consistent in here
            // and CatrtesianChartBase w for more details refer example
            // http://using-d3js.com/04_07_ordinal_scales.html
            const yBarScale = (0, _d3scale.scaleBand)().domain(_yAxisLabels).range([
                containerHeight - (_margins.bottom + _domainMargin),
                _margins.top + _domainMargin
            ]).padding(_yAxisPadding);
            const xBarScale = (0, _d3scale.scaleLinear)().domain(xDomain).nice().range([
                _margins.left,
                containerWidth - _margins.right
            ]);
            return {
                xBarScale,
                yBarScale
            };
        }
    }
    function _createNumericBars(containerHeight, containerWidth, xElement, yElement, singleBarData, xBarScale, yBarScale) {
        const { useSingleColor = false } = props;
        const sortedBars = [
            ...singleBarData
        ];
        sortedBars.sort((a, b)=>{
            const aValue = typeof a.y === 'number' ? a.y : parseFloat(a.y);
            const bValue = typeof b.y === 'number' ? b.y : parseFloat(b.y);
            return bValue - aValue;
        });
        let prevWidthPositive = 0;
        let prevWidthNegative = 0;
        let prevPoint = 0;
        const totalPositiveBars = singleBarData.filter((point)=>point.x >= X_ORIGIN).length;
        const totalNegativeBars = singleBarData.length - totalPositiveBars;
        let currPositiveCounter = 0;
        let currNegativeCounter = 0;
        const bars = sortedBars.map((point, index)=>{
            let shouldHighlight = true;
            if (isLegendHovered || isLegendSelected) {
                shouldHighlight = _isLegendHighlighted(point.legend);
            }
            if (point.x >= X_ORIGIN) {
                ++currPositiveCounter;
            }
            if (point.x < X_ORIGIN) {
                ++currNegativeCounter;
            }
            const barStartX = _isRtl ? containerWidth - (_margins.right + Math.max(xBarScale(point.x + X_ORIGIN), xBarScale(X_ORIGIN)) - _margins.left) : Math.min(xBarScale(point.x + X_ORIGIN), xBarScale(X_ORIGIN));
            const barHeight = Math.max(yBarScale(point.y), 0);
            if (barHeight < 1) {
                return /*#__PURE__*/ _react.createElement(_react.Fragment, {
                    key: point.x
                }, " ");
            }
            let startColor;
            if (useSingleColor) {
                //if useSingle color , then check if user has given a palette or not
                // and pick the first color from that or else from our paltette.
                startColor = props.colors ? _createColors()(1) : (0, _index.getNextColor)(1, 0);
            } else {
                startColor = props.colors ? _createColors()(point.x) : (0, _index.getNextColor)(index, 0);
            }
            startColor = point.color && !useSingleColor ? point.color : startColor;
            const prevBarWidth = Math.abs(xBarScale(prevPoint + X_ORIGIN) - xBarScale(X_ORIGIN));
            prevPoint > X_ORIGIN ? prevWidthPositive += prevBarWidth : prevWidthNegative += prevBarWidth;
            const currentWidth = Math.abs(xBarScale(point.x + X_ORIGIN) - xBarScale(X_ORIGIN));
            const gapWidthLTR = currentWidth > 2 && (point.x > X_ORIGIN && currPositiveCounter !== totalPositiveBars || point.x < X_ORIGIN && (totalPositiveBars !== 0 || currNegativeCounter > 1)) ? 2 : 0;
            const gapWidthRTL = currentWidth > 2 && (point.x > X_ORIGIN && (totalNegativeBars !== 0 || currPositiveCounter > 1) || point.x < X_ORIGIN && currNegativeCounter !== totalNegativeBars) ? 2 : 0;
            let xStart = X_ORIGIN;
            if (_isRtl) {
                xStart = point.x > X_ORIGIN ? barStartX - prevWidthPositive : barStartX + prevWidthNegative;
            } else {
                xStart = point.x > X_ORIGIN ? barStartX + prevWidthPositive : barStartX - prevWidthNegative;
            }
            prevPoint = point.x;
            return /*#__PURE__*/ _react.createElement(_react.Fragment, {
                key: `${index}_${point.x}`
            }, /*#__PURE__*/ _react.createElement("rect", {
                key: point.y,
                x: xStart,
                y: yBarScale(point.y) - _barHeight / 2,
                width: currentWidth - (_isRtl ? gapWidthRTL : gapWidthLTR),
                height: _barHeight,
                ref: (e)=>{
                    _refCallback(e, point.legend);
                },
                rx: props.roundCorners ? 3 : 0,
                onClick: point.onClick,
                onMouseOver: (event)=>_onBarHover(point, startColor, event),
                "aria-label": _getAriaLabel(point),
                role: "img",
                "aria-labelledby": `toolTip${_calloutId}`,
                onMouseLeave: _onBarLeave,
                onFocus: (event)=>_onBarFocus(event, point, index, startColor),
                onBlur: _onBarLeave,
                fill: startColor,
                opacity: shouldHighlight ? 1 : 0.1,
                tabIndex: shouldHighlight ? 0 : undefined
            }));
        });
        return bars;
    }
    function _getUniqueYValues() {
        var _props_data;
        const mapY = {};
        (_props_data = props.data) === null || _props_data === void 0 ? void 0 : _props_data.forEach((point)=>{
            mapY[point.y] = point.y;
        });
        const uniqueY = Object.values(mapY);
        return uniqueY;
    }
    function _calculateAppropriateBarHeight(data, totalWidth, innerPadding) {
        const result = (0, _vbcutils.getClosestPairDiffAndRange)(data);
        if (!result || result[1] === 0) {
            return 16;
        }
        const closestPairDiff = result[0];
        let range = result[1];
        const yMax = (0, _d3array.max)(_points, (point)=>point.y);
        // Since we are always rendering from 0 to yMax, we need to ensure that the range is at least yMax
        // to calculate the bar height correctly.
        range = Math.max(range, yMax);
        // Refer to https://microsoft.github.io/fluentui-charting-contrib/docs/rfcs/fix-overlapping-bars-on-continuous-axes
        // for the derivation of the following formula.
        const barWidth = Math.floor(totalWidth * closestPairDiff * (1 - innerPadding) / (range + closestPairDiff * (1 - innerPadding)));
        return barWidth;
    }
    function _getDomainMarginsForHorizontalBarChart(containerHeight) {
        _domainMargin = _index.MIN_DOMAIN_MARGIN;
        const uniqueY = _getUniqueYValues();
        /** Rate at which the space between the bars changes wrt the bar height */ _yAxisPadding = _yAxisPadding === 1 ? 0.99 : _yAxisPadding;
        const barGapRate = _yAxisPadding / (1 - _yAxisPadding);
        const numBars = uniqueY.length + (uniqueY.length - 1) * barGapRate;
        // Total height available to render the bars
        const totalHeight = containerHeight - (_margins.top + _index.MIN_DOMAIN_MARGIN) - (_margins.bottom + _index.MIN_DOMAIN_MARGIN);
        if (_yAxisType !== _index.YAxisType.StringAxis) {
            // Calculate bar height dynamically
            _barHeight = props.barHeight || _calculateAppropriateBarHeight(uniqueY, totalHeight, _yAxisPadding);
            _barHeight = Math.max(_barHeight, 1);
            _domainMargin += _barHeight / 2;
        } else {
            // Calculate the appropriate bar height
            _barHeight = props.barHeight || totalHeight / numBars;
            /** Total height required to render the bars. Directly proportional to bar height */ const reqHeight = numBars * _barHeight;
            if (totalHeight >= reqHeight) {
                // Center align the chart by setting equal left and right margins for domain
                _domainMargin = _index.MIN_DOMAIN_MARGIN + (totalHeight - reqHeight) / 2;
            }
        }
        return {
            ..._margins,
            top: _margins.top + _domainMargin,
            bottom: _margins.bottom + _domainMargin
        };
    }
    function _createStringBars(containerHeight, containerWidth, xElement, yElement, singleBarData, xBarScale, yBarScale) {
        const { useSingleColor = false } = props;
        let prevWidthPositive = 0;
        let prevWidthNegative = 0;
        let prevPoint = 0;
        const totalPositiveBars = singleBarData.filter((point)=>point.x >= X_ORIGIN).length;
        const totalNegativeBars = singleBarData.length - totalPositiveBars;
        let currPositiveCounter = 0;
        let currNegativeCounter = 0;
        const bars = singleBarData.map((point, index)=>{
            let shouldHighlight = true;
            if (isLegendHovered || isLegendSelected) {
                shouldHighlight = _isLegendHighlighted(point.legend);
            }
            if (point.x >= X_ORIGIN) {
                ++currPositiveCounter;
            }
            if (point.x < X_ORIGIN) {
                ++currNegativeCounter;
            }
            const barStartX = _isRtl ? containerWidth - (_margins.right + Math.max(xBarScale(point.x + X_ORIGIN), xBarScale(X_ORIGIN)) - _margins.left) : Math.min(xBarScale(point.x + X_ORIGIN), xBarScale(X_ORIGIN));
            const barHeight = Math.max(yBarScale(point.y), 0);
            if (barHeight < 1) {
                return /*#__PURE__*/ _react.createElement(_react.Fragment, {
                    key: point.x
                }, " ");
            }
            let startColor;
            if (useSingleColor) {
                //if useSingle color , then check if user has given a palette or not
                // and pick the first color from that or else from our paltette.
                startColor = props.colors ? _createColors()(1) : (0, _index.getNextColor)(1, 0);
            } else {
                startColor = props.colors ? _createColors()(point.x) : (0, _index.getNextColor)(index, 0);
            }
            startColor = point.color && !useSingleColor ? point.color : startColor;
            const prevBarWidth = Math.abs(xBarScale(prevPoint + X_ORIGIN) - xBarScale(X_ORIGIN));
            prevPoint > 0 ? prevWidthPositive += prevBarWidth : prevWidthNegative += prevBarWidth;
            const currentWidth = Math.abs(xBarScale(point.x + X_ORIGIN) - xBarScale(X_ORIGIN));
            const gapWidthLTR = currentWidth > 2 && (point.x > X_ORIGIN && currPositiveCounter !== totalPositiveBars || point.x < X_ORIGIN && (totalPositiveBars !== 0 || currNegativeCounter > 1)) ? 2 : 0;
            const gapWidthRTL = currentWidth > 2 && (point.x > X_ORIGIN && (totalNegativeBars !== 0 || currPositiveCounter > 1) || point.x < X_ORIGIN && currNegativeCounter !== totalNegativeBars) ? 2 : 0;
            prevPoint = point.x;
            let xStart = X_ORIGIN;
            if (_isRtl) {
                xStart = point.x > X_ORIGIN ? barStartX - prevWidthPositive : barStartX + prevWidthNegative;
            } else {
                xStart = point.x > X_ORIGIN ? barStartX + prevWidthPositive : barStartX - prevWidthNegative;
            }
            return /*#__PURE__*/ _react.createElement(_react.Fragment, {
                key: `${index}_${point.x}`
            }, /*#__PURE__*/ _react.createElement("rect", {
                transform: `translate(0,${0.5 * (yBarScale.bandwidth() - _barHeight)})`,
                key: point.x,
                x: xStart,
                y: yBarScale(point.y),
                rx: props.roundCorners ? 3 : 0,
                width: currentWidth - (_isRtl ? gapWidthRTL : gapWidthLTR),
                height: _barHeight,
                "aria-labelledby": `toolTip${_calloutId}`,
                "aria-label": _getAriaLabel(point),
                role: "img",
                ref: (e)=>{
                    _refCallback(e, point.legend);
                },
                onClick: point.onClick,
                onMouseOver: (event)=>_onBarHover(point, startColor, event),
                onMouseLeave: _onBarLeave,
                onBlur: _onBarLeave,
                opacity: shouldHighlight ? 1 : 0.1,
                onFocus: (event)=>_onBarFocus(event, point, index, startColor),
                fill: startColor,
                tabIndex: shouldHighlight ? 0 : undefined
            }));
        });
        return bars;
    }
    function _onLegendHover(customMessage) {
        if (!_isLegendSelected()) {
            setIsLegendHovered(true);
            setSelectedLegendTitle(customMessage);
        }
    }
    function _onLegendLeave(isLegendFocused) {
        if (!!isLegendFocused || !_isLegendSelected()) {
            setIsLegendHovered(false);
            setSelectedLegendTitle('');
            setIsLegendSelected(isLegendFocused ? false : _isLegendSelected());
        }
    }
    function _getLegendData(data) {
        const { useSingleColor } = props;
        const actions = [];
        const mapLegendToColor = {};
        data.forEach((point, _index1)=>{
            // eslint-disable-next-line @typescript-eslint/no-shadow
            const color = useSingleColor ? props.colors ? _createColors()(1) : (0, _index.getNextColor)(1, 0) : point.color;
            mapLegendToColor[point.legend] = color;
        });
        Object.entries(mapLegendToColor).forEach(([legendTitle, color])=>{
            // mapping data to the format Legends component needs
            const legend = {
                title: legendTitle,
                color,
                hoverAction: ()=>{
                    _handleChartMouseLeave();
                    _onLegendHover(legendTitle);
                },
                // eslint-disable-next-line @typescript-eslint/no-shadow
                onMouseOutAction: (isLegendSelected)=>{
                    _onLegendLeave(isLegendSelected);
                }
            };
            actions.push(legend);
        });
        const legends = /*#__PURE__*/ _react.createElement(_Legends.Legends, {
            legends: actions,
            enabledWrapLines: props.enabledLegendsWrapLines,
            overflowText: props.legendsOverflowText,
            ...props.legendProps,
            onChange: _onLegendSelectionChange,
            legendRef: _legendsRef
        });
        return legends;
    }
    function _isLegendSelected() {
        return isLegendSelected;
    }
    /**
   * This function checks if the given legend is highlighted or not.
   * A legend can be highlighted in 2 ways:
   * 1. selection: if the user clicks on it
   * 2. hovering: if there is no selected legend and the user hovers over it
   */ function _isLegendHighlighted(legend) {
        return _getHighlightedLegend().includes(legend);
    }
    function _getHighlightedLegend() {
        return selectedLegends.length > 0 ? selectedLegends : selectedLegendTitle ? [
            selectedLegendTitle
        ] : [];
    }
    function _onLegendSelectionChange(selectedLegends, event, currentLegend) {
        var _props_legendProps, _props_legendProps1;
        if ((_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.canSelectMultipleLegends) {
            setSelectedLegends(selectedLegends);
            setSelectedLegendTitle(currentLegend === null || currentLegend === void 0 ? void 0 : currentLegend.title);
        } else {
            setSelectedLegends(selectedLegends.slice(-1));
            setSelectedLegendTitle(currentLegend === null || currentLegend === void 0 ? void 0 : currentLegend.title);
        }
        setIsLegendSelected(selectedLegends.length > 0);
        if ((_props_legendProps1 = props.legendProps) === null || _props_legendProps1 === void 0 ? void 0 : _props_legendProps1.onChange) {
            props.legendProps.onChange(selectedLegends, event, currentLegend);
        }
    }
    function _getAxisData(yAxisData) {
        if (yAxisData && yAxisData.yAxisDomainValues.length) {
            // For HBCWA x and y Values are swapped
            const { yAxisDomainValues: domainValue } = yAxisData;
            _xMax = Math.max(domainValue[domainValue.length - 1], props.xMaxValue || 0);
        }
    }
    function _getAriaLabel(point) {
        var _point_callOutAccessibilityData;
        const xValue = point.xAxisCalloutData || point.x;
        const yValue = point.yAxisCalloutData || point.y;
        return ((_point_callOutAccessibilityData = point.callOutAccessibilityData) === null || _point_callOutAccessibilityData === void 0 ? void 0 : _point_callOutAccessibilityData.ariaLabel) || `${xValue}. ` + `${yValue}.`;
    }
    function _getChartTitle() {
        const { chartTitle, data } = props;
        return (chartTitle ? `${chartTitle}. ` : '') + `Horizontal bar chart with ${(data === null || data === void 0 ? void 0 : data.length) || 0} bars. `;
    }
    function _getOrderedYAxisLabels() {
        const shouldOrderYAxisLabelsByCategoryOrder = _yAxisType === _index.YAxisType.StringAxis && props.yAxisCategoryOrder !== 'default';
        if (!shouldOrderYAxisLabelsByCategoryOrder) {
            // Keep the original ordering logic as the default behavior to ensure backward compatibility
            const reversedBars = [
                ..._points
            ].reverse();
            return reversedBars.map((point)=>point.y);
        }
        return (0, _index.sortAxisCategories)(_mapCategoryToValues(), props.yAxisCategoryOrder);
    }
    function _mapCategoryToValues() {
        const categoryToValues = {};
        _points.forEach((point)=>{
            if (!categoryToValues[point.y]) {
                categoryToValues[point.y] = [];
            }
            categoryToValues[point.y].push(point.x);
        });
        return categoryToValues;
    }
    function _isChartEmpty() {
        return !(props.data && props.data.length > 0);
    }
    function _updatePosition(newX, newY) {
        const threshold = 1; // Set a threshold for movement
        const { x, y } = clickPosition;
        // Calculate the distance moved
        const distance = Math.sqrt(Math.pow(newX - x, 2) + Math.pow(newY - y, 2));
        // Update the position only if the distance moved is greater than the threshold
        if (distance > threshold) {
            setClickPosition({
                x: newX,
                y: newY
            });
            setPopoverOpen(true);
        }
    }
    function _getDomainNRangeValues(points, margins, width, chartType, isRTL, xAxisType, barWidth, tickValues) {
        let domainNRangeValue;
        if (xAxisType === _index.XAxisTypes.NumericAxis) {
            domainNRangeValue = (0, _index.domainRangeOfNumericForHorizontalBarChartWithAxis)(points, margins, width, isRTL, X_ORIGIN);
        } else {
            domainNRangeValue = {
                dStartValue: 0,
                dEndValue: 0,
                rStartValue: 0,
                rEndValue: 0
            };
        }
        return domainNRangeValue;
    }
    if (!_isChartEmpty()) {
        _adjustProps();
        const calloutProps = {
            color: color,
            legend: selectedLegendTitle,
            XValue: xCalloutValue,
            YValue: yCalloutValue ? yCalloutValue : dataForHoverCard,
            ...props.calloutProps,
            ...(0, _index.getAccessibleDataObject)(callOutAccessibilityData),
            customCallout: {
                customizedCallout: _getCustomizedCallout() !== null ? _getCustomizedCallout() : undefined,
                customCalloutProps: props.calloutPropsPerDataPoint ? props.calloutPropsPerDataPoint(dataPointCalloutProps) : undefined
            },
            isCartesian: true,
            isPopoverOpen,
            clickPosition
        };
        const tickParams = {
            tickValues: props.tickValues,
            tickFormat: props.tickFormat
        };
        _yAxisLabels = _getOrderedYAxisLabels();
        _xMax = Math.max((0, _d3array.max)(_points, (point)=>point.x), props.xMaxValue || 0);
        const legendBars = _getLegendData(_points);
        return /*#__PURE__*/ _react.createElement(_CartesianChart.CartesianChart, {
            yAxisPadding: _yAxisPadding,
            ...props,
            chartTitle: _getChartTitle(),
            points: _points,
            chartType: _index.ChartTypes.HorizontalBarChartWithAxis,
            xAxisType: _xAxisType,
            yAxisType: _yAxisType,
            getDomainNRangeValues: _getDomainNRangeValues,
            stringDatasetForYAxisDomain: _yAxisLabels,
            calloutProps: calloutProps,
            tickParams: tickParams,
            legendBars: legendBars,
            createYAxis: _index.createYAxisForHorizontalBarChartWithAxis,
            createStringYAxis: _index.createStringYAxisForHorizontalBarChartWithAxis,
            getMinMaxOfYAxis: _index.findHBCWANumericMinMaxOfY,
            barwidth: _barHeight,
            getmargins: _getMargins,
            getYDomainMargins: _getDomainMarginsForHorizontalBarChart,
            getGraphData: _getGraphData,
            getAxisData: _getAxisData,
            onChartMouseLeave: _handleChartMouseLeave,
            componentRef: cartesianChartRef,
            /* eslint-disable react/jsx-no-bind */ // eslint-disable-next-line @typescript-eslint/no-shadow
            children: (props)=>{
                return /*#__PURE__*/ _react.createElement(_react.Fragment, null, /*#__PURE__*/ _react.createElement("g", null, _bars));
            }
        });
    } else {
        return /*#__PURE__*/ _react.createElement("div", {
            id: _emptyChartId,
            role: 'alert',
            style: {
                opacity: '0'
            },
            "aria-label": 'Graph has no data to display'
        });
    }
});
HorizontalBarChartWithAxis.displayName = 'HorizontalBarChartWithAxis';
