(() => {
    // 重试次数
    const maximumRetryCount = 10000;

    // 重试间隔
    const retryIntervalMilliseconds = 1000;

    // 创建断开连接的提示遮罩
    const showDisconnectOverlay = () => {
        if (document.getElementById('reconnect-overlay')) return;
        const overlay = document.createElement('div');
        overlay.id = 'reconnect-overlay';
        overlay.style.cssText = 'position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.7);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px)';
        overlay.innerHTML = `
            <div style="width:48px;height:48px;border:3px solid rgba(255,255,255,0.2);border-top-color:#fff;border-radius:50%;animation:spin 1s linear infinite"></div>
            <span style="color:#fff;font-size:16px;font-weight:bold;letter-spacing:2px">连接已断开</span>
            <span style="color:rgba(255,255,255,0.7);font-size:12px">正在尝试重新连接，请稍候...</span>
            <style>@keyframes spin{to{transform:rotate(360deg)}}</style>
        `;
        document.body.appendChild(overlay);
    };

    const hideDisconnectOverlay = () => {
        const overlay = document.getElementById('reconnect-overlay');
        if (overlay) overlay.remove();
    };

    const startReconnectionProcess = () => {

        let isCanceled = false;

        (async () => {
            for (let i = 0; i < maximumRetryCount; i++) {
                console.log(`试图重新连接: ${i + 1} of ${maximumRetryCount}`)
                await new Promise(resolve => setTimeout(resolve, retryIntervalMilliseconds));

                if (isCanceled) {
                    return;
                }

                try {
                    const result = await Blazor.reconnect();
                    if (!result) {
                        // 已到达服务器，但连接被拒绝;重新加载页面。
                        location.reload();
                        return;
                    }

                    // 成功重新连接到服务器。
                    return;
                } catch {
                    //没有到达服务器;再试一次。
                }
            }

            // 重试次数太多;重新加载页面。
            location.reload();
        })();

        return {
            cancel: () => {
                isCanceled = true;
            },
        };
    };

    let currentReconnectionProcess = null;

    Blazor.start({
        circuit: {
            configureSignalR: function (builder) {
                builder.withServerTimeout(30000);
                builder.withKeepAliveInterval(15000);
            },
            reconnectionHandler: {
                onConnectionDown: () => {
                    showDisconnectOverlay();
                    currentReconnectionProcess ??= startReconnectionProcess();
                },
                onConnectionUp: () => {
                    hideDisconnectOverlay();
                    currentReconnectionProcess?.cancel();
                    currentReconnectionProcess = null;
                },
            },
        },
    });
})();
