import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useEffect, useState, useRef, memo, useCallback } from "react";
import { Spin, Progress } from "antd";
import { logger } from "../../utils";
import { initialization, initializationErrorState } from "../initialization";
/**
 * 启动页组件
 * 
 * 在启动页中执行初始化，并使用 Ant Design 5 的 Spin 和 Progress 组件展示启动进度
 */ const SplashScreen = /*#__PURE__*/ memo(({ options, onComplete })=>{
    const [progress, setProgress] = useState(0);
    const [currentStep, setCurrentStep] = useState('准备初始化...');
    const [isInitializing, setIsInitializing] = useState(false);
    const [estimatedTime, setEstimatedTime] = useState(null);
    const hasCompletedRef = useRef(false);
    const onCompleteRef = useRef(onComplete);
    const optionsRef = useRef(options);
    const startTimeRef = useRef(Date.now());
    const minDisplayTimeRef = useRef(options.minSplashScreenTime ?? 500); // 最小显示时间，默认 500ms
    const progressUpdateTimerRef = useRef(null);
    const rafRef = useRef(null);
    const lastProgressRef = useRef(0);
    const progressHistoryRef = useRef([]);
    // 保持引用最新
    useEffect(()=>{
        onCompleteRef.current = onComplete;
        optionsRef.current = options;
        minDisplayTimeRef.current = options.minSplashScreenTime ?? 500;
    }, [
        onComplete,
        options
    ]);
    // 自适应防抖进度更新函数（使用 requestAnimationFrame 优化）
    const debouncedProgressUpdate = useCallback((progressValue, step)=>{
        // 取消之前的更新
        if (rafRef.current !== null) {
            cancelAnimationFrame(rafRef.current);
        }
        // 记录进度历史用于时间预估
        const now = Date.now();
        progressHistoryRef.current.push({
            progress: progressValue,
            time: now
        });
        // 只保留最近10个记录
        if (progressHistoryRef.current.length > 10) {
            progressHistoryRef.current.shift();
        }
        // 计算预估时间
        if (progressHistoryRef.current.length >= 2 && progressValue > 0) {
            const history = progressHistoryRef.current;
            const first = history[0];
            const last = history[history.length - 1];
            const progressDelta = last.progress - first.progress;
            const timeDelta = last.time - first.time;
            if (progressDelta > 0 && timeDelta > 0) {
                const progressPerMs = progressDelta / timeDelta;
                const remainingProgress = 100 - progressValue;
                const estimatedMs = remainingProgress / progressPerMs;
                setEstimatedTime(Math.max(0, Math.round(estimatedMs)));
            }
        }
        // 使用 requestAnimationFrame 优化更新
        rafRef.current = requestAnimationFrame(()=>{
            setProgress(progressValue);
            if (step) {
                setCurrentStep(step);
            }
            lastProgressRef.current = progressValue;
            rafRef.current = null;
        });
    }, []);
    useEffect(()=>{
        if (hasCompletedRef.current) return;
        hasCompletedRef.current = true;
        startTimeRef.current = Date.now();
        const performInitialization = async ()=>{
            try {
                setIsInitializing(true);
                setProgress(0);
                setCurrentStep('开始初始化...');
                logger.info('启动页开始执行初始化');
                // 执行初始化，传入防抖的进度回调
                const context = await initialization(optionsRef.current, (progressValue, step)=>{
                    debouncedProgressUpdate(progressValue, step);
                });
                logger.info('启动页初始化完成', context);
                // 动态调整最小显示时间（如果初始化很快，减少最小显示时间）
                const elapsedTime = Date.now() - startTimeRef.current;
                const dynamicMinTime = elapsedTime < 200 ? Math.min(minDisplayTimeRef.current, 300) : minDisplayTimeRef.current;
                const remainingTime = Math.max(0, dynamicMinTime - elapsedTime);
                if (remainingTime > 0) {
                    await new Promise((resolve)=>setTimeout(resolve, remainingTime));
                }
                // 清理防抖定时器
                if (progressUpdateTimerRef.current) {
                    clearTimeout(progressUpdateTimerRef.current);
                    progressUpdateTimerRef.current = null;
                }
                // 确保进度条显示 100%
                setProgress(100);
                setCurrentStep('初始化完成');
                // 初始化完成，调用回调
                onCompleteRef.current(context);
            } catch (error) {
                logger.error('启动页初始化失败:', error);
                // 设置错误状态，让 ErrorBoundary 能够捕获
                initializationErrorState.setError(error);
                setCurrentStep('初始化失败，请刷新页面重试');
                // 即使失败也调用 onComplete，让应用能够处理错误
                onCompleteRef.current({
                    config: {},
                    progress: 0,
                    isReady: false,
                    duration: 0
                });
            } finally{
                setIsInitializing(false);
            }
        };
        performInitialization();
        // 清理函数
        return ()=>{
            if (progressUpdateTimerRef.current) {
                clearTimeout(progressUpdateTimerRef.current);
            }
            if (rafRef.current !== null) {
                cancelAnimationFrame(rafRef.current);
            }
        };
    }, [
        debouncedProgressUpdate
    ]);
    // 如果提供了自定义启动屏组件，使用自定义组件
    const CustomSplashScreen = optionsRef.current.splashScreen;
    if (CustomSplashScreen) {
        const customProps = {
            progress,
            currentStep,
            isInitializing
        };
        return /*#__PURE__*/ _jsx(CustomSplashScreen, {
            ...customProps
        });
    }
    // 默认启动屏 UI
    return /*#__PURE__*/ _jsxs("div", {
        role: "status",
        "aria-live": "polite",
        "aria-label": "应用正在加载",
        style: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100vh',
            width: '100%',
            gap: 24
        },
        children: [
            /*#__PURE__*/ _jsx(Spin, {
                size: "large",
                spinning: isInitializing,
                "aria-label": "加载中"
            }),
            /*#__PURE__*/ _jsx("div", {
                style: {
                    width: '300px'
                },
                children: /*#__PURE__*/ _jsx(Progress, {
                    percent: progress,
                    status: isInitializing ? 'active' : 'success',
                    showInfo: true,
                    "aria-label": `加载进度 ${progress}%`
                })
            }),
            /*#__PURE__*/ _jsxs("div", {
                role: "status",
                "aria-live": "polite",
                style: {
                    fontSize: 14,
                    color: '#666',
                    textAlign: 'center'
                },
                children: [
                    currentStep,
                    estimatedTime !== null && estimatedTime > 0 && /*#__PURE__*/ _jsxs("div", {
                        style: {
                            fontSize: 12,
                            color: '#999',
                            marginTop: 8
                        },
                        children: [
                            "预计还需 ",
                            Math.ceil(estimatedTime / 1000),
                            " 秒"
                        ]
                    })
                ]
            })
        ]
    });
});
SplashScreen.displayName = 'SplashScreen';
export { SplashScreen };

//# sourceMappingURL=SplashScreen.js.map