// 聊天室用户名快捷操作，提供 switchTarget/openUserCard 全局兼容函数。

/**
 * 将聊天目标切换到指定用户，离线用户会临时补入下拉框。
 *
 * @param {string} username
 * @returns {void}
 */
export function switchTarget(username) {
    const toUserSelect = document.getElementById("to_user");
    if (!toUserSelect) {
        return;
    }

    const options = toUserSelect.options;
    let found = false;

    for (let index = 0; index < options.length; index += 1) {
        if (options[index].value === username) {
            toUserSelect.value = username;
            found = true;
            break;
        }
    }

    // 已离线用户不在下拉列表时，临时加入一次，方便直接发起悄悄话。
    if (!found && username !== "大家") {
        const option = document.createElement("option");
        option.value = username;
        option.textContent = username;
        toUserSelect.appendChild(option);
        toUserSelect.value = username;
    }

    document.getElementById("content")?.focus();
}

/**
 * 打开指定用户的名片弹窗。
 *
 * @param {string} username
 * @returns {void}
 */
export function openUserCard(username) {
    const normalizedUsername = String(username)
        .replace(/^[\u3010\[【\s]+|[\u3011\]】\s]+$/g, "")
        .trim();

    if (!normalizedUsername) {
        return;
    }

    if (!window.Alpine) {
        console.warn("[openUserCard] Alpine.js 尚未初始化，请稍后再试");
        return;
    }

    const container = document.getElementById("user-modal-container");
    if (!container) {
        return;
    }

    window.Alpine.$data(container)?.fetchUser?.(normalizedUsername);
}

/**
 * 暴露用户名快捷操作给存量 Blade 调用点。
 *
 * @returns {void}
 */
export function bindUserTargetActions() {
    if (typeof window === "undefined") {
        return;
    }

    window.switchTarget = switchTarget;
    window.openUserCard = openUserCard;
}
