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 ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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 { X } from "@sofa-design/icons";
import { ConfigProvider, Image } from "antd";
import classNames from "clsx";
import React, { useContext, useEffect, useRef, useState } from "react";
import { ActionIconBox } from "../../../Components/ActionIconBox";
import { I18nContext } from "../../../I18n";
import { isImageFile } from "../utils";
import { AttachmentFileListItem } from "./AttachmentFileListItem";
import { useStyle } from "./style";
var HIDDEN_STYLE = {
    height: 0,
    overflow: 'hidden',
    padding: 0
};
var IMAGE_PREVIEW_STYLE = {
    display: 'none'
};
var CLEAR_BUTTON_TRANSITION = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
/**
 * 子项 stagger 入场延迟（秒/项）。
 * 等价于历史 framer-motion 父级 `staggerChildren: 0.1`。
 */ var ATTACHMENT_ITEM_STAGGER_S = 0.1;
/**
 * 子项退出动画时长（毫秒），与 style.ts 中 `-item-motion` 的 `animationDuration: 0.25s` 保持一致。
 * 测试环境下置 0，避免 jsdom 无 animationend 事件、setTimeout 异步等待引发的断言不稳定。
 */ var ATTACHMENT_ITEM_EXIT_DURATION_MS = process.env.NODE_ENV === 'test' ? 0 : 250;
