/**
 * Per-page bootstrapping shared by both edition entrypoints: find every form
 * wrapper, build the shared config, and create one client per form with the
 * edition's enhancers installed.
 */
import { ScriptLoader } from "./script-loader.js";
import { CountryStateHandler } from "./country-state-handler.js";
import { createFormClient } from "./form-client.js";
import { I18N } from "./i18n.js";

export function bootForms(enhancers = []) {
    const wrappers = document.querySelectorAll(".formatrica");
    if (!wrappers.length) {
        return;
    }

    const settings = window.formatricaFrontend || {};
    const restApiRoot =
        window.wpApiSettings?.root || `${window.location.origin}/wp-json/`;
    const restUrl =
        settings.restUrl ||
        `${restApiRoot.replace(/\/$/, "")}/formatrica/v1`;

    const config = {
        restUrl,
        successMessage: settings.successMessage || I18N.thanks || "Thanks!",
        errorMessage:
            settings.errorMessage || I18N.submitFailed || "Submission failed. Please try again.",
        captchaFailedMessage:
            settings.captchaFailedMessage ||
            I18N.securityFailed || "Security verification failed. Please try again.",
        captchaIncompleteMessage:
            settings.captchaIncompleteMessage ||
            I18N.completeVerification || "Please complete the verification.",
        scriptLoader: new ScriptLoader(),
    };

    // Initialize country/state handler once for all forms
    new CountryStateHandler(restUrl);

    wrappers.forEach((wrapper) => {
        if (wrapper.dataset.fmtBooted === "1") {
            return;
        }

        const formElement = wrapper.querySelector(".formatrica__form");
        const formId = Number(wrapper.dataset.formId || 0);

        if (!formElement || !restUrl || !formId) {
            return;
        }

        wrapper.dataset.fmtBooted = "1";

        createFormClient(wrapper, config, enhancers);
    });
}
