(() => {
    const form = document.querySelector("[data-contact-form]");
    const message = document.querySelector("[data-form-message]");
    const submitButton = document.querySelector("[data-form-submit]");

    if (!form || !message || !submitButton) return;

    form.addEventListener("submit", async (event) => {
        event.preventDefault();
        if (submitButton.disabled) return;

        submitButton.disabled = true;
        submitButton.textContent = "Sending...";
        message.textContent = "";

        try {
            const formData = new FormData(form);
            const body = new URLSearchParams();
            for (const [key, value] of formData.entries()) {
                if (typeof value === "string") {
                    body.append(key, value);
                }
            }
            const response = await fetch(form.action, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body,
            });

            if (!response.ok) {
                let errorMessage = "Request failed";
                const errorData = await response.json().catch(() => null);
                if (errorData?.error) {
                    errorMessage = errorData.details
                        ? `${errorData.error} (${errorData.details})`
                        : errorData.error;
                } else {
                    const errorText = await response.text().catch(() => "");
                    if (errorText.trim()) {
                        errorMessage = `${response.status} ${response.statusText}: ${errorText}`;
                    } else {
                        errorMessage = `${response.status} ${response.statusText}`;
                    }
                }
                throw new Error(errorMessage);
            }

            message.textContent = "Thanks! Your message has been sent.";
            form.reset();
            if (
                window.turnstile &&
                typeof window.turnstile.reset === "function"
            ) {
                window.turnstile.reset();
            }
        } catch (error) {
            message.textContent =
                error instanceof Error
                    ? error.message
                    : "Sorry, something went wrong. Please try again.";
        } finally {
            submitButton.disabled = false;
            submitButton.textContent = "Send message";
        }
    });
})();
