'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "HorizontalBarChart", {
    enumerable: true,
    get: function() {
        return HorizontalBarChart;
    }
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _useHorizontalBarChartStylesstyles = require("./useHorizontalBarChartStyles.styles");
const _index = require("./index");
const _chartutilities = require("@fluentui/chart-utilities");
const _index1 = require("../../utilities/index");
const _reactutilities = require("@fluentui/react-utilities");
const _reacttheme = require("@fluentui/react-theme");
const _reacttabster = require("@fluentui/react-tabster");
const _ChartPopover = require("../CommonComponents/ChartPopover");
const _FocusableTooltipText = require("../../utilities/FocusableTooltipText");
const _index2 = require("../../index");
const HorizontalBarChart = /*#__PURE__*/ _react.forwardRef((props, forwardedRef)=>{
    const legendContainer = _react.useRef(null);
    const _uniqLineText = (0, _reactutilities.useId)('_HorizontalLine_');
    const _refArray = [];
    const _isRTL = (0, _index1.useRtl)();
    const barChartSvgRef = /*#__PURE__*/ _react.createRef();
    const _emptyChartId = (0, _reactutilities.useId)('_HBC_empty');
    let _barHeight;
    let _calloutAnchorPoint;
    let isSingleBar = true;
    let _showToolTipOnSegment = !props.hideTooltip;
    const [hoverValue, setHoverValue] = _react.useState('');
    const [lineColor, setLineColor] = _react.useState('');
    const [legend, setLegend] = _react.useState('');
    const [xCalloutValue, setXCalloutValue] = _react.useState('');
    const [yCalloutValue, setYCalloutValue] = _react.useState('');
    const [barCalloutProps, setBarCalloutProps] = _react.useState();
    const [barSpacingInPercent, setBarSpacingInPercent] = _react.useState(0);
    const [isPopoverOpen, setPopoverOpen] = _react.useState(false);
    const [clickPosition, setClickPosition] = _react.useState({
        x: 0,
        y: 0
    });
    const [selectedLegend, setSelectedLegend] = _react.useState('');
    const [activeLegend, setActiveLegend] = _react.useState('');
    function _refCallback(element, legendTitle) {
        _refArray.push({
            index: legendTitle,
            refElement: element
        });
    }
    function _hoverOn(event, hoverVal, point) {
        if ((!isPopoverOpen || legend !== point.legend) && _calloutAnchorPoint !== point && (_legendHighlighted(point.legend) || _noLegendHighlighted())) {
            _calloutAnchorPoint = point;
            let x = 0;
            let y = 0;
            if ('clientX' in event && event.clientX && event.clientY) {
                // Mouse event
                x = event.clientX;
                y = event.clientY;
            } else {
                // Focus event
                const targetRect = event.target.getBoundingClientRect();
                x = targetRect.left + targetRect.width / 2;
                y = targetRect.top + targetRect.height / 2;
            }
            updatePosition(x, y);
            setHoverValue(hoverVal);
            setLineColor(point.color);
            setLegend(point.legend);
            setXCalloutValue(point.xAxisCalloutData);
            setYCalloutValue(point.yAxisCalloutData);
            setBarCalloutProps(point);
        // ToDo - Confirm setting multiple state variables like this is performant.
        }
    }
    function _hoverOff() {
    /*ToDo. To fix*/ }
    const _handleChartMouseLeave = ()=>{
        _calloutAnchorPoint = null;
        if (isPopoverOpen) {
            setPopoverOpen(false);
            setHoverValue('');
            setLineColor('');
            setLegend('');
        }
    };
    const _adjustProps = ()=>{
        _barHeight = props.barHeight || 12;
    };
    const _getChartDataText = (data)=>{
        /* return props.barChartCustomData ? (
        <div role="text">{props.barChartCustomData(data)}</div>
      ) : ( */ return _getDefaultTextData(data);
    //)
    };
    function _createLegends(chartProps) {
        const legendItems = chartProps.flatMap((point)=>{
            var _point_chartData;
            var _point_chartData_map;
            return (_point_chartData_map = (_point_chartData = point.chartData) === null || _point_chartData === void 0 ? void 0 : _point_chartData.map((dataPoint)=>{
                var _dataPoint_legend;
                const legend = (_dataPoint_legend = dataPoint.legend) !== null && _dataPoint_legend !== void 0 ? _dataPoint_legend : '';
                var _dataPoint_color;
                const color = (_dataPoint_color = dataPoint.color) !== null && _dataPoint_color !== void 0 ? _dataPoint_color : '';
                return {
                    title: legend,
                    color,
                    action: ()=>setSelectedLegend(selectedLegend === legend ? '' : legend),
                    hoverAction: ()=>{
                        _handleChartMouseLeave();
                        setActiveLegend(legend);
                    },
                    onMouseOutAction: ()=>setActiveLegend('')
                };
            })) !== null && _point_chartData_map !== void 0 ? _point_chartData_map : [];
        });
        return /*#__PURE__*/ _react.createElement(_index2.Legends, {
            legends: legendItems,
            centerLegends: true,
            overflowText: props.legendsOverflowText,
            ...props.legendProps
        });
    }
    function _getDefaultTextData(data) {
        const chartDataMode = props.chartDataMode || 'default';
        if (chartDataMode === 'hidden') {
            return /*#__PURE__*/ _react.createElement(_react.Fragment, null); // No text data for hidden mode
        }
        const { culture } = props;
        const accessibilityData = (0, _index1.getAccessibleDataObject)(data.chartDataAccessibilityData, 'text', false);
        if (!isSingleBar) {
            const total = data.chartData.reduce((acc, point)=>acc + (point.horizontalBarChartdata.x ? point.horizontalBarChartdata.x : 0), 0);
            return /*#__PURE__*/ _react.createElement("div", {
                className: classes.chartTitleRight,
                ...accessibilityData
            }, (0, _chartutilities.formatToLocaleString)(total, culture));
        }
        const chartData = data.chartData[0];
        const x = chartData.horizontalBarChartdata.x;
        const y = chartData.horizontalBarChartdata.total;
        switch(chartDataMode){
            case 'default':
                return /*#__PURE__*/ _react.createElement("div", {
                    className: classes.chartTitleRight,
                    ...accessibilityData
                }, (0, _chartutilities.formatToLocaleString)(x, culture));
            case 'fraction':
                return /*#__PURE__*/ _react.createElement("div", accessibilityData, /*#__PURE__*/ _react.createElement("span", {
                    className: classes.chartTitleRight
                }, (0, _chartutilities.formatToLocaleString)(x, culture)), /*#__PURE__*/ _react.createElement("span", {
                    className: classes.chartDataTextDenominator
                }, ' / ' + (0, _chartutilities.formatToLocaleString)(y, culture)));
            case 'percentage':
                const dataRatioPercentage = `${(0, _chartutilities.formatToLocaleString)(Math.round(x / y * 100), culture)}%`;
                return /*#__PURE__*/ _react.createElement("div", {
                    className: classes.chartTitleRight,
                    ...accessibilityData
                }, dataRatioPercentage);
        }
    }
    function _createBenchmark(data) {
        if (data.chartData[0].horizontalBarChartdata.total === undefined) {
            return /*#__PURE__*/ _react.createElement(_react.Fragment, null);
        }
        const totalData = data.chartData[0].horizontalBarChartdata.total;
        const benchmarkData = data.chartData[0].data;
        const benchmarkRatio = Math.round((benchmarkData ? benchmarkData : 0) / totalData * 100);
        const benchmarkStyles = {
            left: 'calc(' + benchmarkRatio + '% - 4px)'
        };
        return /*#__PURE__*/ _react.createElement("div", {
            className: classes.benchmarkContainer
        }, /*#__PURE__*/ _react.createElement("div", {
            className: classes.triangle,
            style: benchmarkStyles
        }));
    }
    /**
   * This functions returns an array of <rect> elements, which form the bars
   * For each bar an x value, and a width needs to be specified
   * The computations are done based on percentages
   * Extra margin is also provided, in the x value to provide some spacing in between the bars
   */ function _createBars(data) {
        var _data_chartData;
        const noOfBars = ((_data_chartData = data.chartData) === null || _data_chartData === void 0 ? void 0 : _data_chartData.reduce((count, point)=>count += (point.data || 0) > 0 ? 1 : 0, 0)) || 1;
        const totalMarginPercent = barSpacingInPercent * (noOfBars - 1);
        const defaultColors = [
            _reacttheme.tokens.colorPaletteBlueForeground2,
            _reacttheme.tokens.colorPaletteCornflowerForeground2,
            _reacttheme.tokens.colorPaletteDarkGreenForeground2,
            _reacttheme.tokens.colorPaletteNavyForeground2,
            _reacttheme.tokens.colorPaletteDarkOrangeForeground2
        ];
        // calculating starting point of each bar and it's range
        const startingPoint = [];
        const total = data.chartData.reduce((acc, point)=>acc + (point.horizontalBarChartdata.x ? point.horizontalBarChartdata.x : 0), 0);
        let prevPosition = 0;
        let value = 0;
        let sumOfPercent = 0;
        data.chartData.map((point, index)=>{
            const pointData = point.horizontalBarChartdata.x ? point.horizontalBarChartdata.x : 0;
            value = pointData / total * 100;
            if (value < 0) {
                value = 0;
            } else if (value < 1 && value !== 0) {
                value = 1;
            }
            sumOfPercent += value;
            return sumOfPercent;
        });
        /**
     * The %age of the space occupied by the margin needs to subtracted
     * while computing the scaling ratio, since the margins are not being
     * scaled down, only the data is being scaled down from a higher percentage to lower percentage
     * Eg: 95% of the space is taken by the bars, 5% by the margins
     * Now if the sumOfPercent is 120% -> This needs to be scaled down to 95%, not 100%
     * since that's only space available to the bars
     */ const scalingRatio = sumOfPercent !== 0 ? (sumOfPercent - totalMarginPercent) / 100 : 1;
        const bars = data.chartData.map((point, index)=>{
            const color = point.color ? point.color : defaultColors[Math.floor(Math.random() * 4 + 1)];
            const pointData = point.horizontalBarChartdata.x ? point.horizontalBarChartdata.x : 0;
            if (index > 0) {
                prevPosition += value;
            }
            value = pointData / total * 100;
            if (value < 0) {
                value = 0;
            } else if (value < 1 && value !== 0) {
                value = 1 / scalingRatio;
            } else {
                value = value / scalingRatio;
            }
            startingPoint.push(prevPosition);
            const xValue = point.horizontalBarChartdata.x;
            const placeholderIndex = 1;
            const isLegendSelected = _legendHighlighted(point.legend) || _noLegendHighlighted();
            // Render bar label instead of placeholder bar for absolute-scale variant
            if (index === placeholderIndex && props.variant === _index.HorizontalBarChartVariant.AbsoluteScale) {
                if (props.hideLabels) {
                    return /*#__PURE__*/ _react.createElement("text", {
                        key: index
                    });
                }
                const barValue = data.chartData[0].horizontalBarChartdata.x;
                return /*#__PURE__*/ _react.createElement("text", {
                    key: index,
                    x: `${_isRTL ? 100 - startingPoint[index] : startingPoint[index]}%`,
                    y: _barHeight / 2,
                    dominantBaseline: "central",
                    transform: `translate(${_isRTL ? -4 : 4})`,
                    className: classes.barLabel,
                    "aria-hidden": true
                }, (0, _index1.formatScientificLimitWidth)(barValue));
            }
            return /*#__PURE__*/ _react.createElement("rect", {
                key: index,
                x: `${_isRTL ? 100 - startingPoint[index] - value - index * barSpacingInPercent : startingPoint[index] + index * barSpacingInPercent}%`,
                y: 0,
                width: value + '%',
                height: _barHeight,
                fill: color,
                onMouseOver: _showToolTipOnSegment && point.legend !== '' ? (event)=>_hoverOn(event, xValue, point) : undefined,
                onFocus: _showToolTipOnSegment && point.legend !== '' ? (event)=>_hoverOn(event, xValue, point) : undefined,
                role: "img",
                "aria-label": _getAriaLabel(point),
                onBlur: _hoverOff,
                onMouseLeave: _hoverOff,
                className: classes.barWrapper,
                opacity: isLegendSelected ? 1 : 0.1,
                tabIndex: _legendHighlighted(point.legend) || _noLegendHighlighted() ? 0 : undefined
            });
        });
        return bars;
    }
    const _getAriaLabel = (point)=>{
        var _point_callOutAccessibilityData;
        const legend = point.xAxisCalloutData || point.legend;
        var _point_horizontalBarChartdata_total;
        const yValue = point.yAxisCalloutData || (point.horizontalBarChartdata ? `${point.horizontalBarChartdata.x}/${(_point_horizontalBarChartdata_total = point.horizontalBarChartdata.total) !== null && _point_horizontalBarChartdata_total !== void 0 ? _point_horizontalBarChartdata_total : ''}` : 0);
        return ((_point_callOutAccessibilityData = point.callOutAccessibilityData) === null || _point_callOutAccessibilityData === void 0 ? void 0 : _point_callOutAccessibilityData.ariaLabel) || (legend ? `${legend}, ` : '') + `${yValue}.`;
    };
    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);
        }
    }
    _react.useEffect(()=>{
        var _barChartSvgRef_current;
        const svgWidth = (barChartSvgRef === null || barChartSvgRef === void 0 ? void 0 : (_barChartSvgRef_current = barChartSvgRef.current) === null || _barChartSvgRef_current === void 0 ? void 0 : _barChartSvgRef_current.getBoundingClientRect().width) || 0;
        const MARGIN_WIDTH_IN_PX = 3;
        if (svgWidth) {
            const currentBarSpacing = MARGIN_WIDTH_IN_PX / svgWidth * 100;
            setBarSpacingInPercent(currentBarSpacing);
        }
    }, [
        barChartSvgRef
    ]);
    function _legendHighlighted(barLegend) {
        if (barLegend === undefined) {
            return false;
        }
        return selectedLegend === barLegend || selectedLegend === '' && activeLegend === barLegend;
    }
    /**
   * This function checks if none of the legends is selected or hovered.*/ function _noLegendHighlighted() {
        return selectedLegend === '' && activeLegend === '';
    }
    const { data } = props;
    _adjustProps();
    const classes = (0, _useHorizontalBarChartStylesstyles.useHorizontalBarChartStyles)(props);
    const focusAttributes = (0, _reacttabster.useFocusableGroup)();
    const legendButtons = _createLegends(data);
    let datapoint = 0;
    return !_isChartEmpty() ? /*#__PURE__*/ _react.createElement("div", {
        className: classes.root,
        onMouseLeave: _handleChartMouseLeave
    }, data.map((points, index)=>{
        if (points.chartData && points.chartData[0] && points.chartData[0].horizontalBarChartdata.x) {
            datapoint = points.chartData[0].horizontalBarChartdata.x;
        } else {
            datapoint = 0;
        }
        isSingleBar = props.showLegendForSinglePointBar ? false : points.chartData.length === 1 || points.chartData.length > 1 && points.chartData[1].legend === '';
        if (isSingleBar) {
            points.chartData[1] = {
                legend: '',
                horizontalBarChartdata: {
                    x: points.chartData[0].horizontalBarChartdata.total - datapoint,
                    total: points.chartData[0].horizontalBarChartdata.total
                },
                color: _reacttheme.tokens.colorBackgroundOverlay
            };
        }
        // Hide right side text of chart title for absolute-scale variant
        const chartDataText = props.variant === _index.HorizontalBarChartVariant.AbsoluteScale ? null : _getChartDataText(points);
        const bars = _createBars(points);
        const keyVal = _uniqLineText + '_' + index;
        // ToDo - Showtriangle property is per data series. How to account for it in the new stylesheet
        /*         const classes = useHorizontalBarChartStyles(props.styles!, {
          width: props.width,
          showTriangle: !!points!.chartData![0].data,
          variant: props.variant,
        }); */ return /*#__PURE__*/ _react.createElement("div", {
            key: index
        }, /*#__PURE__*/ _react.createElement("div", {
            className: classes.items,
            ...focusAttributes
        }, /*#__PURE__*/ _react.createElement("div", {
            className: classes.chartTitle
        }, points.chartTitle && /*#__PURE__*/ _react.createElement(_FocusableTooltipText.FocusableTooltipText, {
            className: classes.chartTitleLeft,
            content: points.chartTitle,
            accessibilityData: points.chartTitleAccessibilityData
        }), chartDataText), points.chartData[0].data && _createBenchmark(points), /*#__PURE__*/ _react.createElement("svg", {
            ref: barChartSvgRef,
            className: classes.chart,
            "aria-label": points.chartTitle
        }, /*#__PURE__*/ _react.createElement("g", {
            id: keyVal,
            ref: (e)=>{
                _refCallback(e, points.chartData[0].legend);
            },
            // NOTE: points.chartData![0] contains current data value
            onClick: ()=>{
                const p = points.chartData[0];
                if (p && p.onClick) {
                    p.onClick();
                }
            }
        }, bars))));
    }), /*#__PURE__*/ _react.createElement(_ChartPopover.ChartPopover, {
        xCalloutValue: xCalloutValue,
        yCalloutValue: yCalloutValue,
        culture: props.culture,
        clickPosition: clickPosition,
        isPopoverOpen: isPopoverOpen,
        legend: legend,
        YValue: hoverValue,
        color: lineColor,
        isCalloutForStack: false,
        customCallout: {
            customizedCallout: props.onRenderCalloutPerHorizontalBar ? props.onRenderCalloutPerHorizontalBar(barCalloutProps) : undefined,
            customCalloutProps: props.calloutPropsPerDataPoint ? props.calloutPropsPerDataPoint(barCalloutProps) : undefined
        },
        isCartesian: false
    }), !isSingleBar && /*#__PURE__*/ _react.createElement("div", {
        ref: (e)=>{
            legendContainer.current = e;
        },
        className: classes.legendContainer
    }, legendButtons)) : /*#__PURE__*/ _react.createElement("div", {
        id: _emptyChartId,
        role: 'alert',
        style: {
            opacity: '0'
        },
        "aria-label": 'Graph has no data to display'
    });
//TODO validate and fix focus border for issue for popover
});
HorizontalBarChart.displayName = 'HorizontalBarChart';
