function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { PlayLottie } from "../../..";
import { ChevronDown, Pause } from "@sofa-design/icons";
import { ConfigProvider, Dropdown, Flex, Tooltip } from "antd";
import classNames from "classnames";
import React, { useMemo, useState } from "react";
import { useSpeechSynthesis } from "../../../Hooks/useSpeechSynthesis";
import VoicingLottie from "../../../Icons/animated/VoicingLottie";
import { useStyle } from "./style";
export var VoiceButton = function(param) {
    var text = param.text, _param_defaultRate = param.defaultRate, defaultRate = _param_defaultRate === void 0 ? 1 : _param_defaultRate, _param_rateOptions = param.rateOptions, rateOptions = _param_rateOptions === void 0 ? [
        1.5,
        1.25,
        1,
        0.75
    ] : _param_rateOptions, useSpeech = param.useSpeech;
    var configContext = React.useContext(ConfigProvider.ConfigContext);
    var prefixCls = (configContext === null || configContext === void 0 ? void 0 : configContext.getPrefixCls("agent-voice-button")) || 'agent-voice-button';
    var _useStyle = useStyle(prefixCls), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var _useState = _sliced_to_array(useState(false), 2), isPlayHover = _useState[0], setIsPlayHover = _useState[1];
    var _useState1 = _sliced_to_array(useState(false), 2), isPlayingHovered = _useState1[0], setIsPlayingHovered = _useState1[1];
    // 首渲染冻结适配器，防止运行时切换导致 Hooks 调用顺序风险
    var speechAdapter = useMemo(function() {
        return useSpeech || useSpeechSynthesis;
    }, []);
    var _speechAdapter = speechAdapter({
        text: text,
        defaultRate: defaultRate
    }), isSupported = _speechAdapter.isSupported, isPlaying = _speechAdapter.isPlaying, rate = _speechAdapter.rate, setRate = _speechAdapter.setRate, start = _speechAdapter.start, stop = _speechAdapter.stop, pause = _speechAdapter.pause, resume = _speechAdapter.resume;
    // 如果外部提供了自定义适配器，则视为一定可用，避免受浏览器 Web Speech 支持度影响
    var isFeatureSupported = useMemo(function() {
        return speechAdapter !== useSpeechSynthesis || isSupported;
    }, [
        speechAdapter,
        isSupported
    ]);
    var handleClick = function() {
        if (!isFeatureSupported || !text) return;
        if (!isPlaying) {
            start();
            return;
        }
        stop();
    };
    var handleStop = function() {
        setIsPlayingHovered(false);
        setIsPlayHover(false);
        stop();
    };
    var handlePlayingMouseEnter = function() {
        setIsPlayingHovered(true);
        if (isPlaying) {
            pause();
        }
    };
    var handlePlayingMouseLeave = function() {
        setIsPlayingHovered(false);
        if (isPlaying) {
            resume();
        }
    };
    var tooltipText = useMemo(function() {
        if (!isFeatureSupported) return '当前环境不支持语音播报';
        return isPlaying ? '停止播报' : '语音播报';
    }, [
        isFeatureSupported,
        isPlaying
    ]);
    var normalizedRateOptions = useMemo(function() {
        var set = new Set(_to_consumable_array(rateOptions).concat([
            1
        ]));
        return Array.from(set).sort(function(a, b) {
            return b - a;
        });
    }, [
        rateOptions
    ]);
    var menuItems = useMemo(function() {
        return normalizedRateOptions.map(function(r) {
            return {
                key: String(r),
                label: /*#__PURE__*/ React.createElement("div", {
                    className: classNames("".concat(prefixCls, "-rateItem"), hashId)
                }, /*#__PURE__*/ React.createElement("span", null, "".concat(r, "x")), r === rate ? /*#__PURE__*/ React.createElement("span", null, "✓") : null)
            };
        });
    }, [
        normalizedRateOptions,
        rate,
        prefixCls,
        hashId
    ]);
    var rateDisplay = useMemo(function() {
        return "".concat(rate, "x");
    }, [
        rate
    ]);
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            alignItems: 'center',
            gap: 8
        }
    }, !isPlaying ? /*#__PURE__*/ React.createElement("div", {
        onMouseEnter: function() {
            return setIsPlayHover(true);
        },
        onMouseLeave: function() {
            return setIsPlayHover(false);
        },
        onClick: handleClick,
        className: classNames("".concat(prefixCls, "-playBox"), hashId),
        role: "button",
        tabIndex: 0,
        "aria-label": '语音播报',
        "aria-disabled": !isFeatureSupported || !text
    }, /*#__PURE__*/ React.createElement(Tooltip, {
        title: tooltipText,
        mouseEnterDelay: 0.1
    }, /*#__PURE__*/ React.createElement(Flex, {
        align: "center",
        justify: "center"
    }, /*#__PURE__*/ React.createElement(PlayLottie, {
        active: isPlayHover
    })))) : /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-playingWrap"), hashId)
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-playingBox"), hashId),
        onMouseEnter: handlePlayingMouseEnter,
        onMouseLeave: handlePlayingMouseLeave,
        onClick: handleStop,
        role: "button",
        tabIndex: 0,
        "aria-label": '停止播报'
    }, /*#__PURE__*/ React.createElement(Tooltip, {
        title: tooltipText,
        mouseEnterDelay: 0.1
    }, /*#__PURE__*/ React.createElement(Flex, {
        align: "center",
        justify: "center"
    }, isPlayingHovered ? /*#__PURE__*/ React.createElement(Pause, {
        fontSize: 14
    }) : /*#__PURE__*/ React.createElement(VoicingLottie, {
        size: 16
    })))), /*#__PURE__*/ React.createElement(Dropdown, {
        trigger: [
            'click'
        ],
        menu: {
            items: menuItems,
            onClick: function(info) {
                var v = Number(info.key);
                if (!Number.isNaN(v)) setRate(v);
            }
        }
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-rateBox"), hashId)
    }, /*#__PURE__*/ React.createElement("span", {
        style: {
            fontSize: 12
        }
    }, rate === 1 ? '倍速' : rateDisplay), /*#__PURE__*/ React.createElement(ChevronDown, {
        fontSize: 14
    }))))));
};
export default VoiceButton;
