(function () {
    "use strict";

    if (!window.h4bsFormsData || !window.h4bsFormsData.ajaxUrl) {
        return;
    }

    function setBusy(form, submit, busy) {
        form.setAttribute("aria-busy", busy ? "true" : "false");
        if (!submit) {
            return;
        }
        submit.disabled = busy;
        submit.setAttribute("aria-disabled", busy ? "true" : "false");
        submit.classList.toggle("is-loading", busy);
    }

    function setMessage(message, text, type, shouldFocus) {
        if (!message) {
            return;
        }
        message.textContent = String(text || "");
        message.classList.toggle("is-success", type === "success");
        message.classList.toggle("is-error", type === "error");
        message.setAttribute("role", type === "error" ? "alert" : "status");
        message.setAttribute("aria-live", type === "error" ? "assertive" : "polite");
        if (shouldFocus && typeof message.focus === "function") {
            message.focus();
        }
    }

    function resetCaptcha(form) {
        if (String(form.getAttribute("data-h4bs-captcha") || "disabled") !== "turnstile") {
            return;
        }
        var widget = form.querySelector(".cf-turnstile");
        if (!widget || !window.turnstile || typeof window.turnstile.reset !== "function") {
            return;
        }
        try {
            window.turnstile.reset(widget);
        } catch (error) {
            // A failed vendor reset must not prevent the accessible error state.
        }
    }

    function refreshSentAt(form) {
        var sentAt = form.querySelector("input[name='h4bs_sent_at']");
        if (sentAt) {
            sentAt.value = String(Math.floor(Date.now() / 1000));
        }
    }

    document.addEventListener("submit", function (event) {
        var form = event.target;
        if (!form || !form.matches || !form.matches("form[data-h4bs-form='1']")) {
            return;
        }

        var ajaxEnabled = String(form.getAttribute("data-h4bs-form-ajax") || "1") !== "0";
        if (!ajaxEnabled) {
            return;
        }

        event.preventDefault();
        var submit = form.querySelector("button[type='submit']");
        var message = form.querySelector("[data-h4bs-form-message]");
        var data = new FormData(form);
        data.set("action", "h4bs_form_submit");
        data.set("security", String(window.h4bsFormsData.nonce || ""));

        setBusy(form, submit, true);
        setMessage(message, "Submitting...", "status", false);

        fetch(String(window.h4bsFormsData.ajaxUrl), {
            method: "POST",
            credentials: "same-origin",
            body: data,
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (json) {
                if (!json || !json.success) {
                    var errorMessage =
                        (json && json.data && json.data.message) ||
                        "Unable to submit. Please try again.";
                    throw new Error(String(errorMessage));
                }

                var successMessage =
                    (json.data && json.data.message) ||
                    "Thanks! We received your request.";
                if (message) {
                    setMessage(message, successMessage, "success", true);
                }
                form.reset();
                refreshSentAt(form);
                resetCaptcha(form);
            })
            .catch(function (error) {
                resetCaptcha(form);
                setMessage(
                    message,
                    String((error && error.message) || "Submission failed."),
                    "error",
                    true
                );
            })
            .finally(function () {
                setBusy(form, submit, false);
            });
    });
})();
