// 聊天室页面初始状态恢复，负责首屏历史消息、入场特效和挂起婚姻事件。

/**
 * DOM 就绪后执行回调。
 *
 * @param {Function} callback
 * @returns {void}
 */
function onDomReady(callback) {
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", callback, { once: true });
        return;
    }

    callback();
}

/**
 * 追加一条聊天消息，等待核心聊天脚本暴露 appendMessage。
 *
 * @param {object} message
 * @returns {void}
 */
function appendInitialMessage(message) {
    if (typeof window.appendMessage === "function") {
        window.appendMessage(message);
    }
}

/**
 * 恢复页面初始历史消息。
 *
 * @param {object} initialState
 * @returns {void}
 */
function restoreHistoryMessages(initialState) {
    const messages = Array.isArray(initialState.historyMessages) ? initialState.historyMessages : [];
    if (messages.length === 0) {
        return;
    }

    const clearId = Number.parseInt(localStorage.getItem(initialState.localClearStorageKey || "") || "0", 10);

    messages.forEach((message) => {
        // 本地清屏后，只恢复清屏点之后的新消息。
        if (Number(message.id || 0) > clearId) {
            appendInitialMessage(message);
        }
    });
}

/**
 * 追加页面入场欢迎消息。
 *
 * @param {object} initialState
 * @returns {void}
 */
function appendWelcomeMessage(initialState) {
    const messages = Array.isArray(initialState.welcomeMessages) && initialState.welcomeMessages.length > 0
        ? initialState.welcomeMessages
        : (initialState.welcomeMessage ? [initialState.welcomeMessage] : []);
    if (messages.length === 0) {
        return;
    }

    window.setTimeout(() => {
        // 本次进房欢迎绕过历史清屏过滤，确保新人礼包和 AI 欢迎能在当前屏看到。
        messages.forEach((message) => appendInitialMessage(message));
    }, 220);
}

/**
 * 播放页面入场特效。
 *
 * @param {object} initialState
 * @returns {void}
 */
function playEntryEffect(initialState) {
    if (!initialState.entryEffect) {
        return;
    }

    window.setTimeout(() => {
        window.EffectManager?.play?.(initialState.entryEffect);
    }, 1000);
}

/**
 * 显示会员进出场横幅。
 *
 * @param {object} initialState
 * @returns {void}
 */
function showInitialPresenceBanner(initialState) {
    if (!initialState.presenceTheme) {
        return;
    }

    window.setTimeout(() => {
        window.showVipPresenceBanner?.(initialState.presenceTheme);
    }, 700);
}

/**
 * 派发挂起的求婚或离婚请求事件。
 *
 * @param {object} initialState
 * @returns {void}
 */
function dispatchPendingMarriageEvents(initialState) {
    if (!initialState.pendingProposal && !initialState.pendingDivorce) {
        return;
    }

    window.setTimeout(() => {
        if (initialState.pendingProposal) {
            window.dispatchEvent(new CustomEvent("chat:marriage-proposed", {
                detail: initialState.pendingProposal,
            }));
        }

        if (initialState.pendingDivorce) {
            window.dispatchEvent(new CustomEvent("chat:divorce-requested", {
                detail: initialState.pendingDivorce,
            }));
        }
    }, 800);
}

/**
 * 绑定聊天室页面初始状态恢复。
 *
 * @returns {void}
 */
export function bindChatInitialStateControls() {
    if (typeof window === "undefined") {
        return;
    }

    onDomReady(() => {
        const initialState = window.chatContext?.initialState || {};

        restoreHistoryMessages(initialState);
        appendWelcomeMessage(initialState);
        playEntryEffect(initialState);
        showInitialPresenceBanner(initialState);
        dispatchPendingMarriageEvents(initialState);
    });
}
