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 _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 _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 _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);
}
/**
 * @fileoverview 语言选择器组件
 * 提供搜索和选择编程语言的交互界面
 * @author Code Plugin Team
 */ import { SearchOutlined } from "@ant-design/icons";
import { AutoComplete, Button, Input, Popover } from "antd";
import React, { useContext, useEffect, useRef, useState } from "react";
import { I18nContext } from "../../../I18n";
import { langIconMap } from "../langIconMap";
import { langOptions } from "../utils/langOptions";
import { LoadImage } from "./LoadImage";
/**
 * 语言选择器组件
 *
 * 功能：
 * - 显示当前选择的编程语言
 * - 提供搜索功能快速查找语言
 * - 支持点击切换语言
 * - 显示语言对应的图标
 *
 * 交互：
 * - 点击按钮打开语言选择弹层
 * - 在搜索框中输入关键字过滤语言
 * - 选择语言后自动关闭弹层
 * - 支持键盘导航（Enter 键确认）
 *
 * @param props - 组件属性
 * @returns React 语言选择器元素
 *
 * @example
 * ```tsx
 * <LanguageSelector
 *   element={{ language: 'javascript', katex: false }}
 *   containerRef={containerRef}
 *   setLanguage={(lang) => console.log('Selected:', lang)}
 * />
 * ```
 */ export var LanguageSelector = function LanguageSelector(props) {
    var _i18n_locale, _safeElement_language, _safeElement_language1;
    // 获取国际化上下文
    var i18n = useContext(I18nContext);
    // 搜索关键字状态
    var _useState = _sliced_to_array(useState(''), 2), keyword = _useState[0], setKeyword = _useState[1];
    // Popover 打开状态
    var _useState1 = _sliced_to_array(useState(false), 2), open = _useState1[0], setOpen = _useState1[1];
    // 跟踪用户是否手动关闭过弹层
    var hasUserClosedRef = useRef(false);
    // 跟踪上一次的语言值
    var prevLanguageRef = useRef(undefined);
    // 处理未定义的 element
    var safeElement = props.element || {
        language: undefined,
        katex: false
    };
    // 如果语言为空且用户未手动关闭过，自动打开下拉框
    useEffect(function() {
        var currentLanguage = safeElement.language;
        var prevLanguage = prevLanguageRef.current;
        // 如果语言从有值变为空，重置关闭标记
        if (prevLanguage && !currentLanguage && !safeElement.katex) {
            hasUserClosedRef.current = false;
        }
        // 如果语言为空且用户未手动关闭过，自动打开下拉框
        if (!currentLanguage && !safeElement.katex && !hasUserClosedRef.current) {
            setOpen(true);
        }
        // 更新上一次的语言值
        prevLanguageRef.current = currentLanguage;
    }, [
        safeElement.language,
        safeElement.katex
    ]);
    return /*#__PURE__*/ React.createElement(Popover, {
        arrow: false,
        open: open,
        styles: {
            body: {
                padding: 8
            }
        },
        trigger: [
            'click'
        ],
        placement: 'bottomLeft',
        onOpenChange: function onOpenChange(visible) {
            setOpen(visible);
            if (visible) {
                // 弹层打开时，延时聚焦到搜索框
                setTimeout(function() {
                    var _props_containerRef_current_querySelector, _props_containerRef_current, _props_containerRef;
                    props === null || props === void 0 ? void 0 : (_props_containerRef = props.containerRef) === null || _props_containerRef === void 0 ? void 0 : (_props_containerRef_current = _props_containerRef.current) === null || _props_containerRef_current === void 0 ? void 0 : (_props_containerRef_current_querySelector = _props_containerRef_current.querySelector('.lang-select input')) === null || _props_containerRef_current_querySelector === void 0 ? void 0 : _props_containerRef_current_querySelector.focus();
                });
            } else {
                // 弹层关闭时清空搜索关键字，并标记用户已手动关闭
                setKeyword('');
                hasUserClosedRef.current = true;
            }
        },
        content: /*#__PURE__*/ React.createElement("div", {
            onClick: function onClick(e) {
                e.stopPropagation();
                e.preventDefault();
            }
        }, /*#__PURE__*/ React.createElement(AutoComplete, {
            value: keyword,
            options: langOptions,
            autoFocus: true,
            style: {
                width: 200
            },
            filterOption: function filterOption(text, item) {
                // 根据输入的文本过滤语言选项
                return (item === null || item === void 0 ? void 0 : item.value.includes(text)) || false;
            },
            onSelect: function onSelect(selectedLanguage) {
                var // 选择语言后执行回调并关闭弹层
                _props_setLanguage;
                (_props_setLanguage = props.setLanguage) === null || _props_setLanguage === void 0 ? void 0 : _props_setLanguage.call(props, selectedLanguage);
                setOpen(false);
                // 重置关闭标记，以便下次语言为空时能再次自动打开
                hasUserClosedRef.current = false;
            },
            onChange: function onChange(inputValue) {
                // 更新搜索关键字
                setKeyword(inputValue);
            },
            onKeyDown: function onKeyDown(e) {
                if (e.key === 'Enter') {
                    // 阻止 Enter 键的默认行为
                    e.preventDefault();
                    e.stopPropagation();
                }
            },
            className: 'lang-select'
        }, /*#__PURE__*/ React.createElement(Input, {
            prefix: /*#__PURE__*/ React.createElement(SearchOutlined, null),
            placeholder: 'Search'
        })))
    }, /*#__PURE__*/ React.createElement(Button, {
        type: "text",
        title: (i18n === null || i18n === void 0 ? void 0 : (_i18n_locale = i18n.locale) === null || _i18n_locale === void 0 ? void 0 : _i18n_locale.switchLanguage) || '切换语言',
        style: {
            display: 'flex',
            alignItems: 'center',
            cursor: 'pointer',
            boxSizing: 'border-box',
            gap: 2,
            color: 'inherit'
        },
        size: "small",
        icon: // 如果有语言图标且不是公式，则显示图标
        langIconMap.get(((_safeElement_language = safeElement.language) === null || _safeElement_language === void 0 ? void 0 : _safeElement_language.toLowerCase()) || '') && !safeElement.katex && /*#__PURE__*/ React.createElement("div", {
            style: {
                height: '1em',
                width: '1em',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: '0.25em'
            }
        }, /*#__PURE__*/ React.createElement(LoadImage, {
            src: langIconMap.get(((_safeElement_language1 = safeElement.language) === null || _safeElement_language1 === void 0 ? void 0 : _safeElement_language1.toLowerCase()) || 'html')
        }))
    }, /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("div", null, safeElement.language ? /*#__PURE__*/ React.createElement("span", null, safeElement.katex ? 'Formula' : safeElement.language) : /*#__PURE__*/ React.createElement("span", null, '')))));
};
