// 房间后台管理页事件代理，替代 Blade 内联显示/隐藏和删除确认逻辑。

let adminRoomControlsBound = false;

/**
 * 读取新增房间表单容器。
 *
 * @returns {HTMLElement|null}
 */
function getCreateRoomForm() {
    const formPanel = document.getElementById("create-room-form");

    return formPanel instanceof HTMLElement ? formPanel : null;
}

/**
 * 切换新增房间表单显示状态。
 *
 * @returns {void}
 */
function toggleCreateRoomForm() {
    getCreateRoomForm()?.classList.toggle("hidden");
}

/**
 * 关闭新增房间表单。
 *
 * @returns {void}
 */
function closeCreateRoomForm() {
    getCreateRoomForm()?.classList.add("hidden");
}

/**
 * 校验错误回显时自动展开新增房间表单。
 *
 * @returns {void}
 */
function openCreateRoomFormWhenInvalid() {
    const formPanel = getCreateRoomForm();

    if (formPanel?.hasAttribute("data-room-create-open")) {
        formPanel.classList.remove("hidden");
    }
}

/**
 * 绑定房间管理页操作。
 *
 * @returns {void}
 */
export function bindAdminRoomControls() {
    if (adminRoomControlsBound || typeof document === "undefined") {
        return;
    }

    adminRoomControlsBound = true;
    openCreateRoomFormWhenInvalid();

    document.addEventListener("click", (event) => {
        if (!(event.target instanceof Element)) {
            return;
        }

        const toggleButton = event.target.closest("[data-room-create-toggle]");
        if (toggleButton) {
            event.preventDefault();
            toggleCreateRoomForm();
            return;
        }

        const closeButton = event.target.closest("[data-room-create-close]");
        if (closeButton) {
            event.preventDefault();
            closeCreateRoomForm();
        }
    });

    document.addEventListener("submit", (event) => {
        if (!(event.target instanceof HTMLFormElement)) {
            return;
        }

        const confirmMessage = event.target.getAttribute("data-room-delete-confirm");
        if (confirmMessage && !window.confirm(confirmMessage)) {
            event.preventDefault();
        }
    });
}
