'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "FunnelChart", {
    enumerable: true,
    get: function() {
        return FunnelChart;
    }
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _reactutilities = require("@fluentui/react-utilities");
const _index = require("../../utilities/index");
const _index1 = require("../Legends/index");
const _reacttabster = require("@fluentui/react-tabster");
const _ChartPopover = require("../CommonComponents/ChartPopover");
const _chartutilities = require("@fluentui/chart-utilities");
const _colors = require("../../utilities/colors");
const _useFunnelChartStylesstyles = require("./useFunnelChartStyles.styles");
const _funnelGeometry = require("./funnelGeometry");
const _hooks = require("../../utilities/hooks");
const FunnelChart = /*#__PURE__*/ _react.forwardRef(({ orientation = 'vertical', ...restProps }, forwardedRef)=>{
    var _props_legendProps, _props_titleStyles_titleFont, _props_titleStyles;
    const props = {
        orientation,
        ...restProps
    };
    const _emptyChartId = (0, _reactutilities.useId)('_FunnelChart_empty');
    const isRTL = (0, _index.useRtl)();
    const [hoveredStage, setHoveredStage] = _react.useState(null);
    const [calloutData, setCalloutData] = _react.useState(null);
    const [selectedLegends, setSelectedLegends] = _react.useState([]);
    const [isPopoverOpen, setPopoverOpen] = _react.useState(false);
    const [refSelected, setRefSelected] = _react.useState(null);
    const isStacked = isStackedFunnelData(props.data);
    const { chartContainerRef, legendsRef: _legendsRef } = (0, _hooks.useImageExport)(props.componentRef, props.hideLegend, false);
    _react.useEffect(()=>{
        var _props_legendProps;
        if ((_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.selectedLegends) {
            setSelectedLegends(props.legendProps.selectedLegends);
        }
    }, [
        (_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.selectedLegends
    ]);
    function _handleHover(data, mouseEvent, targetElement) {
        mouseEvent === null || mouseEvent === void 0 ? void 0 : mouseEvent.persist();
        setCalloutData(data);
        setRefSelected(targetElement);
        setPopoverOpen(true);
    }
    function _handleFocus(data, focusEvent, targetElement) {
        focusEvent === null || focusEvent === void 0 ? void 0 : focusEvent.persist();
        setCalloutData(data);
        setRefSelected(targetElement);
        setPopoverOpen(true);
    }
    function _handleStackedHover(stage, subValue, mouseEvent, targetElement) {
        mouseEvent === null || mouseEvent === void 0 ? void 0 : mouseEvent.persist();
        setCalloutData({
            stage,
            value: subValue.value,
            color: subValue.color,
            category: subValue.category
        });
        setRefSelected(targetElement);
        setPopoverOpen(true);
    }
    function _handleStackedFocus(stage, subValue, focusEvent, targetElement) {
        focusEvent === null || focusEvent === void 0 ? void 0 : focusEvent.persist();
        setCalloutData({
            stage,
            value: subValue.value,
            color: subValue.color,
            category: subValue.category
        });
        setRefSelected(targetElement);
        setPopoverOpen(true);
    }
    function _handleMouseOut() {
        setHoveredStage(null);
        setPopoverOpen(false);
        setCalloutData(null);
    }
    function _onLegendSelectionChange(legendsSelected, event, currentLegend) {
        var _props_legendProps, _props_legendProps1;
        if ((_props_legendProps = props.legendProps) === null || _props_legendProps === void 0 ? void 0 : _props_legendProps.canSelectMultipleLegends) {
            setSelectedLegends(legendsSelected);
        } else {
            setSelectedLegends(legendsSelected.slice(-1));
        }
        if ((_props_legendProps1 = props.legendProps) === null || _props_legendProps1 === void 0 ? void 0 : _props_legendProps1.onChange) {
            props.legendProps.onChange(legendsSelected, event, currentLegend);
        }
    }
    const _onLegendSelectionChangeCallback = _react.useCallback(_onLegendSelectionChange, [
        props.legendProps
    ]);
    function getHighlightedLegend() {
        return selectedLegends.length > 0 ? selectedLegends : hoveredStage ? [
            hoveredStage
        ] : [];
    }
    function legendHighlighted(legend) {
        return getHighlightedLegend().includes(legend);
    }
    function noLegendHighlighted() {
        return getHighlightedLegend().length === 0;
    }
    function _getAriaLabel(data) {
        if ('subValue' in data) {
            // Stacked funnel segment
            const formattedValue = (0, _chartutilities.formatToLocaleString)(data.subValue.value.toString(), props.culture);
            return `${data.stage}, ${data.subValue.category}, ${formattedValue}.`;
        } else {
            var _data_value;
            // Non-stacked funnel segment
            const formattedValue = (0, _chartutilities.formatToLocaleString)(((_data_value = data.value) !== null && _data_value !== void 0 ? _data_value : 0).toString(), props.culture);
            return `${data.stage}, ${formattedValue}.`;
        }
    }
    function _getEventHandlerProps(data, opacity, segmentId) {
        const targetElement = document.getElementById(segmentId);
        if ('subValue' in data) {
            return {
                culture: props.culture,
                onMouseOver: opacity == 1 ? (event)=>_handleStackedHover(data.stage, data.subValue, event, targetElement) : undefined,
                onMouseMove: opacity == 1 ? (event)=>_handleStackedHover(data.stage, data.subValue, event, targetElement) : undefined,
                onFocus: (event)=>_handleStackedFocus(data.stage, data.subValue, event, targetElement),
                onBlur: ()=>_handleMouseOut(),
                onMouseOut: ()=>_handleMouseOut()
            };
        } else {
            return {
                culture: props.culture,
                onMouseOver: opacity == 1 ? (event)=>_handleHover(data, event, targetElement) : undefined,
                onMouseMove: opacity == 1 ? (event)=>_handleHover(data, event, targetElement) : undefined,
                onFocus: (event)=>_handleFocus(data, event, targetElement),
                onBlur: ()=>_handleMouseOut(),
                onMouseOut: ()=>_handleMouseOut()
            };
        }
    }
    function _renderSegmentText({ show, x, y, value, textColor, opacity }) {
        if (!show) {
            return null;
        }
        const textElement = /*#__PURE__*/ _react.createElement("text", {
            x: isRTL ? funnelWidth - x : x,
            y: y,
            opacity: opacity,
            textAnchor: "middle",
            alignmentBaseline: "middle",
            fill: textColor
        }, (0, _chartutilities.formatToLocaleString)(value.toString(), props.culture));
        if (isRTL) {
            return /*#__PURE__*/ _react.createElement("g", {
                transform: `scale(-1,1) translate(${-funnelWidth},0)`
            }, textElement);
        }
        return textElement;
    }
    function _renderFunnelSegment({ key, pathD, fill, opacity, textProps, data, tabIndex }) {
        const segmentId = `funnel-segment-${key}`;
        const eventHandlers = _getEventHandlerProps(data, opacity, segmentId);
        const textColor = (0, _colors.getContrastTextColor)(fill);
        return /*#__PURE__*/ _react.createElement("g", {
            key: key
        }, /*#__PURE__*/ _react.createElement("path", {
            id: segmentId,
            d: pathD,
            fill: fill,
            opacity: opacity,
            ...eventHandlers,
            tabIndex: tabIndex,
            role: "img",
            "aria-label": _getAriaLabel(data)
        }), textProps && /*#__PURE__*/ _react.createElement("g", eventHandlers, _renderSegmentText({
            ...textProps,
            textColor,
            opacity
        })));
    }
    function _createFunnel(containerHeight, containerWidth) {
        const { data } = props;
        const funnelWidth = containerWidth;
        const funnelHeight = containerHeight * 0.8;
        return data.map((d, i)=>{
            const geometryProps = props.orientation === 'vertical' ? (0, _funnelGeometry.getVerticalFunnelSegmentGeometry)({
                d,
                i,
                data,
                funnelWidth,
                funnelHeight,
                isRTL
            }) : (0, _funnelGeometry.getHorizontalFunnelSegmentGeometry)({
                d,
                i,
                data,
                funnelWidth,
                funnelHeight,
                isRTL
            });
            const { pathD, textX, textY, availableWidth } = geometryProps;
            const minTextWidth = 16;
            const eventHandlerProps = _getEventHandlerProps(d);
            const textProps = (0, _funnelGeometry.getSegmentTextProps)({
                availableWidth,
                minTextWidth,
                textX,
                textY,
                value: d.value,
                ...eventHandlerProps
            });
            return _renderFunnelSegment({
                key: i,
                pathD,
                fill: d.color,
                opacity: legendHighlighted(d.stage) || noLegendHighlighted() ? 1 : 0.1,
                textProps,
                data: d,
                tabIndex: legendHighlighted(d.stage) || noLegendHighlighted() ? 0 : undefined
            });
        });
    }
    function isStackedFunnelData(data) {
        return Array.isArray(data) && data.every((stage)=>Array.isArray(stage.subValues));
    }
    function _renderStackedSegment(stage, subValue, stageIndex, subValueIndex, geometryParams) {
        // Ensure stages have subValues for geometry functions
        const stagesWithSubValues = geometryParams.stages.map((s)=>({
                ...s,
                subValues: s.subValues || []
            }));
        const geom = props.orientation === 'vertical' ? (0, _funnelGeometry.getStackedVerticalFunnelSegmentGeometry)({
            ...geometryParams,
            stages: stagesWithSubValues,
            i: stageIndex,
            k: subValueIndex
        }) : (0, _funnelGeometry.getStackedHorizontalFunnelSegmentGeometry)({
            ...geometryParams,
            stages: stagesWithSubValues,
            i: stageIndex,
            k: subValueIndex
        });
        const minTextWidth = 16;
        const eventHandlerProps = _getEventHandlerProps({
            stage: stage.stage,
            subValue
        });
        const textProps = (0, _funnelGeometry.getSegmentTextProps)({
            availableWidth: geom.availableWidth,
            minTextWidth,
            textX: geom.textX,
            textY: geom.textY,
            value: subValue.value,
            ...eventHandlerProps
        });
        return _renderFunnelSegment({
            key: `${stageIndex}-${subValueIndex}`,
            pathD: geom.pathD,
            fill: subValue.color,
            opacity: isStackedFunnelData(props.data) && legendHighlighted(subValue.category) || noLegendHighlighted() ? 1 : 0.1,
            textProps,
            data: {
                stage: stage.stage,
                subValue
            },
            tabIndex: legendHighlighted(subValue.category) || noLegendHighlighted() ? 0 : undefined
        });
    }
    function _createStackedFunnel(containerHeight, containerWidth) {
        const { data } = props;
        const stages = data;
        const totals = stages.map((s)=>{
            var _s_subValues;
            var _s_subValues_reduce;
            return (_s_subValues_reduce = s === null || s === void 0 ? void 0 : (_s_subValues = s.subValues) === null || _s_subValues === void 0 ? void 0 : _s_subValues.reduce((sum, subValue)=>sum + subValue.value, 0)) !== null && _s_subValues_reduce !== void 0 ? _s_subValues_reduce : 0;
        });
        const maxTotal = Math.max(...totals);
        const funnelWidth = containerWidth;
        const funnelHeight = containerHeight * 0.8;
        const paths = [];
        const geometryParams = {
            stages,
            totals,
            maxTotal,
            funnelWidth,
            funnelHeight,
            isRTL
        };
        for(let i = 0; i < stages.length; i++){
            const cur = stages[i];
            var _cur_subValues;
            for(let k = 0; k < ((_cur_subValues = cur.subValues) !== null && _cur_subValues !== void 0 ? _cur_subValues : []).length; k++){
                var _cur_subValues1;
                const v = (_cur_subValues1 = cur.subValues) === null || _cur_subValues1 === void 0 ? void 0 : _cur_subValues1[k];
                if (!v) {
                    continue;
                }
                paths.push(_renderStackedSegment(cur, v, i, k, geometryParams));
            }
        }
        return paths;
    }
    function _renderLegends() {
        if (props.hideLegend) {
            return /*#__PURE__*/ _react.createElement(_react.Fragment, null);
        }
        let legends;
        if (isStacked) {
            // Collect unique categories and their color
            const categoryMap = {};
            props.data.forEach((stage)=>{
                (stage.subValues || []).forEach((sub)=>{
                    if (!(sub.category in categoryMap)) {
                        categoryMap[sub.category] = sub.color;
                    }
                });
            });
            legends = Object.entries(categoryMap).map(([category, color])=>({
                    title: category,
                    color,
                    hoverAction: ()=>setHoveredStage(category),
                    onMouseOutAction: ()=>setHoveredStage(null)
                }));
        } else {
            legends = props.data.map((d)=>({
                    title: d.stage,
                    color: d.color,
                    hoverAction: ()=>setHoveredStage(d.stage),
                    onMouseOutAction: ()=>setHoveredStage(null)
                }));
        }
        return /*#__PURE__*/ _react.createElement("div", {
            style: {
                display: 'flex',
                justifyContent: 'center'
            }
        }, /*#__PURE__*/ _react.createElement(_index1.Legends, {
            legends: legends,
            centerLegends: true,
            onChange: _onLegendSelectionChangeCallback,
            ...props.legendProps,
            legendRef: _legendsRef
        }));
    }
    function _isChartEmpty() {
        return !(props.data && props.data.length > 0);
    }
    const classes = (0, _useFunnelChartStylesstyles.useFunnelChartStyles)(props);
    const calloutProps = {
        ...props.calloutProps,
        color: calloutData === null || calloutData === void 0 ? void 0 : calloutData.color,
        hoverXValue: calloutData === null || calloutData === void 0 ? void 0 : calloutData.stage,
        YValue: calloutData === null || calloutData === void 0 ? void 0 : calloutData.value
    };
    const width = props.width || 350;
    const height = props.height || 500;
    const titleHeight = props.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) + _index.CHART_TITLE_PADDING, 40) : 40;
    const funnelMarginTop = titleHeight;
    const funnelWidth = width * 0.8;
    const funnelOffsetX = (width - funnelWidth) / 2;
    const arrowAttributes = (0, _reacttabster.useArrowNavigationGroup)({
        circular: true,
        axis: 'horizontal'
    });
    return !_isChartEmpty() ? /*#__PURE__*/ _react.createElement("div", {
        ref: chartContainerRef,
        className: classes.root,
        style: {
            width,
            height
        }
    }, /*#__PURE__*/ _react.createElement("svg", {
        width: width,
        height: height,
        className: classes.chart,
        ...arrowAttributes,
        role: 'region',
        "aria-label": props.chartTitle
    }, !props.hideLegend && props.chartTitle && /*#__PURE__*/ _react.createElement(_index.ChartTitle, {
        title: props.chartTitle,
        x: width / 2,
        maxWidth: width - 20,
        className: classes.chartTitle,
        titleStyles: props.titleStyles,
        tooltipClassName: classes.svgTooltip
    }), /*#__PURE__*/ _react.createElement("g", {
        transform: isRTL ? `translate(${funnelOffsetX + funnelWidth}, ${funnelMarginTop}) scale(-1,1)` : `translate(${funnelOffsetX}, ${funnelMarginTop})`
    }, isStacked ? _createStackedFunnel(height - funnelMarginTop, funnelWidth) : _createFunnel(height - funnelMarginTop, funnelWidth))), isPopoverOpen && /*#__PURE__*/ _react.createElement(_ChartPopover.ChartPopover, {
        ...props.calloutProps,
        XValue: calloutProps === null || calloutProps === void 0 ? void 0 : calloutProps.hoverXValue,
        yCalloutValue: calloutProps === null || calloutProps === void 0 ? void 0 : calloutProps.YValue,
        culture: props.culture,
        positioning: {
            target: refSelected
        },
        isPopoverOpen: isPopoverOpen,
        color: calloutProps === null || calloutProps === void 0 ? void 0 : calloutProps.color,
        isCartesian: false
    }), _renderLegends()) : /*#__PURE__*/ _react.createElement("div", {
        id: _emptyChartId,
        role: 'alert',
        style: {
            opacity: '0'
        },
        "aria-label": 'Graph has no data to display'
    });
});
FunnelChart.displayName = 'FunnelChart';
