'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Legends", {
    enumerable: true,
    get: function() {
        return Legends;
    }
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _reactbutton = require("@fluentui/react-button");
const _shape = require("./shape");
const _useLegendsStylesstyles = require("./useLegendsStyles.styles");
const _reactoverflow = require("@fluentui/react-overflow");
const _reacttabster = require("@fluentui/react-tabster");
const _OverflowMenu = require("./OverflowMenu");
const _reacttheme = require("@fluentui/react-theme");
const _imageexportutils = require("../../utilities/image-export-utils");
const _react1 = require("@griffel/react");
const Legends = /*#__PURE__*/ _react.forwardRef((props, forwardedRef)=>{
    /** Boolean variable to check if one or more legends are selected */ let _isLegendSelected = false;
    let _rootElem = _react.useRef(null);
    // set states separately for each instance of the component
    const [activeLegend, setActiveLegend] = _react.useState('');
    const [selectedLegends, setSelectedLegends] = _react.useState({});
    const focusAttributes = (0, _reacttabster.useFocusableGroup)();
    const arrowAttributes = (0, _reacttabster.useArrowNavigationGroup)({
        axis: 'horizontal',
        memorizeCurrent: true
    });
    const classes = (0, _useLegendsStylesstyles.useLegendStyles)(props);
    const toSVG = _react.useCallback((svgWidth, isRTL = false)=>{
        return (0, _imageexportutils.cloneLegendsToSVG)(props.legends, svgWidth, {
            selectedLegends,
            centerLegends: !!props.centerLegends,
            textClassName: classes.text,
            isRTL
        }, _rootElem.current);
    }, [
        props.legends,
        props.centerLegends,
        selectedLegends,
        classes.text
    ]);
    _react.useImperativeHandle(props.legendRef, ()=>({
            toSVG
        }));
    _react.useEffect(()=>{
        var _props_selectedLegends;
        const initialSelectedLegends = (_props_selectedLegends = props.selectedLegends) !== null && _props_selectedLegends !== void 0 ? _props_selectedLegends : props.defaultSelectedLegends;
        var _props_selectedLegend;
        const initialSelectedLegend = (_props_selectedLegend = props.selectedLegend) !== null && _props_selectedLegend !== void 0 ? _props_selectedLegend : props.defaultSelectedLegend;
        let selectedLegendsState = {};
        if (props.canSelectMultipleLegends) {
            var _this;
            selectedLegendsState = ((_this = initialSelectedLegends !== null && initialSelectedLegends !== void 0 ? initialSelectedLegends : []) === null || _this === void 0 ? void 0 : _this.reduce((combineDict, key)=>({
                    [key]: true,
                    ...combineDict
                }), {})) || {};
            setSelectedLegends(selectedLegendsState);
        } else if (initialSelectedLegend !== undefined) {
            selectedLegendsState = {
                [initialSelectedLegend]: true
            };
            setSelectedLegends(selectedLegendsState);
        }
    }, [
        props.canSelectMultipleLegends,
        props.defaultSelectedLegend,
        props.defaultSelectedLegends,
        props.selectedLegend,
        props.selectedLegends
    ]);
    _isLegendSelected = Object.keys(selectedLegends).length > 0;
    const dataToRender = _generateData();
    const { overflowStyles, allowFocusOnLegends = true, canSelectMultipleLegends = false } = props;
    const itemIds = dataToRender.map((_item, index)=>index.toString());
    const overflowHoverCardLegends = [];
    dataToRender.map((legend, index)=>{
        const hoverCardElement = _renderButton(legend, index);
        overflowHoverCardLegends.push(hoverCardElement);
    });
    const overflowString = props.overflowText ? props.overflowText : 'more';
    return props.enabledWrapLines ? renderWrappedLegends() : renderLegends();
    function renderLegends() {
        return /*#__PURE__*/ _react.createElement("div", {
            ...focusAttributes,
            ...arrowAttributes,
            ...allowFocusOnLegends && {
                role: 'listbox',
                'aria-label': 'Legends',
                'aria-multiselectable': canSelectMultipleLegends
            },
            className: classes.root,
            ref: _rootElem
        }, /*#__PURE__*/ _react.createElement(_reactoverflow.Overflow, null, /*#__PURE__*/ _react.createElement("div", {
            className: classes.resizableArea,
            style: {
                textAlign: props.centerLegends ? 'center' : 'unset'
            }
        }, dataToRender.map((item, id)=>/*#__PURE__*/ _react.createElement(_reactoverflow.OverflowItem, {
                key: id,
                id: id.toString()
            }, _renderButton(item))), /*#__PURE__*/ _react.createElement(_OverflowMenu.OverflowMenu, {
            itemIds: itemIds,
            title: `${overflowString}`,
            items: overflowHoverCardLegends
        }))));
    }
    function renderWrappedLegends() {
        return /*#__PURE__*/ _react.createElement("div", {
            ...focusAttributes,
            ...arrowAttributes,
            ...allowFocusOnLegends && {
                role: 'listbox',
                'aria-label': 'Legends',
                'aria-multiselectable': canSelectMultipleLegends
            },
            style: {
                justifyContent: props.centerLegends ? 'center' : 'unset',
                flexWrap: 'wrap',
                ...overflowStyles
            },
            className: classes.root,
            ref: _rootElem
        }, /*#__PURE__*/ _react.createElement("div", {
            className: classes.resizableArea,
            style: {
                display: 'flex',
                flexWrap: 'wrap',
                overflow: 'auto'
            }
        }, dataToRender.map((item)=>/*#__PURE__*/ _react.createElement("div", {
                className: (0, _react1.mergeClasses)(classes.legendContainer, item.legendAnnotation && classes.annotation),
                key: item.key
            }, _renderButton(item), item.legendAnnotation && /*#__PURE__*/ _react.createElement("div", null, item.legendAnnotation())))));
    }
    function _generateData() {
        const { shape } = props;
        const dataItems = props.legends.map((legend, index)=>{
            return {
                /* ...(allowFocusOnLegends && {
            nativeButtonProps: getIntrinsicElementProps(
              'div',
              {
                legend,
                ...buttonProperties,
              },
              ['title'],
            ),
            'aria-setsize': props.legends.length,
            'aria-posinset': index + 1,
          }), */ title: legend.title,
                action: legend.action,
                hoverAction: legend.hoverAction,
                onMouseOutAction: legend.onMouseOutAction,
                color: legend.color,
                shape: shape ? shape : legend.shape,
                stripePattern: legend.stripePattern,
                isLineLegendInBarChart: legend.isLineLegendInBarChart,
                opacity: legend.opacity,
                key: index,
                legendAnnotation: legend.legendAnnotation
            };
        });
        return dataItems;
    }
    /**
     * Determine whether the component is in "controlled" mode for selections, where the selected legend(s) are
     * determined entirely by props passed in from the parent component.
     */ function _isInControlledMode() {
        return props.canSelectMultipleLegends ? props.selectedLegends !== undefined : props.selectedLegend !== undefined;
    }
    /**
     * Get the new selected legends based on the legend that was clicked when multi-select is enabled.
     * @param legend The legend that was clicked
     * @returns An object with the new selected legend(s) state data.
     */ function _getNewSelectedLegendsForMultiselect(legend) {
        let legendsSelected = {
            ...selectedLegends
        };
        if (legendsSelected[legend.title]) {
            // Delete entry for the deselected legend to make
            // the number of keys equal to the number of selected legends
            delete legendsSelected[legend.title];
        } else {
            legendsSelected[legend.title] = true;
            // Clear set if all legends are selected
            if (Object.keys(legendsSelected).length === props.legends.length) {
                legendsSelected = {};
            }
        }
        return legendsSelected;
    }
    /**
     * Get the new selected legends based on the legend that was clicked when single-select is enabled.
     * @param legend The legend that was clicked
     * @returns An object with the new selected legend state data.
     */ function _getNewSelectedLegendsForSingleSelect(legend) {
        return selectedLegends[legend.title] ? {} : {
            [legend.title]: true
        };
    }
    function _onClick(legend, event) {
        var _props_onChange, _legend_action;
        const { canSelectMultipleLegends = false } = props;
        const nextSelectedLegends = canSelectMultipleLegends ? _getNewSelectedLegendsForMultiselect(legend) : _getNewSelectedLegendsForSingleSelect(legend);
        if (!_isInControlledMode()) {
            setSelectedLegends(nextSelectedLegends);
        }
        (_props_onChange = props.onChange) === null || _props_onChange === void 0 ? void 0 : _props_onChange.call(props, Object.keys(nextSelectedLegends), event, legend);
        (_legend_action = legend.action) === null || _legend_action === void 0 ? void 0 : _legend_action.call(legend);
    }
    function _onHoverOverLegend(legend) {
        if (legend.hoverAction) {
            setActiveLegend(legend.title);
            legend.hoverAction();
        }
    }
    function _onLeave(legend) {
        if (legend.onMouseOutAction) {
            setActiveLegend('');
            legend.onMouseOutAction();
        }
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function _renderButton(data, index) {
        const { allowFocusOnLegends = true } = props;
        const legend = {
            title: data.title,
            color: data.color,
            shape: data.shape,
            action: data.action,
            hoverAction: data.hoverAction,
            onMouseOutAction: data.onMouseOutAction,
            stripePattern: data.stripePattern,
            isLineLegendInBarChart: data.isLineLegendInBarChart,
            opacity: data.opacity
        };
        const color = _getColor(legend.title, legend.color);
        const onClickHandler = (event)=>{
            _onClick(legend, event);
        };
        const onHoverHandler = ()=>{
            _onHoverOverLegend(legend);
        };
        const onMouseOut = ()=>{
            _onLeave(legend);
        };
        const shape = _getShape(legend, color);
        return /*#__PURE__*/ _react.createElement(_reactbutton.Button, {
            ...allowFocusOnLegends && {
                'aria-selected': !!selectedLegends[legend.title],
                role: 'option',
                'aria-label': `${legend.title}`,
                'aria-setsize': data['aria-setsize'],
                'aria-posinset': data['aria-posinset']
            },
            ...data.nativeButtonProps && {
                ...data.nativeButtonProps
            },
            key: index,
            className: classes.legend,
            onClick: onClickHandler,
            onMouseOver: onHoverHandler,
            onMouseOut: onMouseOut,
            onFocus: onHoverHandler,
            onBlur: onMouseOut,
            appearance: 'outline',
            size: "small",
            style: {
                '--rect-height': legend.isLineLegendInBarChart ? '4px' : '12px',
                '--rect-backgroundColor': legend.stripePattern ? '' : color,
                '--rect-borderColor': legend.color ? legend.color : _reacttheme.tokens.colorNeutralStroke1,
                '--rect-content': legend.stripePattern ? `repeating-linear-gradient(135deg, transparent, transparent 3px, ${color} 1px, ${color} 4px)` : ''
            }
        }, shape, /*#__PURE__*/ _react.createElement("div", {
            className: classes.text,
            style: {
                opacity: color === _reacttheme.tokens.colorNeutralBackground1 ? '0.67' : ''
            }
        }, legend.title));
    }
    function _getShape(legend, color) {
        const svgParentProps = {
            className: classes.shape
        };
        const svgChildProps = {
            fill: color,
            strokeWidth: 2,
            stroke: legend.color
        };
        return /*#__PURE__*/ _react.createElement(_shape.Shape, {
            svgProps: svgParentProps,
            pathProps: svgChildProps,
            shape: legend.shape,
            classNameForNonSvg: classes.rect,
            style: {
                height: legend.isLineLegendInBarChart ? '4px' : '12px',
                backgroundColor: legend.stripePattern ? '' : color,
                borderColor: legend.color ? legend.color : _reacttheme.tokens.colorNeutralStroke1,
                content: legend.stripePattern ? `repeating-linear-gradient(135deg, transparent, transparent 3px, ${color} 1px, ${color} 4px)` : '',
                '--rect-content-high-contrast': `linear-gradient(to right, ${color}, ${color})`,
                '--rect-opacity-high-contrast': color === _reacttheme.tokens.colorNeutralBackground1 ? '0.6' : ''
            }
        });
    }
    function _getColor(title, color) {
        let legendColor = color;
        // if one or more legends are selected
        if (_isLegendSelected) {
            // if the given legend (title) is one of the selected legends
            if (selectedLegends[title]) {
                legendColor = color;
            } else {
                legendColor = _reacttheme.tokens.colorNeutralBackground1;
            }
        } else {
            // if the given legend is hovered
            // or none of the legends is hovered
            if (activeLegend === title || activeLegend === '') {
                legendColor = color;
            } else {
                legendColor = _reacttheme.tokens.colorNeutralBackground1;
            }
        }
        return legendColor;
    }
});
Legends.displayName = 'Legends';
