// 乐彩百家乐事件监听模块，负责广播事件转发和页面恢复当前局。

/**
 * 读取百家乐面板 Alpine 状态。
 *
 * @returns {Record<string, any>|null}
 */
function getBaccaratPanelState() {
    const panel = document.getElementById("baccarat-panel");

    if (!panel || typeof window.Alpine?.$data !== "function") {
        return null;
    }

    return window.Alpine.$data(panel);
}

/**
 * 同步下注池人数统计，避免不同局的数据互相污染。
 *
 * @param {Record<string, any>} data 下注池广播数据
 * @returns {void}
 */
function updateBaccaratPool(data) {
    const panelState = getBaccaratPanelState();

    if (!panelState || panelState.roundId !== data.round_id) {
        return;
    }

    panelState.betCountBig = data.bet_count_big;
    panelState.betCountSmall = data.bet_count_small;
    panelState.betCountTriple = data.bet_count_triple;
}

/**
 * 从当前局接口恢复下注面板状态。
 *
 * @param {Record<string, any>} panelState 面板 Alpine 状态
 * @param {Record<string, any>} round 当前局数据
 * @returns {void}
 */
function restoreCurrentBaccaratRound(panelState, round) {
    const seconds = Number(round.seconds_left || 0);

    if (seconds <= 0) {
        panelState.setIdleState();
        return;
    }

    panelState.phase = "betting";
    panelState.roundId = round.id;
    panelState.totalSeconds = 60;
    panelState.countdown = seconds;
    panelState.totalBetBig = round.total_bet_big;
    panelState.totalBetSmall = round.total_bet_small;
    panelState.totalBetTriple = round.total_bet_triple;
    panelState.betCountBig = round.bet_count_big;
    panelState.betCountSmall = round.bet_count_small;
    panelState.betCountTriple = round.bet_count_triple;

    if (round.my_bet) {
        panelState.myBet = true;
        panelState.myBetType = round.my_bet.bet_type;
        panelState.myBetAmount = round.my_bet.amount;
    }

    // 只显示悬浮按钮，不自动弹出全屏，避免打扰刚进入的用户。
    panelState.updateFab(true);
}

/**
 * 页面加载后恢复历史趋势、金币和当前局。
 *
 * @returns {Promise<void>}
 */
async function restoreBaccaratOnReady() {
    try {
        const panelState = getBaccaratPanelState();

        if (!panelState) {
            return;
        }

        const historyResponse = await fetch("/baccarat/history");
        const historyData = await historyResponse.json();
        panelState.history = (historyData.history || []).reverse();

        const currentResponse = await fetch("/baccarat/current");
        const currentData = await currentResponse.json();
        panelState.syncUserGold(currentData.jjb);

        if (currentData.round) {
            restoreCurrentBaccaratRound(panelState, currentData.round);
            return;
        }

        panelState.setIdleState();
    } catch (error) {
        console.warn("[百家乐] 初始化失败", error);
    }
}

/**
 * 绑定百家乐广播事件和页面恢复逻辑。
 *
 * @returns {void}
 */
export function bindBaccaratEvents() {
    if (typeof window === "undefined" || typeof document === "undefined" || window.__baccaratEventsBound) {
        return;
    }

    window.__baccaratEventsBound = true;

    window.addEventListener("chat:baccarat.opened", (event) => {
        getBaccaratPanelState()?.openRound(event.detail);
    });

    window.addEventListener("chat:baccarat.settled", (event) => {
        getBaccaratPanelState()?.showResult(event.detail);
    });

    window.addEventListener("chat:baccarat.pool_updated", (event) => {
        updateBaccaratPool(event.detail || {});
    });

    document.addEventListener("DOMContentLoaded", () => window.deferChatGameBootstrap?.(restoreBaccaratOnReady));
}
