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 { LoadingOutlined } from "@ant-design/icons";
import { Download as DownloadIcon, ArrowLeft as LeftIcon, Locate, SquareArrowOutUpRight as ShareIcon } from "@sofa-design/icons";
import { Alert, ConfigProvider, Segmented, Spin } from "antd";
import classNames from "clsx";
import React, { useContext, useEffect, useRef, useState } from "react";
import { ActionIconBox } from "../../Components/ActionIconBox";
import { I18nContext } from "../../I18n";
import { MarkdownEditor } from "../../MarkdownEditor";
import { HtmlPreview } from "../HtmlPreview";
import { formatLastModified } from "../utils";
import { fileTypeProcessor } from "./FileTypeProcessor";
import { MediaPreview } from "./preview/components/MediaPreview";
import { PlaceholderContent } from "./preview/components/PlaceholderContent";
import { UnsupportedFileCard } from "./preview/components/UnsupportedFileCard";
import { usePreviewContent } from "./preview/usePreviewContent";
import { getContentStatus, isHtmlFile } from "./preview/utils";
import { useFileStyle } from "./style";
import { getFileTypeIcon } from "./utils";
var EDITOR_PADDING = '0 12px';
/**
 * 文件预览组件
 *
 * 渲染管线：
 * 1. `customContent` 优先 → 自定义节点
 * 2. 文件 `loading` → 流式占位
 * 3. `usePreviewContent` 未就绪 → Spin 占位
 * 4. 内容加载错误 → Alert 占位
 * 5. `canPreview === false` → `UnsupportedFileCard`
 * 6. 文本/代码 → `MarkdownEditor`（HTML 子类型走 `HtmlPreview`，支持 preview/code 切换）
 * 7. 图片/视频/音频/PDF → `MediaPreview`
 * 8. 其它 → 通用占位（含可选下载）
 */ export var PreviewComponent = function PreviewComponent(param) {
    var file = param.file, customContent = param.customContent, customHeader = param.customHeader, customActions = param.customActions, onBack = param.onBack, onDownload = param.onDownload, onShare = param.onShare, onLocate = param.onLocate, markdownEditorProps = param.markdownEditorProps, headerFileOverride = param.headerFileOverride;
    var _ref;
    var locale = useContext(I18nContext).locale;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var filePrefixCls = getPrefixCls('workspace-file');
    var _useFileStyle = useFileStyle(filePrefixCls), wrapSSR = _useFileStyle.wrapSSR, hashId = _useFileStyle.hashId;
    var prefixCls = "".concat(filePrefixCls, "-preview");
    var editorRef = useRef();
    var _usePreviewContent = usePreviewContent(file, customContent, locale), processResult = _usePreviewContent.processResult, contentState = _usePreviewContent.contentState;
    var _useState = _sliced_to_array(useState('preview'), 2), htmlViewMode = _useState[0], setHtmlViewMode = _useState[1];
    var canDownload = file.canDownload !== false;
    var handleDownload = function handleDownload() {
        if (!canDownload) return;
        onDownload === null || onDownload === void 0 ? void 0 : onDownload(file);
    };
    var handleShare = function handleShare(e) {
        onShare === null || onShare === void 0 ? void 0 : onShare(file, {
            anchorEl: e.currentTarget,
            origin: 'preview'
        });
    };
    var handleLocate = function handleLocate() {
        onLocate === null || onLocate === void 0 ? void 0 : onLocate(file);
    };
    // 内容就绪后注入到 MarkdownEditor store
    useEffect(function() {
        var _editorRef_current;
        if (customContent) return;
        if (((_editorRef_current = editorRef.current) === null || _editorRef_current === void 0 ? void 0 : _editorRef_current.store) && contentState.status === 'ready' && contentState.mdContent) {
            editorRef.current.store.setMDContent(contentState.mdContent);
        }
    }, [
        contentState,
        customContent
    ]);
    // 切换文件时重置 HTML 视图模式
    useEffect(function() {
        setHtmlViewMode('preview');
    }, [
        file.name
    ]);
    var isCurrentFileHtml = isHtmlFile(file.name, processResult === null || processResult === void 0 ? void 0 : processResult.dataSource.mimeType);
    var renderTextOrCode = function renderTextOrCode() {
        if (isCurrentFileHtml) {
            var htmlStatus = getContentStatus(contentState);
            var rawContent = contentState.status === 'error' ? '' : contentState.rawContent || '';
            return /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-text"), hashId)
            }, /*#__PURE__*/ React.createElement(HtmlPreview, {
                html: rawContent,
                status: htmlStatus,
                viewMode: htmlViewMode,
                onViewModeChange: setHtmlViewMode,
                iframeProps: {
                    sandbox: 'allow-scripts'
                },
                showSegmented: false
            }));
        }
        if (contentState.status === 'loading') {
            return /*#__PURE__*/ React.createElement(PlaceholderContent, {
                prefixCls: prefixCls,
                hashId: hashId
            }, /*#__PURE__*/ React.createElement(Spin, {
                size: "large",
                tip: (locale === null || locale === void 0 ? void 0 : locale['workspace.loadingFileContent']) || '正在加载文件内容...'
            }, /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-spin-anchor"), hashId),
                style: {
                    minHeight: 64,
                    width: '100%'
                },
                "aria-hidden": true
            })));
        }
        return /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(prefixCls, "-text"), hashId)
        }, /*#__PURE__*/ React.createElement(MarkdownEditor, _object_spread({
            editorRef: editorRef,
            initValue: "",
            readonly: true,
            contentStyle: {
                padding: EDITOR_PADDING
            }
        }, markdownEditorProps)));
    };
    var renderPreviewContent = function renderPreviewContent() {
        if (file.loading) {
            return /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-content-loading"), hashId)
            }, /*#__PURE__*/ React.createElement("span", {
                className: classNames("".concat(prefixCls, "-content-loading-tip"), hashId)
            }, /*#__PURE__*/ React.createElement(LoadingOutlined, null), (locale === null || locale === void 0 ? void 0 : locale['workspace.file.generating']) || '正在生成'), /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-content-loading-inner"), hashId)
            }, (file === null || file === void 0 ? void 0 : file.content) || '...'));
        }
        if (customContent) {
            return /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-custom-content"), hashId)
            }, customContent);
        }
        if (!processResult) {
            return /*#__PURE__*/ React.createElement(PlaceholderContent, {
                prefixCls: prefixCls,
                hashId: hashId
            }, /*#__PURE__*/ React.createElement(Spin, {
                size: "large",
                tip: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.processing']) || '正在处理文件...'
            }, /*#__PURE__*/ React.createElement("div", {
                className: classNames("".concat(prefixCls, "-spin-anchor"), hashId),
                style: {
                    minHeight: 64,
                    width: '100%'
                },
                "aria-hidden": true
            })));
        }
        if (contentState.status === 'error') {
            return /*#__PURE__*/ React.createElement(PlaceholderContent, {
                prefixCls: prefixCls,
                hashId: hashId
            }, /*#__PURE__*/ React.createElement(Alert, {
                message: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.processFailed']) || '文件处理失败',
                description: contentState.error,
                type: "error",
                showIcon: true
            }));
        }
        var typeInference = processResult.typeInference, dataSource = processResult.dataSource, canPreview = processResult.canPreview, previewMode = processResult.previewMode;
        if (!canPreview || previewMode === 'none') {
            return /*#__PURE__*/ React.createElement(UnsupportedFileCard, {
                file: file,
                canDownload: canDownload,
                onDownload: canDownload && onDownload ? handleDownload : undefined,
                filePrefixCls: filePrefixCls,
                prefixCls: prefixCls,
                hashId: hashId,
                locale: locale
            });
        }
        switch(typeInference.category){
            case 'text':
            case 'code':
                return renderTextOrCode();
            case 'image':
            case 'video':
            case 'audio':
            case 'pdf':
                return /*#__PURE__*/ React.createElement(MediaPreview, {
                    category: typeInference.category,
                    file: file,
                    previewUrl: dataSource.previewUrl,
                    prefixCls: prefixCls,
                    hashId: hashId,
                    locale: locale
                });
            default:
                return /*#__PURE__*/ React.createElement(PlaceholderContent, {
                    file: file,
                    showFileInfo: true,
                    onDownload: canDownload && onDownload ? handleDownload : undefined,
                    locale: locale,
                    prefixCls: prefixCls,
                    hashId: hashId
                }, /*#__PURE__*/ React.createElement("p", null, (locale === null || locale === void 0 ? void 0 : locale['workspace.file.unknownFileType']) || '未知的文件类型'), /*#__PURE__*/ React.createElement("p", null, (locale === null || locale === void 0 ? void 0 : locale['workspace.file.fileType']) || '文件类型：', typeInference.fileType));
        }
    };
    var headerFile = headerFileOverride ? _object_spread({}, file, headerFileOverride) : file;
    var headerFileType = fileTypeProcessor.inferFileType(file).fileType;
    var headerLastModified = (_ref = headerFileOverride === null || headerFileOverride === void 0 ? void 0 : headerFileOverride.lastModified) !== null && _ref !== void 0 ? _ref : file.lastModified;
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        className: classNames(prefixCls, hashId)
    }, customHeader ? /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header"), hashId)
    }, customHeader) : /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-header"), hashId)
    }, onBack && /*#__PURE__*/ React.createElement("button", {
        type: "button",
        className: classNames("".concat(prefixCls, "-back-button"), hashId),
        onClick: onBack,
        "aria-label": (locale === null || locale === void 0 ? void 0 : locale['workspace.file.backToFileList']) || '返回文件列表'
    }, /*#__PURE__*/ React.createElement(LeftIcon, {
        className: classNames("".concat(prefixCls, "-back-icon"), hashId)
    })), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-file-info"), hashId)
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-file-title"), hashId)
    }, /*#__PURE__*/ React.createElement("span", {
        className: classNames("".concat(prefixCls, "-file-icon"), hashId)
    }, getFileTypeIcon(headerFileType, headerFile.icon, headerFile.name)), /*#__PURE__*/ React.createElement("span", {
        className: classNames("".concat(prefixCls, "-file-name"), hashId)
    }, headerFile.name)), headerLastModified && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-generate-time"), hashId)
    }, (locale === null || locale === void 0 ? void 0 : locale['workspace.file.generationTime']) || '生成时间：', formatLastModified(headerLastModified))), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-actions"), hashId)
    }, !customContent && isCurrentFileHtml && /*#__PURE__*/ React.createElement(Segmented, {
        size: "small",
        options: [
            {
                label: (locale === null || locale === void 0 ? void 0 : locale['htmlPreview.preview']) || '预览',
                value: 'preview'
            },
            {
                label: (locale === null || locale === void 0 ? void 0 : locale['htmlPreview.code']) || '代码',
                value: 'code'
            }
        ],
        value: htmlViewMode,
        onChange: function onChange(val) {
            return setHtmlViewMode(val);
        }
    }), customActions && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-custom-actions"), hashId)
    }, customActions), onLocate && file.canLocate === true && /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.location']) || '定位',
        onClick: handleLocate,
        tooltipProps: {
            mouseEnterDelay: 0.3
        },
        className: classNames("".concat(prefixCls, "-item-action-btn"), hashId)
    }, /*#__PURE__*/ React.createElement(Locate, null)), onShare && file.canShare === true && /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.share']) || '分享',
        onClick: handleShare,
        tooltipProps: {
            mouseEnterDelay: 0.3
        },
        className: classNames("".concat(prefixCls, "-item-action-btn"), hashId)
    }, /*#__PURE__*/ React.createElement(ShareIcon, null)), canDownload && onDownload && /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: (locale === null || locale === void 0 ? void 0 : locale['workspace.file.download']) || '下载',
        onClick: handleDownload,
        tooltipProps: {
            mouseEnterDelay: 0.3
        },
        className: classNames("".concat(prefixCls, "-item-action-btn"), hashId)
    }, /*#__PURE__*/ React.createElement(DownloadIcon, null)))), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(prefixCls, "-content"), hashId)
    }, renderPreviewContent())));
};
