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 _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
}
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 { GripVertical, Menu } from "@sofa-design/icons";
import { ConfigProvider, Popover } from "antd";
import classNames from "clsx";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useStyle } from "../../Components/ActionItemBox";
import { useRefFunction } from "../../Hooks/useRefFunction";
// 常量提取
var INTERACTIVE_SELECTOR = 'button, a, input, textarea, select, [role="button"], [contenteditable="true"], [data-no-pan]';
var PAN_THRESHOLD = 6;
var SCROLL_STYLE = {
    display: 'flex',
    alignItems: 'center',
    width: '100%',
    gap: 8,
    overflowX: 'auto',
    overflowY: 'hidden',
    WebkitOverflowScrolling: 'touch',
    overscrollBehavior: 'contain',
    touchAction: 'pan-x',
    paddingRight: 54
};
var POPOVER_OVERLAY_STYLE = {
    padding: 0
};
// 可拖拽的 Popup Item 子组件
var DraggablePopupItem = /*#__PURE__*/ React.memo(function(props) {
    var entry = props.entry, index = props.index, basePrefixCls = props.basePrefixCls, hashId = props.hashId, draggingIndex = props.draggingIndex, overIndex = props.overIndex, isHandlePressRef = props.isHandlePressRef, onDragStart = props.onDragStart, onDragOver = props.onDragOver, onDrop = props.onDrop, onDragEnd = props.onDragEnd, isHandleTarget = props.isHandleTarget, setDraggingIndex = props.setDraggingIndex;
    var handleMouseDown = useRefFunction(function(evt) {
        var isHandle = isHandleTarget(evt.target);
        isHandlePressRef.current = isHandle;
        setDraggingIndex(isHandle ? index : null);
    });
    var handleMouseUp = useRefFunction(function() {
        if (draggingIndex === null) {
            isHandlePressRef.current = false;
        }
    });
    var handleGripMouseDown = useRefFunction(function(evt) {
        isHandlePressRef.current = true;
        setDraggingIndex(index);
        evt.stopPropagation();
    });
    var _obj;
    return /*#__PURE__*/ React.createElement("div", {
        key: entry.key,
        className: classNames("".concat(basePrefixCls, "-overflow-container-popup-item"), hashId, (_obj = {}, _define_property(_obj, "".concat(basePrefixCls, "-dragging"), draggingIndex === index), _define_property(_obj, "".concat(basePrefixCls, "-drag-over"), overIndex === index), _obj)),
        draggable: true,
        onMouseDown: handleMouseDown,
        onMouseUp: handleMouseUp,
        onDragStart: function onDragStart1(evt) {
            return onDragStart(evt, index);
        },
        onDragOver: function onDragOver1(evt) {
            return onDragOver(evt, index);
        },
        onDrop: function onDrop1(evt) {
            return onDrop(evt, index);
        },
        onDragEnd: onDragEnd
    }, /*#__PURE__*/ React.createElement(GripVertical, {
        className: classNames("".concat(basePrefixCls, "-drag-handle"), hashId),
        onMouseDown: handleGripMouseDown
    }), /*#__PURE__*/ React.createElement("div", {
        draggable: false
    }, entry.node));
});
DraggablePopupItem.displayName = 'DraggablePopupItem';
export var ActionItemContainer = function ActionItemContainer(props) {
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var basePrefixCls = getPrefixCls('agentic-chat-action-item-box');
    var _useStyle = useStyle(basePrefixCls), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var containerRef = useRef(null);
    var scrollRef = useRef(null);
    var _useState = _sliced_to_array(useState(false), 2), isIndicatorHover = _useState[0], setIsIndicatorHover = _useState[1];
    var _useState1 = _sliced_to_array(useState(false), 2), showOverflowPopup = _useState1[0], setShowOverflowPopup = _useState1[1];
    var _useState2 = _sliced_to_array(useState(null), 2), draggingIndex = _useState2[0], setDraggingIndex = _useState2[1];
    var _useState3 = _sliced_to_array(useState(null), 2), overIndex = _useState3[0], setOverIndex = _useState3[1];
    var isHandlePressRef = useRef(false);
    // horizontal drag-to-scroll state (main container only)
    var isPanningRef = useRef(false);
    var panStartXRef = useRef(0);
    var panStartScrollLeftRef = useRef(0);
    var hasPanMovedRef = useRef(false);
    var panIntentRef = useRef(false);
    // 辅助函数：检查是否是交互元素
    var isInteractiveTarget = useRefFunction(function(target) {
        if (!_instanceof(target, HTMLElement)) return false;
        return !!target.closest(INTERACTIVE_SELECTOR);
    });
    // 辅助函数：检查是否是拖拽手柄
    var isHandleTarget = useRefFunction(function(target) {
        if (!_instanceof(target, HTMLElement)) return false;
        var handle = target.closest(".".concat(basePrefixCls, "-drag-handle"));
        return !!handle;
    });
    // 辅助函数：将子节点转换为条目数组
    var toEntries = useRefFunction(function(nodes) {
        var array = React.Children.toArray(nodes);
        return array.map(function(node) {
            var _ref;
            return {
                key: (_ref = node === null || node === void 0 ? void 0 : node.key) !== null && _ref !== void 0 ? _ref : null,
                node: node
            };
        });
    });
    var _useState4 = _sliced_to_array(useState(function() {
        return toEntries(props.children);
    }), 2), ordered = _useState4[0], setOrdered = _useState4[1];
    useEffect(function() {
        if (process.env.NODE_ENV === 'production') return;
        var hasMissingKey = false;
        React.Children.forEach(props.children, function(child) {
            if (!/*#__PURE__*/ React.isValidElement(child)) return;
            if (child.key === null) {
                hasMissingKey = true;
            }
        });
        if (hasMissingKey) {
            throw new Error('ActionItemContainer: all children must include an explicit `key` prop.');
        }
    }, [
        props.children
    ]);
    // keep ordered list in sync when children change; preserve existing order by key when possible
    useEffect(function() {
        var incoming = toEntries(props.children);
        var existingKeys = new Set(ordered.map(function(e) {
            return e.key;
        }));
        // map existing order
        var merged = [];
        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
        try {
            var _loop = function() {
                var e = _step.value;
                if (incoming.find(function(i) {
                    return i.key === e.key;
                })) {
                    // replace node to reflect latest props while keeping position
                    var updated = incoming.find(function(i) {
                        return i.key === e.key;
                    });
                    merged.push({
                        key: e.key,
                        node: updated.node
                    });
                }
            };
            // keep items in previous order for keys that still exist
            for(var _iterator = ordered[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally{
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
        var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
        try {
            // append any new items not seen before
            for(var _iterator1 = incoming[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
                var e = _step1.value;
                if (!existingKeys.has(e.key)) {
                    merged.push(e);
                }
            }
        } catch (err) {
            _didIteratorError1 = true;
            _iteratorError1 = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
                    _iterator1.return();
                }
            } finally{
                if (_didIteratorError1) {
                    throw _iteratorError1;
                }
            }
        }
        // if counts don't match (e.g., many changes), fallback to incoming order
        setOrdered(merged.length === incoming.length ? merged : incoming);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
        props.children
    ]);
    // 辅助函数：重新排序数组
    var reorder = useRefFunction(function(list, from, to) {
        var next = list.slice();
        var _next_splice = _sliced_to_array(next.splice(from, 1), 1), moved = _next_splice[0];
        next.splice(to, 0, moved);
        return next;
    });
    // 拖拽事件处理
    var handleDragStart = useRefFunction(function(e, index) {
        e.stopPropagation();
        e.dataTransfer.effectAllowed = 'move';
        try {
            e.dataTransfer.setData('text/plain', String(index));
        } catch (unused) {
            console.error(e);
        }
        setDraggingIndex(index);
    });
    var handleDragOver = useRefFunction(function(e, index) {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        if (overIndex !== index) setOverIndex(index);
    });
    var handleDrop = useRefFunction(function(e, index) {
        e.preventDefault();
        e.stopPropagation();
        if (draggingIndex === null) return;
        if (draggingIndex === index) return;
        setOrdered(function(prev) {
            return reorder(prev, draggingIndex, index);
        });
        setDraggingIndex(null);
        setOverIndex(null);
        isHandlePressRef.current = false;
    });
    var handleDragEnd = useRefFunction(function() {
        setDraggingIndex(null);
        setOverIndex(null);
        isHandlePressRef.current = false;
    });
    // Pointer 事件处理 - 拖拽滚动
    var handlePointerDown = useRefFunction(function(e) {
        var el = scrollRef.current;
        if (!el || e.button !== 0 || isInteractiveTarget(e.target)) return;
        panIntentRef.current = true;
        hasPanMovedRef.current = false;
        panStartXRef.current = e.clientX;
        panStartScrollLeftRef.current = el.scrollLeft;
    });
    var handlePointerMove = useRefFunction(function(e) {
        var el = scrollRef.current;
        if (!el) return;
        // 检测是否开始拖拽
        if (!isPanningRef.current && panIntentRef.current) {
            var dx = e.clientX - panStartXRef.current;
            if (Math.abs(dx) > PAN_THRESHOLD) {
                isPanningRef.current = true;
                hasPanMovedRef.current = true;
                try {
                    el.setPointerCapture(e.pointerId);
                } catch (unused) {}
            }
        }
        // 执行拖拽滚动
        if (isPanningRef.current) {
            var dx1 = e.clientX - panStartXRef.current;
            el.scrollLeft = panStartScrollLeftRef.current - dx1;
            if (e.cancelable) e.preventDefault();
            e.stopPropagation();
        }
    });
    var handlePointerUp = useRefFunction(function(e) {
        var el = scrollRef.current;
        if (!el) return;
        panIntentRef.current = false;
        if (isPanningRef.current) {
            isPanningRef.current = false;
            try {
                el.releasePointerCapture(e.pointerId);
            } catch (unused) {}
        }
    });
    var handlePointerCancel = useRefFunction(function() {
        isPanningRef.current = false;
        panIntentRef.current = false;
    });
    var handleWheel = useRefFunction(function(e) {
        var el = scrollRef.current;
        if (!el) return;
        // 将滚轮事件映射到水平滚动
        var horizontalDelta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
        if (horizontalDelta !== 0) {
            el.scrollLeft += horizontalDelta;
        }
        e.stopPropagation();
    });
    var handleClick = useRefFunction(function(e) {
        // 防止拖拽时误触点击
        if (hasPanMovedRef.current) {
            e.preventDefault();
            e.stopPropagation();
            hasPanMovedRef.current = false;
        }
    });
    // Popover 事件处理
    var handlePopoverChange = useRefFunction(function(visible) {
        if (!props.menuDisabled) {
            setShowOverflowPopup(visible);
        }
    });
    var handleMenuMouseEnter = useRefFunction(function() {
        if (!props.menuDisabled) {
            setIsIndicatorHover(true);
        }
    });
    var handleMenuMouseLeave = useRefFunction(function() {
        if (!props.menuDisabled) {
            setIsIndicatorHover(false);
        }
    });
    var handlePopupWheel = useRefFunction(function(e) {
        e.stopPropagation();
    });
    // 容器样式
    var containerStyle = useMemo(function() {
        return _object_spread({}, props.style);
    }, [
        props.style
    ]);
    var containerClassName = useMemo(function() {
        var _obj;
        return classNames("".concat(basePrefixCls, "-container"), (_obj = {}, _define_property(_obj, "".concat(basePrefixCls, "-container-").concat(props.size), props.size), _define_property(_obj, "".concat(basePrefixCls, "-container-no-hover"), isIndicatorHover), _obj), hashId);
    }, [
        basePrefixCls,
        props.size,
        isIndicatorHover,
        hashId
    ]);
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        style: containerStyle,
        className: containerClassName,
        onPointerDown: handlePointerDown,
        onPointerMove: handlePointerMove,
        onPointerUp: handlePointerUp,
        onPointerCancel: handlePointerCancel,
        onWheel: handleWheel,
        onClick: handleClick
    }, /*#__PURE__*/ React.createElement("div", {
        ref: scrollRef,
        className: classNames("".concat(basePrefixCls, "-scroll"), hashId),
        style: SCROLL_STYLE
    }, ordered.map(function(entry) {
        return /*#__PURE__*/ React.createElement(React.Fragment, {
            key: entry.key
        }, entry.node);
    })), props.showMenu !== false && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(basePrefixCls, "-overflow-container"), hashId),
        "data-no-pan": true
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(basePrefixCls, "-overflow-container-indicator"), hashId)
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(basePrefixCls, "-overflow-container-placeholder"), hashId)
    }), /*#__PURE__*/ React.createElement(Popover, {
        open: showOverflowPopup,
        onOpenChange: handlePopoverChange,
        trigger: "click",
        placement: "topRight",
        arrow: false,
        styles: {
            body: POPOVER_OVERLAY_STYLE
        },
        overlayClassName: classNames("".concat(basePrefixCls, "-overflow-popover"), hashId),
        content: /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(basePrefixCls, "-overflow-container-popup"), hashId),
            onWheel: handlePopupWheel
        }, ordered.map(function(entry, index) {
            return /*#__PURE__*/ React.createElement(DraggablePopupItem, {
                key: entry.key,
                entry: entry,
                index: index,
                basePrefixCls: basePrefixCls,
                hashId: hashId,
                draggingIndex: draggingIndex,
                overIndex: overIndex,
                isHandlePressRef: isHandlePressRef,
                onDragStart: handleDragStart,
                onDragOver: handleDragOver,
                onDrop: handleDrop,
                onDragEnd: handleDragEnd,
                isHandleTarget: isHandleTarget,
                setDraggingIndex: setDraggingIndex
            });
        }))
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(basePrefixCls, "-overflow-container-menu"), hashId, _define_property({}, "".concat(basePrefixCls, "-overflow-container-menu-disabled"), props.menuDisabled)),
        onMouseEnter: handleMenuMouseEnter,
        onMouseLeave: handleMenuMouseLeave
    }, /*#__PURE__*/ React.createElement(Menu, null)))))));
};
ActionItemContainer.displayName = 'ActionItemContainer';
