'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "DonutChart", {
    enumerable: true,
    get: function() {
        return DonutChart;
    }
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _index = require("./Pie/index");
const _useDonutChartStylesstyles = require("./useDonutChartStyles.styles");
const _chartutilities = require("@fluentui/chart-utilities");
const _index1 = require("../../utilities/index");
const _index2 = require("../../index");
const _reactutilities = require("@fluentui/react-utilities");
const _reacttabster = require("@fluentui/react-tabster");
const _ChartPopover = require("../CommonComponents/ChartPopover");
const _hooks = require("../../utilities/hooks");
const MIN_LEGEND_CONTAINER_HEIGHT = 40;
const DonutChart = /*#__PURE__*/ _react.forwardRef(({ innerRadius = 0, hideLabels = true, ...restProps }, forwardedRef)=>{
    var _props_legendProps, _props_titleStyles_titleFont, _props_titleStyles;
    const props = {
        innerRadius,
        hideLabels,
        ...restProps
    };
    const { chartContainerRef: _rootElem, legendsRef: _legendsRef } = (0, _hooks.useImageExport)(props.componentRef, props.hideLegend, false);
    const _uniqText = (0, _reactutilities.useId)('_Pie_');
    /* eslint-disable @typescript-eslint/no-explicit-any */ let _calloutAnchorPoint;
    let _emptyChartId;
    const legendContainer = _react.useRef(null);
    const prevSize = _react.useRef({});
    const [value, setValue] = _react.useState('');
    const [legend, setLegend] = _react.useState('');
    const [_width, setWidth] = _react.useState(props.width || 200);
    const [_height, setHeight] = _react.useState(props.height || 200);
    const [activeLegend, setActiveLegend] = _react.useState(undefined);
    const [color, setColor] = _react.useState('');
    const [xCalloutValue, setXCalloutValue] = _react.useState('');
    const [yCalloutValue, setYCalloutValue] = _react.useState('');
    const [selectedLegends, setSelectedLegends] = _react.useState(((_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.selectedLegends) || []);
    const [focusedArcId, setFocusedArcId] = _react.useState('');
    const [dataPointCalloutProps, setDataPointCalloutProps] = _react.useState();
    const [refSelected, setRefSelected] = _react.useState(null);
    const [isPopoverOpen, setPopoverOpen] = _react.useState(false);
    const prevPropsRef = _react.useRef(null);
    _react.useEffect(()=>{
        _fitParentContainer();
    }, []);
    _react.useEffect(()=>{
        if (prevPropsRef.current) {
            var _prevProps_legendProps, _props_legendProps;
            const prevProps = prevPropsRef.current;
            if (!(0, _index1.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
    ]);
    _react.useEffect(()=>{
        if (prevSize.current.height !== props.height || prevSize.current.width !== props.width) {
            _fitParentContainer();
        }
        prevSize.current.height = props.height;
        prevSize.current.width = props.width;
    }, [
        props.width,
        props.height
    ]);
    function _elevateToMinimums(data) {
        let sumOfData = 0;
        const minPercent = 0.01;
        const elevatedData = [];
        data.forEach((item)=>{
            sumOfData += item.data;
        });
        data.forEach((item)=>{
            elevatedData.push(minPercent * sumOfData > item.data && item.data > 0 ? {
                ...item,
                data: minPercent * sumOfData,
                yAxisCalloutData: item.yAxisCalloutData === undefined ? item.data.toLocaleString() : item.yAxisCalloutData
            } : item);
        });
        return elevatedData;
    }
    function _createLegends(chartData) {
        if (props.order === 'sorted') {
            chartData.sort((a, b)=>{
                return b.data - a.data;
            });
        }
        const legendDataItems = chartData.map((point, index)=>{
            const color = point.color;
            // mapping data to the format Legends component needs
            const legend = {
                title: point.legend,
                color,
                hoverAction: ()=>{
                    _handleChartMouseLeave();
                    setActiveLegend(point.legend);
                },
                onMouseOutAction: ()=>{
                    setActiveLegend(undefined);
                }
            };
            return legend;
        });
        const legends = /*#__PURE__*/ _react.createElement(_index2.Legends, {
            legends: legendDataItems,
            centerLegends: true,
            overflowText: props.legendsOverflowText,
            ...props.legendProps,
            // eslint-disable-next-line react/jsx-no-bind
            onChange: _onLegendSelectionChange,
            legendRef: _legendsRef
        });
        return legends;
    }
    function _onLegendSelectionChange(selectedLegends, event, currentLegend) {
        var _props_legendProps, _props_legendProps1;
        if (props.legendProps && ((_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.canSelectMultipleLegends)) {
            setSelectedLegends(selectedLegends);
        } else {
            setSelectedLegends(selectedLegends.slice(-1));
        }
        if ((_props_legendProps1 = props.legendProps) === null || _props_legendProps1 === void 0 ? void 0 : _props_legendProps1.onChange) {
            props.legendProps.onChange(selectedLegends, event, currentLegend);
        }
    }
    function _focusCallback(data, id, e, targetElement) {
        setPopoverOpen(_noLegendsHighlighted() || _isLegendHighlighted(data.legend));
        setValue(data.data.toString());
        setLegend(data.legend);
        setColor(data.color);
        setXCalloutValue(data.xAxisCalloutData);
        setYCalloutValue(data.yAxisCalloutData);
        setFocusedArcId(id);
        setDataPointCalloutProps(data);
        setRefSelected(targetElement);
    }
    function _hoverCallback(data, e, targetElement) {
        if (_calloutAnchorPoint !== data) {
            _calloutAnchorPoint = data;
            setPopoverOpen(_noLegendsHighlighted() || _isLegendHighlighted(data.legend));
            setValue(data.data.toString());
            setLegend(data.legend);
            setColor(data.color);
            setXCalloutValue(data.xAxisCalloutData);
            setYCalloutValue(data.yAxisCalloutData);
            setDataPointCalloutProps(data);
            setRefSelected(targetElement);
        }
    }
    function _onBlur() {
        setFocusedArcId('');
    }
    function _hoverLeave() {
    /**/ }
    function _handleChartMouseLeave() {
        _calloutAnchorPoint = null;
        setPopoverOpen(false);
    }
    function _valueInsideDonut(valueInsideDonut, data) {
        const highlightedLegends = _getHighlightedLegend();
        if (valueInsideDonut !== undefined && (highlightedLegends.length === 1 || isPopoverOpen)) {
            const pointValue = data.find((point)=>_isLegendHighlighted(point.legend));
            return pointValue ? pointValue.yAxisCalloutData ? pointValue.yAxisCalloutData : pointValue.data : valueInsideDonut;
        } else if (highlightedLegends.length > 0) {
            let totalValue = 0;
            data.forEach((point)=>{
                if (highlightedLegends.includes(point.legend)) {
                    totalValue += point.data;
                }
            });
            return totalValue;
        } else {
            return valueInsideDonut;
        }
    }
    function _toLocaleString(data) {
        const localeString = (0, _chartutilities.formatToLocaleString)(data, props.culture);
        if (!localeString) {
            return data;
        }
        return localeString === null || localeString === void 0 ? void 0 : localeString.toString();
    }
    /**
     * This function returns
     * the selected legend if there is one
     * or the hovered legend if none of the legends is selected.
     */ function _getHighlightedLegend() {
        return selectedLegends.length > 0 ? selectedLegends : activeLegend ? [
            activeLegend
        ] : [];
    }
    function _isLegendHighlighted(legend) {
        return _getHighlightedLegend().includes(legend);
    }
    function _noLegendsHighlighted() {
        return _getHighlightedLegend().length === 0;
    }
    function _isChartEmpty() {
        return !(props.data && props.data.chartData && props.data.chartData.filter((d)=>d.data > 0).length > 0);
    }
    function _addDefaultColors(donutChartDataPoint) {
        return donutChartDataPoint ? donutChartDataPoint.map((item, index)=>{
            let defaultColor;
            if (typeof item.color === 'undefined') {
                defaultColor = (0, _index1.getNextColor)(index, 0);
            } else {
                defaultColor = (0, _index1.getColorFromToken)(item.color);
            }
            return {
                ...item,
                defaultColor
            };
        }) : [];
    }
    /**
     * When screen resizes, along with screen, chart also auto adjusted.
     * This method used to adjust height and width of the charts.
     */ function _fitParentContainer() {
        //_reqID = requestAnimationFrame(() => {
        let legendContainerHeight;
        if (props.hideLegend) {
            // If there is no legend, need not to allocate some space from total chart space.
            legendContainerHeight = 0;
        } else {
            const legendContainerComputedStyles = legendContainer.current && getComputedStyle(legendContainer.current);
            legendContainerHeight = (legendContainer.current && legendContainer.current.getBoundingClientRect().height || MIN_LEGEND_CONTAINER_HEIGHT) + parseFloat(legendContainerComputedStyles && legendContainerComputedStyles.marginTop || '0') + parseFloat(legendContainerComputedStyles && legendContainerComputedStyles.marginBottom || '0');
        }
        if (props.parentRef || _rootElem.current) {
            const container = props.parentRef ? props.parentRef : _rootElem.current;
            const currentContainerWidth = container.getBoundingClientRect().width;
            const currentContainerHeight = container.getBoundingClientRect().height > legendContainerHeight ? container.getBoundingClientRect().height : 200;
            const shouldResize = _width !== currentContainerWidth || _height !== currentContainerHeight - legendContainerHeight;
            if (shouldResize) {
                setWidth(currentContainerWidth);
                setHeight(currentContainerHeight - legendContainerHeight);
            }
        }
    //});
    }
    const { data, hideLegend = false } = props;
    const points = _addDefaultColors(data === null || data === void 0 ? void 0 : data.chartData);
    const classes = (0, _useDonutChartStylesstyles.useDonutChartStyles)(props);
    const legendBars = _createLegends(points.filter((d)=>d.data >= 0));
    const donutMarginHorizontal = props.hideLabels ? 0 : 80;
    const donutMarginVertical = props.hideLabels ? 0 : 40;
    const titleHeight = (data === null || data === void 0 ? void 0 : data.chartTitle) ? Math.max((typeof ((_props_titleStyles = props.titleStyles) === null || _props_titleStyles === void 0 ? void 0 : (_props_titleStyles_titleFont = _props_titleStyles.titleFont) === null || _props_titleStyles_titleFont === void 0 ? void 0 : _props_titleStyles_titleFont.size) === 'number' ? props.titleStyles.titleFont.size : 13) + _index1.CHART_TITLE_PADDING, 36) : 0;
    const outerRadius = Math.min(_width - donutMarginHorizontal, _height - donutMarginVertical - titleHeight) / 2;
    const chartData = _elevateToMinimums(points);
    const valueInsideDonut = props.innerRadius > _index1.MIN_DONUT_RADIUS ? _valueInsideDonut(props.valueInsideDonut, chartData) : '';
    const arrowAttributes = (0, _reacttabster.useArrowNavigationGroup)({
        circular: true,
        axis: 'horizontal'
    });
    return !_isChartEmpty() ? /*#__PURE__*/ _react.createElement("div", {
        className: classes.root,
        ref: (rootElem)=>{
            _rootElem.current = rootElem;
        },
        onMouseLeave: _handleChartMouseLeave
    }, props.xAxisAnnotation && /*#__PURE__*/ _react.createElement("text", {
        className: classes.axisAnnotation,
        x: _width / 2,
        y: _height - 10,
        textAnchor: "middle"
    }, props.xAxisAnnotation), /*#__PURE__*/ _react.createElement("div", {
        className: classes.chartWrapper,
        ...arrowAttributes
    }, /*#__PURE__*/ _react.createElement("svg", {
        className: classes.chart,
        "aria-label": data === null || data === void 0 ? void 0 : data.chartTitle,
        width: _width,
        height: _height + titleHeight / 2
    }, !hideLegend && (data === null || data === void 0 ? void 0 : data.chartTitle) && /*#__PURE__*/ _react.createElement(_index1.ChartTitle, {
        title: data.chartTitle,
        x: _width / 2,
        y: 0,
        maxWidth: _width - 20,
        className: classes.chartTitle,
        titleStyles: props.titleStyles,
        tooltipClassName: classes.svgTooltip
    }), /*#__PURE__*/ _react.createElement(_index.Pie, {
        width: _width,
        height: _height,
        outerRadius: outerRadius,
        innerRadius: props.innerRadius,
        data: chartData,
        onFocusCallback: _focusCallback,
        hoverOnCallback: _hoverCallback,
        hoverLeaveCallback: _hoverLeave,
        uniqText: _uniqText,
        onBlurCallback: _onBlur,
        activeArc: _getHighlightedLegend(),
        focusedArcId: focusedArcId || '',
        href: props.href,
        valueInsideDonut: _toLocaleString(valueInsideDonut),
        showLabelsInPercent: props.showLabelsInPercent,
        hideLabels: props.hideLabels
    }))), /*#__PURE__*/ _react.createElement(_ChartPopover.ChartPopover, {
        xCalloutValue: xCalloutValue,
        yCalloutValue: yCalloutValue,
        culture: props.culture,
        positioning: {
            target: refSelected
        },
        isPopoverOpen: !props.hideTooltip && isPopoverOpen && (_noLegendsHighlighted() || _isLegendHighlighted(legend)),
        legend: legend,
        YValue: value,
        color: color,
        isCalloutForStack: false,
        customCallout: {
            customizedCallout: props.onRenderCalloutPerDataPoint ? props.onRenderCalloutPerDataPoint(dataPointCalloutProps) : undefined,
            customCalloutProps: props.calloutPropsPerDataPoint ? props.calloutPropsPerDataPoint(dataPointCalloutProps) : undefined
        },
        isCartesian: false
    }), !hideLegend && /*#__PURE__*/ _react.createElement("div", {
        ref: (e)=>{
            legendContainer.current = e;
        },
        className: classes.legendContainer,
        style: {
            marginTop: (data === null || data === void 0 ? void 0 : data.chartTitle) ? `-${titleHeight}px` : undefined
        }
    }, legendBars)) : /*#__PURE__*/ _react.createElement("div", {
        id: _emptyChartId,
        role: 'alert',
        style: {
            opacity: '0'
        },
        "aria-label": 'Graph has no data to display'
    });
});
DonutChart.displayName = 'DonutChart';
