/**
 * 表单提交防重复:网络慢时禁用按钮并显示「提交中」.
 */
(function (global) {
    "use strict";

    function submitButtons(form) {
        if (!form) return [];
        return Array.prototype.slice.call(
            form.querySelectorAll('button[type="submit"], input[type="submit"]')
        );
    }

    function lockForm(form, label) {
        if (!form) return false;
        if (form.dataset.submitGuard === "locked") return false;
        form.dataset.submitGuard = "locked";
        form.classList.add("is-form-submitting");
        submitButtons(form).forEach(function (btn) {
            if (btn.dataset.submitGuardOrig === undefined) {
                btn.dataset.submitGuardOrig =
                    btn.tagName === "BUTTON" ? btn.textContent : btn.value;
            }
            btn.disabled = true;
            if (label) {
                if (btn.tagName === "BUTTON") btn.textContent = label;
                else btn.value = label;
            }
        });
        return true;
    }

    function unlockForm(form) {
        if (!form) return;
        delete form.dataset.submitGuard;
        form.classList.remove("is-form-submitting");
        submitButtons(form).forEach(function (btn) {
            btn.disabled = false;
            var orig = btn.dataset.submitGuardOrig;
            if (orig !== undefined) {
                if (btn.tagName === "BUTTON") btn.textContent = orig;
                else btn.value = orig;
                delete btn.dataset.submitGuardOrig;
            }
        });
    }

    function isLocked(form) {
        return !!(form && form.dataset.submitGuard === "locked");
    }

    /** 已锁定时仅更新按钮文案(校验通过 → 真正提交前) */
    function setSubmitLabel(form, label) {
        if (!form || !label) return;
        submitButtons(form).forEach(function (btn) {
            if (btn.tagName === "BUTTON") btn.textContent = label;
            else btn.value = label;
        });
    }

    /** 已通过前端校验,发起最终 POST(页面将跳转) */
    function nativeSubmitOnce(form, label) {
        if (!form) return;
        var text = label || "提交中…";
        if (form.dataset.submitGuard === "locked") {
            setSubmitLabel(form, text);
        } else {
            lockForm(form, text);
        }
        form.submit();
    }

    global.FormSubmitGuard = {
        lock: lockForm,
        unlock: unlockForm,
        isLocked: isLocked,
        setSubmitLabel: setSubmitLabel,
        nativeSubmitOnce: nativeSubmitOnce,
    };
})(typeof window !== "undefined" ? window : this);
