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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
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);
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { LoadingOutlined } from "@ant-design/icons";
import { Skeleton } from "antd";
import React, { useEffect, useLayoutEffect, useMemo, useState } from "react";
import { useRefFunction } from "../../../../Hooks/useRefFunction";
import { MediaErrorLink } from "../../components/MediaErrorLink";
import { useGetSetState } from "../../utils";
import { getMediaType } from "../../utils/dom";
import { ReadonlyImage } from "../Image";
/**
 * ReadonlyMedia 组件 - 只读媒体预览组件
 *
 * 专门针对 readonly 模式优化的媒体组件，移除了编辑相关功能（调整大小、删除等）。
 * 简化渲染逻辑，提升预览模式性能。
 *
 * @component
 * @description 只读媒体预览组件，用于预览模式下的媒体渲染
 * @param {ElementProps<MediaNode>} props - 组件属性
 * @param {MediaNode} props.element - 媒体节点元素
 * @param {React.ReactNode} props.children - 子组件内容
 * @param {Object} props.attributes - 元素属性
 *
 * @example
 * ```tsx
 * <ReadonlyMedia
 *   element={mediaNode}
 *   attributes={attributes}
 * >
 *   媒体内容
 * </ReadonlyMedia>
 * ```
 *
 * @returns {React.ReactElement} 渲染的只读媒体组件
 *
 * @remarks
 * - 移除调整大小功能
 * - 移除删除功能
 * - 移除选择状态管理
 * - 简化状态管理逻辑
 * - 使用 React.memo 优化性能
 * - 保持预览模式的视觉效果
 */ export var ReadonlyMedia = /*#__PURE__*/ React.memo(function(param) {
    var element = param.element, attributes = param.attributes, children = param.children;
    var _state, _state1;
    var _useState = _sliced_to_array(useState(false), 2), showAsText = _useState[0], setShowAsText = _useState[1];
    var _useGetSetState = _sliced_to_array(useGetSetState({
        loadSuccess: true,
        url: '',
        type: getMediaType(element === null || element === void 0 ? void 0 : element.url, element.alt)
    }), 2), state = _useGetSetState[0], setState = _useGetSetState[1];
    // 如果 finished 为 false，设置 5 秒超时，超时后显示为文本
    useEffect(function() {
        if (element.finished === false) {
            setShowAsText(false);
            var timer = setTimeout(function() {
                setShowAsText(true);
            }, 5000);
            return function() {
                clearTimeout(timer);
            };
        } else {
            setShowAsText(false);
        }
    }, [
        element.finished
    ]);
    var initial = useRefFunction(function() {
        return _async_to_generator(function() {
            var type, finalType, realUrl, img, video, audio;
            return _ts_generator(this, function(_state) {
                type = getMediaType(element === null || element === void 0 ? void 0 : element.url, element.alt);
                type = !type ? 'image' : type;
                finalType = [
                    'image',
                    'video',
                    'autio',
                    'attachment'
                ].includes(type) ? type : 'other';
                setState({
                    type: finalType
                });
                realUrl = element === null || element === void 0 ? void 0 : element.url;
                setState({
                    url: realUrl
                });
                if (finalType === 'image' || finalType === 'other') {
                    img = document.createElement('img');
                    img.referrerPolicy = 'no-referrer';
                    img.crossOrigin = 'anonymous';
                    img.src = realUrl;
                    img.onerror = function() {
                        setState({
                            loadSuccess: false
                        });
                    };
                    img.onload = function() {
                        return setState({
                            loadSuccess: true
                        });
                    };
                }
                if (finalType === 'video') {
                    video = document.createElement('video');
                    video.src = realUrl;
                    video.preload = 'metadata';
                    video.onerror = function() {
                        setState({
                            loadSuccess: false
                        });
                    };
                    video.onloadedmetadata = function() {
                        setState({
                            loadSuccess: true
                        });
                    };
                }
                if (finalType === 'audio') {
                    audio = document.createElement('audio');
                    audio.src = realUrl;
                    audio.preload = 'metadata';
                    audio.onerror = function() {
                        setState({
                            loadSuccess: false
                        });
                    };
                    audio.onloadedmetadata = function() {
                        setState({
                            loadSuccess: true
                        });
                    };
                }
                return [
                    2
                ];
            });
        })();
    });
    useLayoutEffect(function() {
        initial();
    }, [
        element === null || element === void 0 ? void 0 : element.url
    ]);
    // 图片预览
    var imageDom = useMemo(function() {
        var _state;
        if (state().type !== 'image' && state().type !== 'other') return null;
        // 检查是否为不完整的图片（finished 状态）
        if (element.finished === false) {
            // 如果 5 秒后仍未完成，显示为文本
            if (showAsText) {
                return /*#__PURE__*/ React.createElement("div", {
                    style: {
                        padding: '8px 12px',
                        border: '1px solid #d9d9d9',
                        borderRadius: '4px',
                        color: 'rgba(0, 0, 0, 0.65)',
                        wordBreak: 'break-all'
                    }
                }, element.alt || element.url || '图片链接');
            }
            // 5 秒内显示 loading 状态的占位符
            return /*#__PURE__*/ React.createElement(Skeleton.Image, {
                active: true
            });
        }
        return /*#__PURE__*/ React.createElement(ReadonlyImage, {
            src: ((_state = state()) === null || _state === void 0 ? void 0 : _state.url) || (element === null || element === void 0 ? void 0 : element.url),
            alt: (element === null || element === void 0 ? void 0 : element.alt) || 'image',
            width: element.width,
            height: element.height,
            crossOrigin: "anonymous"
        });
    }, [
        state().type,
        (_state = state()) === null || _state === void 0 ? void 0 : _state.url,
        element.finished,
        showAsText,
        element.url,
        element.alt,
        element.width,
        element.height
    ]);
    // 媒体元素预览（video、audio、attachment）
    var mediaElement = useMemo(function() {
        var _element_otherProps;
        var rawMarkdown = (element === null || element === void 0 ? void 0 : element.rawMarkdown) || (element === null || element === void 0 ? void 0 : (_element_otherProps = element.otherProps) === null || _element_otherProps === void 0 ? void 0 : _element_otherProps.rawMarkdown);
        if (state().type === 'video') {
            var _state;
            // 如果是不完整状态
            if (element.finished === false) {
                // 如果 5 秒后仍未完成，显示为文本
                if (showAsText) {
                    return /*#__PURE__*/ React.createElement("div", {
                        style: {
                            padding: '8px 12px',
                            border: '1px solid #d9d9d9',
                            borderRadius: '4px',
                            color: 'rgba(0, 0, 0, 0.65)',
                            wordBreak: 'break-all'
                        }
                    }, element.alt || element.url || '视频链接');
                }
                // 5 秒内显示 loading 占位符
                return /*#__PURE__*/ React.createElement(Skeleton.Image, {
                    active: true
                });
            }
            if (!state().loadSuccess) {
                var _state1, _state2;
                return /*#__PURE__*/ React.createElement(MediaErrorLink, {
                    url: (_state1 = state()) === null || _state1 === void 0 ? void 0 : _state1.url,
                    fallbackUrl: element === null || element === void 0 ? void 0 : element.url,
                    displayText: element.alt || ((_state2 = state()) === null || _state2 === void 0 ? void 0 : _state2.url) || (element === null || element === void 0 ? void 0 : element.url) || '视频链接'
                });
            }
            return /*#__PURE__*/ React.createElement("video", {
                "data-testid": "video-element",
                controls: element.controls !== false,
                autoPlay: element.autoplay,
                loop: element.loop,
                muted: element.muted,
                poster: element.poster,
                style: {
                    width: element.width ? "".concat(element.width, "px") : '100%',
                    height: element.height ? "".concat(element.height, "px") : 'auto',
                    maxWidth: '100%',
                    borderRadius: '6px',
                    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                    display: 'block'
                },
                src: ((_state = state()) === null || _state === void 0 ? void 0 : _state.url) || '',
                preload: "metadata",
                onError: function onError() {
                    var _state;
                    console.warn('Video failed to load:', (_state = state()) === null || _state === void 0 ? void 0 : _state.url);
                    setState({
                        loadSuccess: false
                    });
                }
            });
        }
        if (state().type === 'audio') {
            var _state3;
            // 如果是不完整状态
            if (element.finished === false) {
                // 如果 5 秒后仍未完成，显示为文本
                if (showAsText) {
                    return /*#__PURE__*/ React.createElement("div", {
                        style: {
                            padding: '8px 12px',
                            border: '1px solid #d9d9d9',
                            borderRadius: '4px',
                            color: 'rgba(0, 0, 0, 0.65)',
                            wordBreak: 'break-all'
                        }
                    }, element.alt || element.url || '音频链接');
                }
                // 5 秒内显示 loading 占位符
                return /*#__PURE__*/ React.createElement("div", {
                    style: {
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '8px',
                        padding: '12px 16px',
                        border: '1px dashed #d9d9d9',
                        borderRadius: '6px',
                        backgroundColor: '#fafafa',
                        minWidth: '200px',
                        justifyContent: 'center'
                    }
                }, /*#__PURE__*/ React.createElement(LoadingOutlined, {
                    style: {
                        color: '#1890ff',
                        fontSize: '16px'
                    },
                    spin: true
                }), /*#__PURE__*/ React.createElement("span", {
                    style: {
                        color: '#666',
                        fontSize: '13px',
                        wordBreak: 'break-all'
                    }
                }, rawMarkdown || (element === null || element === void 0 ? void 0 : element.alt) || '音频加载中...'));
            }
            if (!state().loadSuccess) {
                var _state4, _state5;
                return /*#__PURE__*/ React.createElement(MediaErrorLink, {
                    url: (_state4 = state()) === null || _state4 === void 0 ? void 0 : _state4.url,
                    fallbackUrl: element === null || element === void 0 ? void 0 : element.url,
                    displayText: element.alt || ((_state5 = state()) === null || _state5 === void 0 ? void 0 : _state5.url) || (element === null || element === void 0 ? void 0 : element.url) || '音频链接'
                });
            }
            return /*#__PURE__*/ React.createElement("audio", {
                "data-testid": "audio-element",
                controls: true,
                style: {
                    width: '100%',
                    height: 'auto'
                },
                src: ((_state3 = state()) === null || _state3 === void 0 ? void 0 : _state3.url) || '',
                onError: function onError() {
                    var _state;
                    console.warn('Audio failed to load:', (_state = state()) === null || _state === void 0 ? void 0 : _state.url);
                    setState({
                        loadSuccess: false
                    });
                }
            }, "Your browser does not support the", /*#__PURE__*/ React.createElement("code", null, "audio"), " element.");
        }
        if (state().type === 'attachment') {
            var _state6;
            return /*#__PURE__*/ React.createElement("div", {
                style: {
                    padding: 12,
                    boxSizing: 'border-box',
                    border: '1px solid #f0f0f0',
                    borderRadius: '0.5em',
                    width: '100%',
                    backgroundImage: 'linear-gradient(rgb(249, 251, 255) 0%, rgb(243, 248, 255) 100%)',
                    flex: 1,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 12,
                    color: '#262626',
                    justifyContent: 'space-between'
                }
            }, /*#__PURE__*/ React.createElement("div", {
                style: {
                    display: 'flex',
                    alignItems: 'center',
                    gap: 12,
                    color: '#262626',
                    fontSize: 16,
                    flex: 1,
                    minWidth: 0
                }
            }, /*#__PURE__*/ React.createElement("div", {
                style: {
                    width: 40,
                    height: 40,
                    borderRadius: '0.25em',
                    backgroundColor: '#fff',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 20
                }
            }, "\uD83D\uDCCE"), /*#__PURE__*/ React.createElement("div", {
                style: {
                    flex: 1,
                    minWidth: 0,
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                }
            }, element.alt || element.url || '附件')), /*#__PURE__*/ React.createElement("div", {
                "data-icon-box": true,
                style: {
                    padding: '0 18px'
                }
            }, /*#__PURE__*/ React.createElement("a", {
                href: (_state6 = state()) === null || _state6 === void 0 ? void 0 : _state6.url,
                target: "_blank",
                rel: "noopener noreferrer",
                style: {
                    fontSize: 16,
                    cursor: 'pointer',
                    color: '#1677ff'
                }
            }, "查看")));
        }
        return null;
    }, [
        state().type,
        (_state1 = state()) === null || _state1 === void 0 ? void 0 : _state1.url,
        element.finished,
        showAsText,
        element === null || element === void 0 ? void 0 : element.rawMarkdown,
        element.url,
        element.alt,
        element.width,
        element.height,
        element.controls,
        element.autoplay,
        element.loop,
        element.muted,
        element.poster,
        state().loadSuccess
    ]);
    return /*#__PURE__*/ React.createElement("div", attributes, /*#__PURE__*/ React.createElement("div", {
        "data-be": "media",
        "data-testid": "media-container",
        style: {
            position: 'relative',
            display: 'flex',
            alignItems: 'flex-end',
            userSelect: 'none',
            WebkitUserSelect: 'none',
            MozUserSelect: 'none',
            msUserSelect: 'none',
            width: '100%',
            maxWidth: '100%',
            boxSizing: 'border-box'
        },
        draggable: false
    }, /*#__PURE__*/ React.createElement("div", {
        tabIndex: -1,
        style: {
            color: 'transparent',
            padding: 4,
            userSelect: 'none',
            display: 'flex',
            flexDirection: 'column',
            width: mediaElement ? '100%' : undefined,
            maxWidth: '100%',
            boxSizing: 'border-box'
        },
        draggable: false,
        contentEditable: false,
        "data-be": "media-container"
    }, mediaElement, imageDom, /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'none'
        }
    }, children))));
});
ReadonlyMedia.displayName = 'ReadonlyMedia';
