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 _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 _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 { useEffect, useState } from "react";
import { fileTypeProcessor } from "../FileTypeProcessor";
import { buildMarkdownContent } from "./utils";
var INITIAL_STATE = {
    status: 'idle',
    mdContent: '',
    rawContent: ''
};
/**
 * 预览内容加载 hook
 *
 * 串联以下副作用，集中管理生命周期：
 * 1. `file` 变化时跑 `fileTypeProcessor.processFile` 得到类型 + 数据源
 * 2. 仅文本/代码类需要拉取原文，按 dataSource 优先 content -> previewUrl 加载
 * 3. 卸载或文件变化时回收 Blob URL（`cleanupResult`）
 *
 * 当 `customContent` 存在时短路所有逻辑，由调用方直接渲染外部内容。
 */ export var usePreviewContent = function usePreviewContent(file, customContent, locale) {
    var _useState = _sliced_to_array(useState(null), 2), processResult = _useState[0], setProcessResult = _useState[1];
    var _useState1 = _sliced_to_array(useState(INITIAL_STATE), 2), contentState = _useState1[0], setContentState = _useState1[1];
    // 1) 跑类型 + 数据源处理
    useEffect(function() {
        if (customContent) return;
        try {
            var result = fileTypeProcessor.processFile(file);
            setProcessResult(result);
        } catch (err) {
            setContentState({
                status: 'error',
                error: _instanceof(err, Error) ? err.message : (locale === null || locale === void 0 ? void 0 : locale['workspace.file.processFailed']) || '文件处理失败'
            });
        }
    }, [
        file,
        customContent
    ]);
    // 2) 文本/代码加载（其他类型仅重置状态）
    useEffect(function() {
        if (customContent || !processResult) return;
        var typeInference = processResult.typeInference, dataSource = processResult.dataSource;
        var isTextOrCode = typeInference.category === 'text' || typeInference.category === 'code';
        if (!isTextOrCode) {
            setContentState(INITIAL_STATE);
            return;
        }
        var setReadyContent = function setReadyContent(raw) {
            setContentState({
                status: 'ready',
                mdContent: buildMarkdownContent(raw, typeInference.category, file.name),
                rawContent: raw
            });
        };
        if (dataSource.content) {
            setReadyContent(dataSource.content);
            return;
        }
        if (dataSource.previewUrl) {
            setContentState({
                status: 'loading',
                mdContent: '',
                rawContent: ''
            });
            fetch(dataSource.previewUrl).then(function(response) {
                if (!response.ok) {
                    throw new Error("HTTP ".concat(response.status, ": ").concat(response.statusText));
                }
                return response.text();
            }).then(setReadyContent).catch(function(err) {
                var errorMessage = _instanceof(err, Error) ? err.message : (locale === null || locale === void 0 ? void 0 : locale['common.loadTextFailed']) || '加载文本内容失败';
                setContentState({
                    status: 'error',
                    error: errorMessage
                });
                console.error('加载文本内容失败:', err);
            });
            return;
        }
        // 无数据源时回到 idle，避免显示旧内容
        setContentState(INITIAL_STATE);
    }, [
        processResult,
        file.name,
        customContent,
        locale
    ]);
    // 3) 卸载/重新处理时清理 Blob URL
    useEffect(function() {
        return function() {
            if (processResult) {
                fileTypeProcessor.cleanupResult(processResult);
            }
        };
    }, [
        processResult
    ]);
    return {
        processResult: processResult,
        contentState: contentState
    };
};