var getFileKey = function getFileKey(file, index) {
    return (file === null || file === void 0 ? void 0 : file.uuid) || (file === null || file === void 0 ? void 0 : file.name) || index;
};
var openFileInNewWindow = function openFileInNewWindow(url) {
    if (typeof window === 'undefined' || !url) return;
    window.open(url, '_blank');
};
var ClearButton = function ClearButton(param) {
    var visible = param.visible, onClick = param.onClick, className = param.className;
    if (!visible) return null;
    return /*#__PURE__*/ React.createElement(ActionIconBox, {
        style: {
            transition: CLEAR_BUTTON_TRANSITION
        },
        onClick: onClick,
        className: className
    }, /*#__PURE__*/ React.createElement(X, null));
};
export var AttachmentFileList = function AttachmentFileList(param) {
    var fileMap = param.fileMap, onDelete = param.onDelete, onPreview = param.onPreview, onDownload = param.onDownload, onRetry = param.onRetry, onClearFileMap = param.onClearFileMap, dataTestId = param.dataTestId;
    var context = useContext(ConfigProvider.ConfigContext);
    var locale = useContext(I18nContext).locale;
    var prefix = context === null || context === void 0 ? void 0 : context.getPrefixCls('agentic-md-editor-attachment-list');
    var _useStyle = useStyle(prefix), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var _React_useState = _sliced_to_array(React.useState(undefined), 2), imgSrc = _React_useState[0], setImgSrc = _React_useState[1];
    var fileList = Array.from((fileMap === null || fileMap === void 0 ? void 0 : fileMap.values()) || []);
    var fileCount = (fileMap === null || fileMap === void 0 ? void 0 : fileMap.size) || 0;
    var hasFiles = fileList.length > 0;
    var isAnyUploading = fileList.some(function(file) {
        return file.status === 'uploading';
    });
    // 有文件且没有正在上传时才显示清空按钮，避免空列表时透明按钮占用布局空间
    var canShowClearButton = hasFiles && !isAnyUploading;
    var containerStyle = fileCount ? {} : HIDDEN_STYLE;
    // ---- 等价 AnimatePresence：维护"被移除但尚在播放退出动画"的影子项 ----
    // 当外部 fileMap 中的某项被移除时，先在 renderEntries 中标记为 'exit'，
    // ATTACHMENT_ITEM_EXIT_DURATION_MS 后再真正卸载。
    var _useState = _sliced_to_array(useState(function() {
        return fileList.map(function(file, index) {
            return {
                key: getFileKey(file, index),
                file: file,
                index: index,
                state: 'enter'
            };
        });
    }), 2), renderEntries = _useState[0], setRenderEntries = _useState[1];
    var exitTimersRef = useRef(new Map());
    useEffect(function() {
        var nextKeys = new Set();
        var nextEntriesByKey = new Map();
        fileList.forEach(function(file, index) {
            var key = getFileKey(file, index);
            nextKeys.add(key);
            nextEntriesByKey.set(key, {
                key: key,
                file: file,
                index: index,
                state: 'enter'
            });
        });
        setRenderEntries(function(prev) {
            var merged = [];
            var seen = new Set();
            // 1) 优先按当前 fileMap 顺序输出仍存在的项（state='enter'，刷新 file/index）
            fileList.forEach(function(file, index) {
                var key = getFileKey(file, index);
                merged.push({
                    key: key,
                    file: file,
                    index: index,
                    state: 'enter'
                });
                seen.add(key);
                // 若先前曾被标记为 exit 但又重新加入，取消其 pending 卸载定时器
                var pendingTimer = exitTimersRef.current.get(key);
                if (pendingTimer !== undefined) {
                    window.clearTimeout(pendingTimer);
                    exitTimersRef.current.delete(key);
                }
            });
            // 2) 上一轮存在但本轮被移除的项，标记为 exit 并保留在列表中（位置沿用上一轮）
            prev.forEach(function(entry, prevIdx) {
                if (seen.has(entry.key) || nextKeys.has(entry.key)) return;
                // 已经在 exit 中的，保持不动；首次转为 exit 的，启动延迟卸载定时器
                var exitingEntry = _object_spread_props(_object_spread({}, entry), {
                    state: 'exit'
                });
                // 插入到大致原位置以保持视觉稳定
                var insertAt = Math.min(prevIdx, merged.length);
                merged.splice(insertAt, 0, exitingEntry);
                if (entry.state !== 'exit') {
                    var timerId = window.setTimeout(function() {
                        exitTimersRef.current.delete(entry.key);
                        setRenderEntries(function(curr) {
                            return curr.filter(function(it) {
                                return it.key !== entry.key;
                            });
                        });
                    }, ATTACHMENT_ITEM_EXIT_DURATION_MS);
                    exitTimersRef.current.set(entry.key, timerId);
                }
            });
            return merged;
        });
    // 仅依赖 fileMap 引用变化即可触发对齐
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
        fileMap
    ]);
    // 卸载时清理所有 pending 定时器
    useEffect(function() {
        var timers = exitTimersRef.current;
        return function() {
            timers.forEach(function(id) {
                return window.clearTimeout(id);
            });
            timers.clear();
        };
    }, []);
    var handlePreview = function handlePreview(file) {
        if (onPreview) {
            onPreview(file);
            return;
        }
        if (isImageFile(file)) {
            setImgSrc(file.previewUrl || file.url);
            return;
        }
        openFileInNewWindow(file.previewUrl || file.url);
    };
    var handlePreviewClose = function handlePreviewClose(visible) {
        if (!visible) setImgSrc(undefined);
    };
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefix, "-container"), hashId, _define_property({}, "".concat(prefix, "-container-empty"), !hasFiles)),
        "data-testid": dataTestId
    }, /*#__PURE__*/ React.createElement("div", {
        style: containerStyle,
        className: classNames(prefix, hashId, "".concat(prefix, "-motion-fade-in"))
    }, hasFiles ? /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefix, "-title"), hashId),
        "data-testid": "attachment-list-title"
    }, (locale === null || locale === void 0 ? void 0 : locale['input.attachmentListTitle']) || '上传附件') : null, renderEntries.map(function(entry) {
        return /*#__PURE__*/ React.createElement(AttachmentFileListItem, {
            prefixCls: "".concat(prefix, "-item"),
            hashId: hashId,
            className: classNames(hashId, "".concat(prefix, "-item")),
            key: entry.key,
            file: entry.file,
            onDelete: onDelete,
            onPreview: onPreview !== null && onPreview !== void 0 ? onPreview : handlePreview,
            onDownload: onDownload,
            onRetry: onRetry,
            motionState: entry.state,
            motionDelaySec: entry.state === 'enter' ? entry.index * ATTACHMENT_ITEM_STAGGER_S : 0
        });
    }), /*#__PURE__*/ React.createElement(Image, {
        key: "preview",
        src: imgSrc,
        alt: "Preview",
        style: IMAGE_PREVIEW_STYLE,
        preview: {
            visible: !!imgSrc,
            scaleStep: 1,
            src: imgSrc,
            onVisibleChange: handlePreviewClose
        }
    })), /*#__PURE__*/ React.createElement(ClearButton, {
        visible: canShowClearButton,
        onClick: onClearFileMap,
        className: classNames("".concat(prefix, "-close-icon"), hashId)
    })));
};
