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 _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
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 _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
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);
}
import { FileStack, Language, ListTodo, MousePointerClick, X } from "@sofa-design/icons";
import { ConfigProvider, Segmented } from "antd";
import classNames from "classnames";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { ActionIconBox } from "../Components/ActionIconBox";
import { I18nContext } from "../I18n";
import Browser from "./Browser";
import { File } from "./File";
import { RealtimeFollowList } from "./RealtimeFollow";
import { useWorkspaceStyle } from "./style";
import { TaskList } from "./Task";
var ComponentType = /*#__PURE__*/ function(ComponentType) {
    ComponentType["REALTIME"] = "realtime";
    ComponentType["BROWSER"] = "browser";
    ComponentType["TASK"] = "task";
    ComponentType["FILE"] = "file";
    ComponentType["CUSTOM"] = "custom";
    return ComponentType;
}(ComponentType || {});
var DEFAULT_CONFIG = function(locale) {
    var _obj;
    return _obj = {}, _define_property(_obj, "realtime", {
        key: "realtime",
        icon: /*#__PURE__*/ React.createElement(MousePointerClick, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.realtimeFollow']) || '实时跟随',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.realtimeFollow']) || '实时跟随'
    }), _define_property(_obj, "browser", {
        key: "browser",
        icon: /*#__PURE__*/ React.createElement(Language, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.browser']) || '浏览器',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.browser']) || '浏览器'
    }), _define_property(_obj, "task", {
        key: "task",
        icon: /*#__PURE__*/ React.createElement(ListTodo, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.task']) || '任务',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.task']) || '任务'
    }), _define_property(_obj, "file", {
        key: "file",
        icon: /*#__PURE__*/ React.createElement(FileStack, null),
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file']) || '文件',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.file']) || '文件'
    }), _define_property(_obj, "custom", {
        key: "custom",
        icon: null,
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.custom']) || '自定义',
        label: (locale === null || locale === void 0 ? void 0 : locale['workspace.custom']) || '自定义'
    }), _obj;
};
var resolveTabConfig = function(tab, defaultConfig, index) {
    var _ref;
    return {
        key: (tab === null || tab === void 0 ? void 0 : tab.key) || defaultConfig.key + (index !== undefined ? "-".concat(index) : ''),
        icon: (_ref = tab === null || tab === void 0 ? void 0 : tab.icon) !== null && _ref !== void 0 ? _ref : defaultConfig.icon,
        title: (tab === null || tab === void 0 ? void 0 : tab.title) || defaultConfig.label,
        count: tab === null || tab === void 0 ? void 0 : tab.count
    };
};
var RealtimeComponent = function(param) {
    var data = param.data;
    return data ? /*#__PURE__*/ React.createElement(RealtimeFollowList, {
        data: data
    }) : null;
};
var BrowserComponent = function(props) {
    return /*#__PURE__*/ React.createElement(Browser, props);
};
var TaskComponent = function(param) {
    var data = param.data, onItemClick = param.onItemClick;
    return data ? /*#__PURE__*/ React.createElement(TaskList, {
        data: data,
        onItemClick: onItemClick
    }) : null;
};
var FileComponent = function(props) {
    return /*#__PURE__*/ React.createElement(File, props);
};
var CustomComponent = function(param) {
    var children = param.children;
    return children || null;
};
var COMPONENT_MAP = new Map([
    [
        RealtimeComponent,
        "realtime"
    ],
    [
        BrowserComponent,
        "browser"
    ],
    [
        TaskComponent,
        "task"
    ],
    [
        FileComponent,
        "file"
    ],
    [
        CustomComponent,
        "custom"
    ]
]);
/**
 * 工作空间组件
 * 提供多标签页界面，支持实时跟随、浏览器、任务、文件等功能模块
 */ var Workspace = function(param) {
    var activeTabKey = param.activeTabKey, onTabChange = param.onTabChange, style = param.style, className = param.className, title = param.title, onClose = param.onClose, children = param.children, _param_pure = param.pure, pure = _param_pure === void 0 ? false : _param_pure, headerExtra = param.headerExtra;
    var _ref, _ref1;
    var _availableTabs_find, _availableTabs_, _availableTabs_find1;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var locale = useContext(I18nContext).locale;
    var prefixCls = getPrefixCls('workspace');
    var _useWorkspaceStyle = useWorkspaceStyle(prefixCls), wrapSSR = _useWorkspaceStyle.wrapSSR, hashId = _useWorkspaceStyle.hashId;
    var containerRef = useRef(null);
    var _useState = _sliced_to_array(useState(0), 2), segmentedKey = _useState[0], setSegmentedKey = _useState[1];
    var _useState1 = _sliced_to_array(useState(0), 2), resetKey = _useState1[0], setResetKey = _useState1[1];
    var displayTitle = title !== null && title !== void 0 ? title : (locale === null || locale === void 0 ? void 0 : locale['workspace.title']) || 'Workspace';
    var defaultConfig = DEFAULT_CONFIG(locale);
    var _useState2 = _sliced_to_array(useState(''), 2), internalActiveTab = _useState2[0], setInternalActiveTab = _useState2[1];
    var availableTabs = useMemo(function() {
        var tabs = [];
        React.Children.forEach(children, function(child, index) {
            if (!/*#__PURE__*/ React.isValidElement(child)) return;
            var componentType = COMPONENT_MAP.get(child.type);
            if (!componentType) return;
            var tabConfig = resolveTabConfig(child.props.tab, defaultConfig[componentType], componentType === "custom" ? index : undefined);
            tabs.push({
                key: tabConfig.key,
                icon: tabConfig.icon,
                componentType: componentType,
                label: /*#__PURE__*/ React.createElement("div", {
                    className: classNames("".concat(prefixCls, "-tab-item"), hashId)
                }, /*#__PURE__*/ React.createElement("span", {
                    className: classNames("".concat(prefixCls, "-tab-title"), hashId)
                }, tabConfig.title), tabConfig.count !== undefined && /*#__PURE__*/ React.createElement("span", {
                    className: classNames("".concat(prefixCls, "-tab-count"), hashId)
                }, tabConfig.count)),
                content: /*#__PURE__*/ React.createElement(child.type, _object_spread({}, child.props, componentType === "file" && {
                    resetKey: resetKey
                }))
            });
        });
        return tabs;
    }, [
        children,
        defaultConfig,
        hashId,
        prefixCls
    ]);
    useEffect(function() {
        if (!availableTabs.length) return;
        var isControlled = activeTabKey !== undefined;
        var currentKey = isControlled ? activeTabKey : internalActiveTab;
        if (!availableTabs.some(function(tab) {
            return tab.key === currentKey;
        })) {
            var firstKey = availableTabs[0].key;
            if (!isControlled) setInternalActiveTab(firstKey);
            onTabChange === null || onTabChange === void 0 ? void 0 : onTabChange(firstKey);
        } else if (isControlled) {
            setInternalActiveTab(currentKey);
        }
    }, [
        availableTabs,
        activeTabKey,
        internalActiveTab,
        onTabChange
    ]);
    // 监听容器宽度变化，强制 Segmented 重新渲染
    useEffect(function() {
        if (!containerRef.current) return;
        var el = containerRef.current;
        var lastWidth = el.getBoundingClientRect().width;
        var observer = new ResizeObserver(function(entries) {
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                for(var _iterator = entries[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var entry = _step.value;
                    var width = entry.contentRect.width;
                    if (width > 0 && lastWidth === 0) {
                        setSegmentedKey(function(k) {
                            return k + 1;
                        });
                    }
                    lastWidth = width;
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
        });
        observer.observe(el);
        return function() {
            return observer.disconnect();
        };
    }, []);
    var currentActiveTab = (_ref = (_ref1 = (_availableTabs_find = availableTabs.find(function(tab) {
        return tab.key === (activeTabKey !== null && activeTabKey !== void 0 ? activeTabKey : internalActiveTab);
    })) === null || _availableTabs_find === void 0 ? void 0 : _availableTabs_find.key) !== null && _ref1 !== void 0 ? _ref1 : (_availableTabs_ = availableTabs[0]) === null || _availableTabs_ === void 0 ? void 0 : _availableTabs_.key) !== null && _ref !== void 0 ? _ref : '';
    var handleTabChange = function(key) {
        var tabKey = String(key);
        if (activeTabKey === undefined) setInternalActiveTab(tabKey);
        setResetKey(function(prev) {
            return prev + 1;
        });
        onTabChange === null || onTabChange === void 0 ? void 0 : onTabChange(tabKey);
    };
    if (!availableTabs.length) return null;
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        className: classNames(prefixCls, _define_property({}, "".concat(prefixCls, "-pure"), pure), className, hashId),
        style: style,
        "data-testid": "workspace"
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header"), hashId),
        "data-testid": "workspace-header"
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-title"), hashId),
        "data-testid": "workspace-title"
    }, displayTitle), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header-right"), hashId)
    }, headerExtra, onClose && /*#__PURE__*/ React.createElement(ActionIconBox, {
        className: classNames("".concat(prefixCls, "-close"), hashId),
        onClick: onClose,
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.closeWorkspace']) || '关闭工作空间',
        "data-testid": "workspace-close"
    }, /*#__PURE__*/ React.createElement(X, null)))), availableTabs.length > 1 && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-tabs"), hashId),
        "data-testid": "workspace-tabs"
    }, /*#__PURE__*/ React.createElement(Segmented, {
        key: segmentedKey,
        className: classNames("".concat(prefixCls, "-segmented"), hashId),
        options: availableTabs.reduce(function(acc, param, index) {
            var label = param.label, key = param.key, icon = param.icon, componentType = param.componentType;
            acc.push({
                label: label,
                value: key,
                icon: icon
            });
            // 只在第一个"实时跟随"组件后插入分割线
            var isFirstRealtime = componentType === "realtime" && availableTabs.findIndex(function(tab) {
                return tab.componentType === "realtime";
            }) === index;
            if (isFirstRealtime && availableTabs.length > 1) {
                acc.push({
                    label: '',
                    value: '__divider__',
                    disabled: true
                });
            }
            return acc;
        }, []),
        value: currentActiveTab,
        onChange: handleTabChange,
        block: true,
        "data-testid": "workspace-segmented"
    })), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-content"), hashId),
        "data-testid": "workspace-content"
    }, (_availableTabs_find1 = availableTabs.find(function(tab) {
        return tab.key === currentActiveTab;
    })) === null || _availableTabs_find1 === void 0 ? void 0 : _availableTabs_find1.content)));
};
Workspace.Realtime = RealtimeComponent;
Workspace.Browser = BrowserComponent;
Workspace.Task = TaskComponent;
Workspace.File = FileComponent;
Workspace.Custom = CustomComponent;
export * from "./File";
export default Workspace;
