<template>
    <div
        class="fmt-modal"
        :class="{ 'fmt-modal--visible': visible }"
        role="dialog"
        aria-modal="true"
    >
        <div class="fmt-modal__overlay" @click="emit('close')"></div>
        <div class="fmt-modal__content">
            <header class="fmt-modal__header">
                <h2>{{ __("Form settings", "formatrica") }}</h2>
                <div class="fmt-settings-mode-toggle">
                    <button
                        type="button"
                        class="button button-small"
                        :class="{ 'is-primary': settingsMode === 'simple' }"
                        @click="settingsMode = 'simple'"
                    >
                        {{ __("Essential", "formatrica") }}
                    </button>
                    <button
                        type="button"
                        class="button button-small"
                        :class="{ 'is-primary': settingsMode === 'advanced' }"
                        @click="settingsMode = 'advanced'"
                    >
                        {{ __("All Options", "formatrica") }}
                    </button>
                </div>
                <button
                    type="button"
                    class="fmt-close-btn fmt-modal-close"
                    @click="emit('close')"
                    :aria-label="__('Close', 'formatrica')"
                >
                    <img :src="ICON_CLOSE" alt="" aria-hidden="true" />
                </button>
            </header>
            <section class="fmt-modal__body">
                <nav class="fmt-modal__tabs" role="tablist">
                    <button
                        v-for="tab in visibleTabs"
                        :key="tab.id"
                        type="button"
                        class="fmt-tab"
                        role="tab"
                        :id="`fmt-tab-${tab.id}`"
                        :class="{ 'fmt-tab--active': activeTab === tab.id }"
                        :aria-selected="activeTab === tab.id"
                        :aria-controls="`fmt-panel-${tab.id}`"
                        @click="activeTab = tab.id"
                    >
                        {{ tab.label }}
                    </button>
                </nav>
                <div class="fmt-modal__panels">
                    <GeneralSettingsTab v-show="activeTab === 'general'" />
                    <AppearanceSettingsTab v-show="activeTab === 'appearance'" />
                    <NotificationSettingsTab v-show="activeTab === 'notifications'" />
                    <PaymentsSettingsTab v-if="PaymentsSettingsTab" v-show="activeTab === 'payments'" />
                    <SaveResumeSettingsTab v-if="SaveResumeSettingsTab" v-show="activeTab === 'save_resume'" />
                    <WpIntegrationsSettingsTab v-show="activeTab === 'wp'" />
                    <IntegrationsSettingsTab v-show="activeTab === 'integrations'" />
                    <SecuritySettingsTab v-show="activeTab === 'security'" />
                    <PrivacySettingsTab v-show="activeTab === 'privacy'" />
                    <AdvancedSettingsTab v-show="activeTab === 'advanced'" />
                </div>
            </section>
            <footer class="fmt-modal__footer">
                <button
                    type="button"
                    class="button button-secondary"
                    @click="emit('close')"
                >
                    {{ __("Cancel", "formatrica") }}
                </button>
                <button
                    type="button"
                    class="button button-primary"
                    @click="save"
                >
                    {{ __("Save settings", "formatrica") }}
                </button>
            </footer>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, watch, computed, provide } from "vue";
import { __ } from "@/utils/i18n";
import { useFormStore } from "@/admin/stores/formStore";
import { createFormDefaults } from "@/admin/utils/formDefaults";
import { safeTrim, isObject, createRowId } from "@/admin/utils/strings";
import { useFormSettings } from "@/admin/composables/useFormSettings";
import { normalizeTheme } from "@/admin/utils/themeAppearance";
import GeneralSettingsTab from "./settings/GeneralSettingsTab.vue";
import AppearanceSettingsTab from "./settings/AppearanceSettingsTab.vue";
import NotificationSettingsTab from "./settings/NotificationSettingsTab.vue";
import WpIntegrationsSettingsTab from "./settings/WpIntegrationsSettingsTab.vue";
import IntegrationsSettingsTab from "./settings/IntegrationsSettingsTab.vue";
import SecuritySettingsTab from "./settings/SecuritySettingsTab.vue";
import PrivacySettingsTab from "./settings/PrivacySettingsTab.vue";
import AdvancedSettingsTab from "./settings/AdvancedSettingsTab.vue";
import { proUi as proUiSlot } from "@/admin/pro-ui-registry";
import ICON_CLOSE from "../../../assets/icons/hexagon-letter-x.svg";

// Pro tab components come from the Pro UI slot registry (Phase 7.2): filled
// by the Pro entrypoint, null in Free — the code never enters the Free bundle.
// The tab-list entries below still use the __FMT_PRO_UI__ literal so their
// labels fold out of the free bundle at build time.
const PaymentsSettingsTab = proUiSlot("paymentsSettingsTab");
const SaveResumeSettingsTab = proUiSlot("saveResumeSettingsTab");
const tabs = [
    { id: "general", label: __("General", "formatrica") },
    { id: "appearance", label: __("Appearance", "formatrica") },
    { id: "notifications", label: __("Email", "formatrica") },
    ...(__FMT_PRO_UI__ ? [
        { id: "payments", label: __("Payments", "formatrica") },
        { id: "save_resume", label: __("Save & Resume", "formatrica") },
    ] : []),
    { id: "wp", label: __("WP", "formatrica") },
    { id: "integrations", label: __("Integrations", "formatrica") },
    { id: "security", label: __("Security", "formatrica") },
    { id: "privacy", label: __("Privacy", "formatrica") },
    { id: "advanced", label: __("Advanced", "formatrica") },
];

const SIMPLE_MODE_TABS = ["general", "notifications"];
const SETTINGS_MODE_KEY = "fmt_hporm_settings_mode";

const getStoredSettingsMode = () => {
    try {
        const stored = localStorage.getItem(SETTINGS_MODE_KEY);
        return stored === "advanced" ? "advanced" : "simple";
    } catch {
        return "simple";
    }
};

const settingsMode = ref(getStoredSettingsMode());

const visibleTabs = computed(() => {
    if (settingsMode.value === "simple") {
        return tabs.filter((tab) => SIMPLE_MODE_TABS.includes(tab.id));
    }
    return tabs;
});

const activeTab = ref(tabs[0].id);

const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    options: {
        type: Object,
        required: true,
    },
    fields: {
        type: Array,
        default: () => [],
    },
});

const emit = defineEmits(["update", "close", "test-email"]);

const store = useFormStore();
const builderSettings = window.formatrica?.builder || {};

const local = reactive(createFormDefaults());
const CAPTCHA_SECRET_PLACEHOLDER = '__PF_CAPTCHA_MASK__';

const {
    mailchimpAudiences,
    mailchimpAudiencesLoading,
    mailchimpAudiencesError,
    fetchMailchimpAudiences: fetchMailchimpAudiencesBase,
    resetMailchimpAudiences,
    brevoLists,
    brevoListsLoading,
    brevoListsError,
    fetchBrevoLists: fetchBrevoListsBase,
    resetBrevoLists,
} = useFormSettings();

const slackTemplatePlaceholder = __(
    "New submission on {{form_title}}\nEmail: {{field:email}}",
    "formatrica"
);
const slackTemplateHint = __(
    "Use placeholders such as {{form_title}} or {{field:email}}. Leave blank to send the default summary.",
    "formatrica"
);
const fieldOptions = computed(() =>
    (props.fields || [])
        .filter((field) => field && field.name)
        .map((field) => ({
            value: field.name,
            label: field.label || field.name,
            type: field.type || "text",
        }))
);

const fileFieldOptions = computed(() =>
    (props.fields || [])
        .filter((field) => field && field.type === "file")
        .map((field) => ({
            value: field.name,
            label: field.label || field.name,
        }))
);

const emailFieldOptions = computed(() =>
    fieldOptions.value.filter((option) => option.type === "email")
);

const mappableFieldOptions = computed(() => fieldOptions.value);

const captchaSecretStored = ref(false);

const setCaptchaSecretStored = (stored) => {
    captchaSecretStored.value = stored;
    if (builderSettings?.meta) {
        builderSettings.meta.captchaSecretSet = stored;
    }
};

const hasStoredCaptchaSecret = computed(() => captchaSecretStored.value);

const addSalesforceMapping = () => {
    local.integrations.salesforce.mappings.push({
        id: createRowId(),
        salesforce_field: "",
        form_field: "",
    });
};

const removeSalesforceMapping = (id) => {
    const index = local.integrations.salesforce.mappings.findIndex(
        (mapping) => mapping.id === id
    );
    if (index !== -1) {
        local.integrations.salesforce.mappings.splice(index, 1);
    }
};

const addHubspotMapping = () => {
    local.integrations.hubspot.field_mappings.push({
        id: createRowId(),
        hubspot_field: "",
        form_field: "",
    });
};

const removeHubspotMapping = (id) => {
    const index = local.integrations.hubspot.field_mappings.findIndex(
        (mapping) => mapping.id === id
    );
    if (index !== -1) {
        local.integrations.hubspot.field_mappings.splice(index, 1);
    }
};

const mapOptionsToLocal = (value) => {
    if (!value) {
        return;
    }

    resetMailchimpAudiences();
    resetBrevoLists();

    local.store_submissions = value.store_submissions !== false;
    local.send_email = value.send_email !== false;
    // Global usage flags (default to true). Map legacy use_global_sender if present.
    const legacySender = value.use_global_sender;
    local.use_global_email_delivery = value.use_global_email_delivery !== false;
    local.use_global_recipient = value.use_global_recipient === false ? false : true;
    if (typeof value.use_global_from_name === 'boolean') {
        local.use_global_from_name = value.use_global_from_name;
    } else if (typeof legacySender === 'boolean') {
        local.use_global_from_name = legacySender;
    } else {
        local.use_global_from_name = true;
    }
    if (typeof value.use_global_from_email === 'boolean') {
        local.use_global_from_email = value.use_global_from_email;
    } else if (typeof legacySender === 'boolean') {
        local.use_global_from_email = legacySender;
    } else {
        local.use_global_from_email = true;
    }
    local.email_recipient = value.email_recipient || "";
    local.email_subject = value.email_subject || "";
    local.email_from_name = value.email_from_name || "";
    local.email_from_address = value.email_from_address || "";
    local.honeypot = value.honeypot !== false;
    local.success_message =
        value.success_message || local.success_message;
    local.error_message = value.error_message || local.error_message;
    local.ip_storage = value.ip_storage || "anonymous";
    local.delete_submissions_after_days_enabled =
        value.delete_submissions_after_days_enabled === true;
    local.delete_submissions_after_days =
        Number(value.delete_submissions_after_days ?? 90) || 90;

    local.throttle = {
        max_requests: Number(value.throttle?.max_requests ?? 3) || 1,
        per_seconds: Number(value.throttle?.per_seconds ?? 10) || 1,
    };

    const storedCaptcha =
        !!value.captcha?.secret_key_set ||
        builderSettings?.meta?.captchaSecretSet === true;

    local.captcha = {
        provider: value.captcha?.provider || "none",
        site_key: value.captcha?.site_key || "",
        secret_key: storedCaptcha ? CAPTCHA_SECRET_PLACEHOLDER : "",
        secret_key_set: storedCaptcha,
        remove_secret_key: false,
    };
    setCaptchaSecretStored(storedCaptcha);

    local.email_delivery.provider =
        value.email_delivery?.provider || "wordpress";
    // Provider API keys are write-only: the GET carries only a *_set flag
    // (never the key), and the tab shows a stored-key placeholder from it.
    // Dropping the flags here made every stored key look unset after reload.
    local.email_delivery.sendgrid.api_key =
        value.email_delivery?.sendgrid?.api_key || "";
    local.email_delivery.sendgrid.api_key_set =
        value.email_delivery?.sendgrid?.api_key_set === true;
    // New providers
    local.email_delivery.mailgun = {
        api_key: value.email_delivery?.mailgun?.api_key || "",
        api_key_set: value.email_delivery?.mailgun?.api_key_set === true,
        domain: value.email_delivery?.mailgun?.domain || "",
        region: value.email_delivery?.mailgun?.region || "us",
    };
    local.email_delivery.postmark = {
        api_token: value.email_delivery?.postmark?.api_token || "",
        api_token_set: value.email_delivery?.postmark?.api_token_set === true,
    };
    local.email_delivery.brevo = {
        api_key: value.email_delivery?.brevo?.api_key || "",
        api_key_set: value.email_delivery?.brevo?.api_key_set === true,
    };
    local.email_delivery.amazon_ses = {
        access_key: value.email_delivery?.amazon_ses?.access_key || "",
        secret_key: value.email_delivery?.amazon_ses?.secret_key || "",
        secret_key_set: value.email_delivery?.amazon_ses?.secret_key_set === true,
        region: value.email_delivery?.amazon_ses?.region || "us-east-1",
    };
    local.email_delivery.mailpit.host =
        value.email_delivery?.mailpit?.host || "127.0.0.1";
    local.email_delivery.mailpit.port =
        Number(value.email_delivery?.mailpit?.port ?? 1025) || 1025;
    local.email_delivery.smtp2go.api_key =
        value.email_delivery?.smtp2go?.api_key || "";
    local.email_delivery.smtp2go.api_key_set =
        value.email_delivery?.smtp2go?.api_key_set === true;
    local.email_delivery.smtp.host = value.email_delivery?.smtp?.host || "";
    local.email_delivery.smtp.port =
        Number(value.email_delivery?.smtp?.port ?? 587) || 587;
    local.email_delivery.smtp.encryption =
        value.email_delivery?.smtp?.encryption || "tls";
    local.email_delivery.smtp.username =
        value.email_delivery?.smtp?.username || "";
    local.email_delivery.smtp.password =
        value.email_delivery?.smtp?.password || "";
    local.email_delivery.smtp.password_set =
        value.email_delivery?.smtp?.password_set === true;

    local.custom_css = value.custom_css || "";

    local.theme = normalizeTheme(value.theme);

    local.layout = {
        mode: ["single", "two_column", "three_column"].includes(value.layout?.mode)
            ? value.layout.mode
            : "single",
    };

    local.submit_action = {
        type: value.submit_action?.type === "url" ? "url" : "same_page",
        url: typeof value.submit_action?.url === "string" ? value.submit_action.url : "",
    };

    local.wrapper_class = typeof value.wrapper_class === "string" ? value.wrapper_class : "";

    // Wave 5 Pro feature blocks (flat objects). Overlay the form's saved values
    // on the defaults so a form saved before these existed still binds cleanly.
    const w5 = createFormDefaults();
    local.drafts = { ...w5.drafts, ...(value.drafts || {}) };
    local.submitter_email = { ...w5.submitter_email, ...(value.submitter_email || {}) };
    local.email_template = { ...w5.email_template, ...(value.email_template || {}) };
    local.payments = { ...w5.payments, ...(value.payments || {}) };

    // Headless API submissions (Pro api.headless). The key input is WRITE-ONLY:
    // never seed it with the stored encrypted blob — an empty field means
    // "keep the stored key" (the server preserves it when nothing is posted).
    local.headless_submission_enabled = value.headless_submission_enabled === true;
    local.headless_api_key = "";
    local.headless_api_key_set = value.headless_api_key_set === true;
    local.headless_allowed_ips = Array.isArray(value.headless_allowed_ips)
        ? value.headless_allowed_ips.filter((ip) => typeof ip === "string")
        : [];

    local.webhooks = {
        enabled: value.webhooks?.enabled === true,
        endpoint: value.webhooks?.endpoint || "",
        secret: "",
        secret_set: value.webhooks?.secret_set === true,
        remove_secret: false,
    };

    const integrations = value.integrations || {};
    const defaults = createFormDefaults().integrations;

    const wpMap = integrations?.wordpress_post?.map || {};
    const wpTaxonomies = Array.isArray(integrations?.wordpress_post?.taxonomies)
        ? integrations.wordpress_post.taxonomies
              .filter(isObject)
              .map((item) => ({
                  id:
                      typeof item?.id === "string" && item.id !== ""
                          ? item.id
                          : createRowId(),
                  taxonomy: safeTrim(item?.taxonomy || ""),
                  field: safeTrim(item?.field || ""),
                  mode: item?.mode === "ids" ? "ids" : "names",
              }))
        : [];
    const wpMeta = Array.isArray(integrations?.wordpress_post?.meta)
        ? integrations.wordpress_post.meta
              .filter(isObject)
              .map((item) => ({
                  id:
                      typeof item?.id === "string" && item.id !== ""
                          ? item.id
                          : createRowId(),
                  key: safeTrim(item?.key || ""),
                  field: safeTrim(item?.field || ""),
              }))
        : [];

    local.integrations.wordpress_post = {
        ...defaults.wordpress_post,
        enabled: integrations?.wordpress_post?.enabled === true,
        post_type: integrations?.wordpress_post?.post_type || "post",
        post_status: integrations?.wordpress_post?.post_status || "pending",
        author_mode: integrations?.wordpress_post?.author_mode || "current_user",
        fixed_author_id:
            Number(integrations?.wordpress_post?.fixed_author_id ?? 0) || 0,
        map: {
            title: wpMap?.title || "",
            content: wpMap?.content || "",
            excerpt: wpMap?.excerpt || "",
            featured_image: wpMap?.featured_image || "",
        },
        taxonomies: wpTaxonomies,
        meta: wpMeta,
    };

    const mailchimpTags = Array.isArray(integrations?.mailchimp?.tags)
        ? integrations.mailchimp.tags
        : [];

    local.integrations.mailchimp = {
        ...defaults.mailchimp,
        enabled: integrations?.mailchimp?.enabled === true,
        api_key: "",
        api_key_set: integrations?.mailchimp?.api_key_set === true,
        remove_api_key: false,
        list_id: integrations?.mailchimp?.list_id || "",
        double_opt_in: integrations?.mailchimp?.double_opt_in === true,
        email_field: integrations?.mailchimp?.email_field || "",
        first_name_field: integrations?.mailchimp?.first_name_field || "",
        last_name_field: integrations?.mailchimp?.last_name_field || "",
        tags_input: mailchimpTags.join(", "),
    };

    const brevoTags = Array.isArray(integrations?.brevo?.tags)
        ? integrations.brevo.tags
        : [];

    local.integrations.brevo = {
        ...defaults.brevo,
        enabled: integrations?.brevo?.enabled === true,
        api_key: "",
        api_key_set: integrations?.brevo?.api_key_set === true,
        remove_api_key: false,
        list_id: integrations?.brevo?.list_id || "",
        email_field: integrations?.brevo?.email_field || "",
        first_name_field: integrations?.brevo?.first_name_field || "",
        last_name_field: integrations?.brevo?.last_name_field || "",
        tags_input: brevoTags.join(", "),
    };

    local.integrations.zapier = {
        ...defaults.zapier,
        enabled: integrations?.zapier?.enabled === true,
        webhook_url: integrations?.zapier?.webhook_url || "",
    };

    local.integrations.make = {
        ...defaults.make,
        enabled: integrations?.make?.enabled === true,
        webhook_url: integrations?.make?.webhook_url || "",
        // Write-only: the encrypted blob never round-trips; empty = keep.
        api_key: "",
        api_key_set: integrations?.make?.api_key_set === true,
        remove_api_key: false,
    };

    local.integrations.twilio = {
        ...defaults.twilio,
        enabled: integrations?.twilio?.enabled === true,
        account_sid: integrations?.twilio?.account_sid || "",
        api_key_sid: integrations?.twilio?.api_key_sid || "",
        // Write-only secret: never seed the stored blob.
        api_key_secret: "",
        api_key_secret_set: integrations?.twilio?.api_key_secret_set === true,
        remove_api_key_secret: false,
        sender_mode: integrations?.twilio?.sender_mode === "messaging_service" ? "messaging_service" : "number",
        from_number: integrations?.twilio?.from_number || "",
        messaging_service_sid: integrations?.twilio?.messaging_service_sid || "",
        recipient_number: integrations?.twilio?.recipient_number || "",
        message_template: integrations?.twilio?.message_template || "",
        region: ["us1", "ie1", "au1"].includes(integrations?.twilio?.region) ? integrations.twilio.region : "us1",
    };

    local.integrations.slack = {
        ...defaults.slack,
        enabled: integrations?.slack?.enabled === true,
        webhook_url: integrations?.slack?.webhook_url || "",
        message_template: integrations?.slack?.message_template || "",
    };

    const salesforceMappings = Array.isArray(integrations?.salesforce?.mappings)
        ? integrations.salesforce.mappings
              .filter(isObject)
              .map((item) => ({
                  id:
                      typeof item?.id === "string" && item.id !== ""
                          ? item.id
                          : createRowId(),
                  salesforce_field: safeTrim(item?.salesforce_field || ""),
                  form_field: safeTrim(item?.form_field || ""),
              }))
        : [];

    local.integrations.salesforce = {
        ...defaults.salesforce,
        enabled: integrations?.salesforce?.enabled === true,
        org_id: integrations?.salesforce?.org_id || "",
        lead_source: integrations?.salesforce?.lead_source || "",
        assignment_rule_id:
            integrations?.salesforce?.assignment_rule_id || "",
        debug_email: integrations?.salesforce?.debug_email || "",
        mappings: salesforceMappings,
    };

const hubspotMappings = Array.isArray(
        integrations?.hubspot?.field_mappings
    )
        ? integrations.hubspot.field_mappings
              .filter(isObject)
              .map((item) => ({
                  id:
                      typeof item?.id === "string" && item.id !== ""
                          ? item.id
                          : createRowId(),
                  hubspot_field: safeTrim(item?.hubspot_field || ""),
                  form_field: safeTrim(item?.form_field || ""),
              }))
        : [];

    local.integrations.hubspot = {
        ...defaults.hubspot,
        enabled: integrations?.hubspot?.enabled === true,
        access_token: "",
        access_token_set: integrations?.hubspot?.access_token_set === true,
        remove_access_token: false,
        portal_id: integrations?.hubspot?.portal_id || "",
        form_guid: integrations?.hubspot?.form_guid || "",
        email_field: integrations?.hubspot?.email_field || "",
        field_mappings: hubspotMappings,
        legal_consent: integrations?.hubspot?.legal_consent === true,
        consent_text: integrations?.hubspot?.consent_text || "",
    };

    const incomingWoo = integrations?.woocommerce || {};
    const wooStaticProducts = Array.isArray(incomingWoo.static_products)
        ? incomingWoo.static_products
              .filter(isObject)
              .map((item) => ({
                  id:
                      typeof item?.id === "string" && item.id !== ""
                          ? item.id
                          : createRowId(),
                  product_id: Number(item?.product_id) || 0,
                  variation_id: Number(item?.variation_id) || 0,
                  quantity: Number(item?.quantity) || 1,
              }))
        : [];

    const wooMetadata = Array.isArray(incomingWoo.metadata)
        ? incomingWoo.metadata
              .filter(isObject)
              .map((item) => ({
                  id:
                      typeof item?.id === "string" && item.id !== ""
                          ? item.id
                          : createRowId(),
                  key: safeTrim(item?.key || ""),
                  field: safeTrim(item?.field || ""),
              }))
        : [];

    const incomingCustomer = isObject(incomingWoo.customer)
        ? incomingWoo.customer
        : {};
    const incomingBilling = isObject(incomingCustomer.billing)
        ? incomingCustomer.billing
        : {};
    const incomingShipping = isObject(incomingCustomer.shipping)
        ? incomingCustomer.shipping
        : {};

    local.integrations.woocommerce = {
        ...defaults.woocommerce,
        enabled: incomingWoo.enabled === true,
        product_mode: incomingWoo.product_mode === "field" ? "field" : "static",
        static_products: wooStaticProducts,
        product_field: incomingWoo.product_field || "",
        quantity_field: incomingWoo.quantity_field || "",
        variation_field: incomingWoo.variation_field || "",
        price_field: incomingWoo.price_field || "",
        order_status: incomingWoo.order_status || "wc-pending",
        create_customer: incomingWoo.create_customer !== false,
        customer: {
            email_field: incomingCustomer.email_field || "",
            first_name_field: incomingCustomer.first_name_field || "",
            last_name_field: incomingCustomer.last_name_field || "",
            phone_field: incomingCustomer.phone_field || "",
            company_field: incomingCustomer.company_field || "",
            billing: {
                line1_field: incomingBilling.line1_field || "",
                line2_field: incomingBilling.line2_field || "",
                city_field: incomingBilling.city_field || "",
                state_field: incomingBilling.state_field || "",
                postcode_field: incomingBilling.postcode_field || "",
                country_field: incomingBilling.country_field || "",
            },
            shipping: {
                use_billing: incomingShipping.use_billing === false ? false : true,
                line1_field: incomingShipping.line1_field || "",
                line2_field: incomingShipping.line2_field || "",
                city_field: incomingShipping.city_field || "",
                state_field: incomingShipping.state_field || "",
                postcode_field: incomingShipping.postcode_field || "",
                country_field: incomingShipping.country_field || "",
            },
        },
        metadata: wooMetadata,
    };
};

watch(
    () => props.options,
    (value) => {
        mapOptionsToLocal(value);
    },
    { immediate: true }
);

watch(
    () => props.visible,
    (visible) => {
        if (!visible) {
            activeTab.value = tabs[0].id;
        }
    }
);

watch(settingsMode, (newMode) => {
    try {
        localStorage.setItem(SETTINGS_MODE_KEY, newMode);
    } catch {
        // localStorage not available
    }
    // Reset to first visible tab when switching modes
    if (visibleTabs.value.length > 0) {
        activeTab.value = visibleTabs.value[0].id;
    }
});

watch(
    emailFieldOptions,
    (options) => {
        if (options.length > 0) {
            if (!local.integrations.mailchimp.email_field) {
                local.integrations.mailchimp.email_field = options[0].value;
            }
            if (!local.integrations.hubspot.email_field) {
                local.integrations.hubspot.email_field = options[0].value;
            }
        }
    },
    { immediate: true }
);

watch(
    () => local.integrations.salesforce.enabled,
    (enabled) => {
        if (enabled && local.integrations.salesforce.mappings.length === 0) {
            addSalesforceMapping();
        }
    }
);

watch(
    () => local.integrations.hubspot.enabled,
    (enabled) => {
        if (enabled && local.integrations.hubspot.field_mappings.length === 0) {
            addHubspotMapping();
        }
    }
);

watch(
    () => local.webhooks.enabled,
    (enabled) => {
        if (!enabled) {
            local.webhooks.remove_secret = false;
            local.webhooks.secret = "";
        }
    }
);

watch(
    () => local.captcha.secret_key,
    (value, previous) => {
        if (value === CAPTCHA_SECRET_PLACEHOLDER) {
            local.captcha.secret_key_set = true;
            local.captcha.remove_secret_key = false;
            setCaptchaSecretStored(true);
            return;
        }

        if (value === "") {
            const hadStored =
                previous === CAPTCHA_SECRET_PLACEHOLDER ||
                captchaSecretStored.value;

            if (hadStored) {
                local.captcha.remove_secret_key = true;
                local.captcha.secret_key_set = false;
                setCaptchaSecretStored(false);
            } else {
                local.captcha.remove_secret_key = false;
            }
            return;
        }

        local.captcha.remove_secret_key = false;
        local.captcha.secret_key_set = true;
        setCaptchaSecretStored(true);
    }
);

watch(
    () => local.captcha.provider,
    (provider) => {
        if (provider === "none") {
            local.captcha.secret_key = "";
            local.captcha.remove_secret_key = false;
            local.captcha.secret_key_set = false;
            setCaptchaSecretStored(false);
        } else if (
            local.captcha.secret_key_set &&
            local.captcha.secret_key === ""
        ) {
            local.captcha.secret_key = CAPTCHA_SECRET_PLACEHOLDER;
        }
    }
);

watch(
    () => local.integrations.wordpress_post.enabled,
    (enabled) => {
        if (enabled) {
            if (!Array.isArray(local.integrations.wordpress_post.taxonomies)) {
                local.integrations.wordpress_post.taxonomies = [];
            }
            if (!Array.isArray(local.integrations.wordpress_post.meta)) {
                local.integrations.wordpress_post.meta = [];
            }
        }
    },
    { immediate: true }
);

watch(
    () => local.integrations.woocommerce.enabled,
    (enabled) => {
        if (enabled) {
            if (!Array.isArray(local.integrations.woocommerce.static_products)) {
                local.integrations.woocommerce.static_products = [];
            }
            if (!Array.isArray(local.integrations.woocommerce.metadata)) {
                local.integrations.woocommerce.metadata = [];
            }
        }
    },
    { immediate: true }
);

const parseMailchimpTags = () =>
    local.integrations.mailchimp.tags_input
        .split(",")
        .map((tag) => safeTrim(tag))
        .filter((tag) => tag.length > 0);

const parseBrevoTags = () =>
    local.integrations.brevo.tags_input
        .split(",")
        .map((tag) => safeTrim(tag))
        .filter((tag) => tag.length > 0);

const fetchMailchimpAudiences = async () => {
    if (!builderSettings.restUrl) {
        return;
    }

    await fetchMailchimpAudiencesBase({
        apiKey: local.integrations.mailchimp.api_key,
        formId: store.formId,
        restUrl: builderSettings.restUrl,
        nonce: builderSettings.nonce,
    });

    // Auto-select first audience if none selected
    if (
        !local.integrations.mailchimp.list_id &&
        mailchimpAudiences.value.length > 0
    ) {
        local.integrations.mailchimp.list_id =
            mailchimpAudiences.value[0].id;
    }
};

const fetchBrevoLists = async () => {
    if (!builderSettings.restUrl) {
        return;
    }

    await fetchBrevoListsBase({
        apiKey: local.integrations.brevo.api_key,
        formId: store.formId,
        restUrl: builderSettings.restUrl,
        nonce: builderSettings.nonce,
    });

    // Auto-select first list if none selected
    if (!local.integrations.brevo.list_id && brevoLists.value.length > 0) {
        local.integrations.brevo.list_id = brevoLists.value[0].id;
    }
};

const buildIntegrationPayload = () => ({
    zapier: {
        enabled: !!local.integrations.zapier.enabled,
        webhook_url: safeTrim(local.integrations.zapier.webhook_url),
    },
    make: {
        enabled: !!local.integrations.make.enabled,
        webhook_url: safeTrim(local.integrations.make.webhook_url),
        // Sent only when the admin typed a new key; empty = keep stored.
        api_key: safeTrim(local.integrations.make.api_key || ""),
        remove_api_key: !!local.integrations.make.remove_api_key,
    },
    twilio: {
        enabled: !!local.integrations.twilio.enabled,
        account_sid: safeTrim(local.integrations.twilio.account_sid),
        api_key_sid: safeTrim(local.integrations.twilio.api_key_sid),
        api_key_secret: safeTrim(local.integrations.twilio.api_key_secret || ""),
        remove_api_key_secret: !!local.integrations.twilio.remove_api_key_secret,
        sender_mode: local.integrations.twilio.sender_mode === "messaging_service" ? "messaging_service" : "number",
        from_number: safeTrim(local.integrations.twilio.from_number),
        messaging_service_sid: safeTrim(local.integrations.twilio.messaging_service_sid),
        recipient_number: safeTrim(local.integrations.twilio.recipient_number),
        message_template: local.integrations.twilio.message_template || "",
        region: local.integrations.twilio.region || "us1",
    },
    slack: {
        enabled: !!local.integrations.slack.enabled,
        webhook_url: safeTrim(local.integrations.slack.webhook_url),
        message_template: local.integrations.slack.message_template,
    },
    wordpress_post: {
        enabled: !!local.integrations.wordpress_post.enabled,
        post_type: safeTrim(local.integrations.wordpress_post.post_type) || "post",
        post_status: safeTrim(local.integrations.wordpress_post.post_status) || "pending",
        author_mode: local.integrations.wordpress_post.author_mode || "current_user",
        fixed_author_id:
            Number(local.integrations.wordpress_post.fixed_author_id) || 0,
        map: {
            title: safeTrim(local.integrations.wordpress_post.map.title),
            content: safeTrim(local.integrations.wordpress_post.map.content),
            excerpt: safeTrim(local.integrations.wordpress_post.map.excerpt),
            featured_image: safeTrim(
                local.integrations.wordpress_post.map.featured_image
            ),
        },
        taxonomies: (local.integrations.wordpress_post.taxonomies || [])
            .filter((item) => item.taxonomy && item.field)
            .map((item) => ({
                taxonomy: safeTrim(item.taxonomy),
                field: safeTrim(item.field),
                mode: item.mode === "ids" ? "ids" : "names",
            })),
        meta: (local.integrations.wordpress_post.meta || [])
            .filter((item) => item.key && item.field)
            .map((item) => ({
                key: safeTrim(item.key),
                field: safeTrim(item.field),
            })),
    },
    mailchimp: {
        enabled: !!local.integrations.mailchimp.enabled,
        api_key: safeTrim(local.integrations.mailchimp.api_key),
        remove_api_key: !!local.integrations.mailchimp.remove_api_key,
        list_id: safeTrim(local.integrations.mailchimp.list_id),
        double_opt_in: !!local.integrations.mailchimp.double_opt_in,
        email_field: safeTrim(local.integrations.mailchimp.email_field),
        first_name_field: safeTrim(
            local.integrations.mailchimp.first_name_field
        ),
        last_name_field: safeTrim(local.integrations.mailchimp.last_name_field),
        tags: parseMailchimpTags(),
    },
    brevo: {
        enabled: !!local.integrations.brevo.enabled,
        api_key: safeTrim(local.integrations.brevo.api_key),
        remove_api_key: !!local.integrations.brevo.remove_api_key,
        list_id: safeTrim(local.integrations.brevo.list_id),
        email_field: safeTrim(local.integrations.brevo.email_field),
        first_name_field: safeTrim(local.integrations.brevo.first_name_field),
        last_name_field: safeTrim(local.integrations.brevo.last_name_field),
        tags: parseBrevoTags(),
    },
    salesforce: {
        enabled: !!local.integrations.salesforce.enabled,
        org_id: safeTrim(local.integrations.salesforce.org_id),
        lead_source: safeTrim(local.integrations.salesforce.lead_source),
        assignment_rule_id: safeTrim(
            local.integrations.salesforce.assignment_rule_id
        ),
        debug_email: safeTrim(local.integrations.salesforce.debug_email),
        mappings: local.integrations.salesforce.mappings
            .map((item) => ({
                salesforce_field: safeTrim(item.salesforce_field),
                form_field: safeTrim(item.form_field),
            }))
            .filter(
                (item) => item.salesforce_field !== "" && item.form_field !== ""
            ),
    },
    hubspot: {
        enabled: !!local.integrations.hubspot.enabled,
        access_token: safeTrim(local.integrations.hubspot.access_token),
        remove_access_token: !!local.integrations.hubspot.remove_access_token,
        portal_id: safeTrim(local.integrations.hubspot.portal_id),
        form_guid: safeTrim(local.integrations.hubspot.form_guid),
        email_field: safeTrim(local.integrations.hubspot.email_field),
        field_mappings: local.integrations.hubspot.field_mappings
            .map((item) => ({
                hubspot_field: safeTrim(item.hubspot_field),
                form_field: safeTrim(item.form_field),
            }))
            .filter(
                (item) => item.hubspot_field !== "" && item.form_field !== ""
            ),
        legal_consent: !!local.integrations.hubspot.legal_consent,
        consent_text: local.integrations.hubspot.consent_text,
    },
    woocommerce: {
        enabled: !!local.integrations.woocommerce.enabled,
        product_mode:
            local.integrations.woocommerce.product_mode === "field"
                ? "field"
                : "static",
        static_products: (local.integrations.woocommerce.static_products || [])
            .map((item) => ({
                product_id: Number(item.product_id) || 0,
                variation_id: Number(item.variation_id) || 0,
                quantity: Number(item.quantity) || 1,
            }))
            .filter((item) => item.product_id > 0),
        product_field: safeTrim(local.integrations.woocommerce.product_field),
        quantity_field: safeTrim(local.integrations.woocommerce.quantity_field),
        variation_field: safeTrim(
            local.integrations.woocommerce.variation_field
        ),
        price_field: safeTrim(local.integrations.woocommerce.price_field),
        order_status:
            safeTrim(local.integrations.woocommerce.order_status) ||
            "wc-pending",
        create_customer: !!local.integrations.woocommerce.create_customer,
        customer: {
            email_field: safeTrim(
                local.integrations.woocommerce.customer.email_field
            ),
            first_name_field: safeTrim(
                local.integrations.woocommerce.customer.first_name_field
            ),
            last_name_field: safeTrim(
                local.integrations.woocommerce.customer.last_name_field
            ),
            phone_field: safeTrim(
                local.integrations.woocommerce.customer.phone_field
            ),
            company_field: safeTrim(
                local.integrations.woocommerce.customer.company_field
            ),
            billing: {
                line1_field: safeTrim(
                    local.integrations.woocommerce.customer.billing.line1_field
                ),
                line2_field: safeTrim(
                    local.integrations.woocommerce.customer.billing.line2_field
                ),
                city_field: safeTrim(
                    local.integrations.woocommerce.customer.billing.city_field
                ),
                state_field: safeTrim(
                    local.integrations.woocommerce.customer.billing.state_field
                ),
                postcode_field: safeTrim(
                    local.integrations.woocommerce.customer.billing
                        .postcode_field
                ),
                country_field: safeTrim(
                    local.integrations.woocommerce.customer.billing.country_field
                ),
            },
            shipping: {
                use_billing:
                    local.integrations.woocommerce.customer.shipping.use_billing !==
                    false,
                line1_field: safeTrim(
                    local.integrations.woocommerce.customer.shipping.line1_field
                ),
                line2_field: safeTrim(
                    local.integrations.woocommerce.customer.shipping.line2_field
                ),
                city_field: safeTrim(
                    local.integrations.woocommerce.customer.shipping.city_field
                ),
                state_field: safeTrim(
                    local.integrations.woocommerce.customer.shipping.state_field
                ),
                postcode_field: safeTrim(
                    local.integrations.woocommerce.customer.shipping
                        .postcode_field
                ),
                country_field: safeTrim(
                    local.integrations.woocommerce.customer.shipping.country_field
                ),
            },
        },
        metadata: (local.integrations.woocommerce.metadata || [])
            .map((item) => ({
                key: safeTrim(item.key),
                field: safeTrim(item.field),
            }))
            .filter((item) => item.key !== "" && item.field !== ""),
    },
});

const buildOptionsPayload = () => {
    const ipMode = safeTrim(local.ip_storage);
    const allowedIpModes = ["full", "anonymous", "none"];


    return {
        store_submissions: !!local.store_submissions,
        send_email: !!local.send_email,
        use_global_email_delivery: local.use_global_email_delivery !== false,
        use_global_recipient: local.use_global_recipient !== false,
        use_global_from_name: local.use_global_from_name !== false,
        use_global_from_email: local.use_global_from_email !== false,
        email_recipient: safeTrim(local.email_recipient),
        email_subject: safeTrim(local.email_subject),
        email_from_name: safeTrim(local.email_from_name),
        email_from_address: safeTrim(local.email_from_address),
        honeypot: !!local.honeypot,
        ip_storage: allowedIpModes.includes(ipMode)
            ? ipMode
            : "anonymous",
        delete_submissions_after_days_enabled:
            !!local.delete_submissions_after_days_enabled,
        delete_submissions_after_days:
            Number(local.delete_submissions_after_days) || 90,
        throttle: {
            max_requests: Number(local.throttle.max_requests) || 1,
            per_seconds: Number(local.throttle.per_seconds) || 1,
        },
        success_message: local.success_message,
        error_message: local.error_message,
        captcha: {
            provider: local.captcha.provider || "none",
            site_key: safeTrim(local.captcha.site_key),
            secret_key:
                local.captcha.secret_key === CAPTCHA_SECRET_PLACEHOLDER
                    ? ""
                    : safeTrim(local.captcha.secret_key),
            remove_secret_key: local.captcha.remove_secret_key === true,
            secret_key_set:
                local.captcha.secret_key === CAPTCHA_SECRET_PLACEHOLDER
                    ? true
                    : local.captcha.secret_key_set === true,
        },
        email_delivery: {
            provider: local.email_delivery.provider || "wordpress",
            sendgrid: {
                api_key: safeTrim(local.email_delivery.sendgrid.api_key),
            },
            mailgun: {
                api_key: safeTrim(local.email_delivery.mailgun?.api_key || ""),
                domain: safeTrim(local.email_delivery.mailgun?.domain || ""),
                region: safeTrim(local.email_delivery.mailgun?.region || "us"),
            },
            postmark: {
                api_token: safeTrim(local.email_delivery.postmark?.api_token || ""),
            },
            brevo: {
                api_key: safeTrim(local.email_delivery.brevo?.api_key || ""),
            },
            amazon_ses: {
                access_key: safeTrim(local.email_delivery.amazon_ses?.access_key || ""),
                secret_key: safeTrim(local.email_delivery.amazon_ses?.secret_key || ""),
                region: safeTrim(local.email_delivery.amazon_ses?.region || "us-east-1"),
            },
            mailpit: {
                host:
                    safeTrim(local.email_delivery.mailpit.host) ||
                    "127.0.0.1",
                port: Number(local.email_delivery.mailpit.port) || 1025,
            },
            smtp2go: {
                api_key: safeTrim(local.email_delivery.smtp2go.api_key),
            },
            smtp: {
                host: safeTrim(local.email_delivery.smtp.host),
                port: Number(local.email_delivery.smtp.port) || 587,
                encryption: local.email_delivery.smtp.encryption || "tls",
                username: safeTrim(local.email_delivery.smtp.username),
                password: local.email_delivery.smtp.password,
            },
        },
        custom_css: local.custom_css || "",
        theme: normalizeTheme(local.theme),
        layout: {
            mode: ["single", "two_column", "three_column"].includes(local.layout?.mode)
                ? local.layout.mode
                : "single",
        },
        submit_action: {
            type: local.submit_action?.type === "url" ? "url" : "same_page",
            url: local.submit_action?.type === "url" ? (local.submit_action?.url || "") : "",
        },
        // Wave 5 Pro feature blocks (server sanitizer + save-guards are the
        // allow-list; gated flags are reverted there on Free).
        drafts: { ...local.drafts },
        submitter_email: { ...local.submitter_email },
        email_template: { ...local.email_template },
        payments: { ...local.payments },
        wrapper_class: local.wrapper_class || "",
        // Headless API (Pro api.headless): the key is write-only — sent only
        // when the admin typed a new one; empty means keep the stored key.
        headless_submission_enabled: local.headless_submission_enabled === true,
        headless_api_key: safeTrim(local.headless_api_key || ""),
        headless_allowed_ips: Array.isArray(local.headless_allowed_ips)
            ? local.headless_allowed_ips
            : [],
        webhooks: {
            enabled: !!local.webhooks.enabled,
            endpoint: safeTrim(local.webhooks.endpoint),
            secret: local.webhooks.secret,
            remove_secret: !!local.webhooks.remove_secret,
        },
        integrations: buildIntegrationPayload(),
    };
};

const save = () => {
    emit("update", buildOptionsPayload());
    emit("close");
};

const requestTestEmail = () => {
    const recipient = safeTrim(local.email_recipient);
    if (!recipient && !local.use_global_recipient) {
        return;
    }
    emit("test-email", {
        recipient,
        options: buildOptionsPayload(),
    });
};

provide("formSettingsContext", {
    local,
    fieldOptions,
    fileFieldOptions,
    emailFieldOptions,
    mappableFieldOptions,
    hasStoredCaptchaSecret,
    setCaptchaSecretStored,
    builderSettings,
    slackTemplatePlaceholder,
    slackTemplateHint,
    mailchimpAudiences,
    mailchimpAudiencesLoading,
    mailchimpAudiencesError,
    fetchMailchimpAudiences,
    brevoLists,
    brevoListsLoading,
    brevoListsError,
    fetchBrevoLists,
    requestTestEmail,
    addSalesforceMapping,
    removeSalesforceMapping,
    addHubspotMapping,
    removeHubspotMapping,
    createRowId,
});
</script>

<style>
.fmt-modal { position: fixed; inset: 0; display: none; align-items: center; justify-content: center; z-index: 1000; }
.fmt-modal--visible { display: flex; align-items: center; justify-content: center; padding: 24px 20px; overflow-y: auto; }
.fmt-modal__overlay { position: absolute; inset: 0; background: rgba(0, 0, 0, 0.35); }
.fmt-modal__content { position: relative; background: #fff; border-radius: 12px; width: 920px; max-width: calc(100vw - 40px); max-height: calc(100vh - 48px); display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 24px 48px rgba(14, 30, 37, 0.12); }
.fmt-modal__header, .fmt-modal__footer { padding: 16px 20px; border-bottom: 1px solid #dcdcde; }
.fmt-modal__header { display: flex; align-items: center; gap: 16px; }
.fmt-modal__header h2 { margin: 0; flex: 1; }
.fmt-settings-mode-toggle { display: flex; gap: 4px; background: #f0f0f1; padding: 2px; border-radius: 6px;
    margin-right: 30px; }
.fmt-settings-mode-toggle .button { margin: 0!important; background: transparent!important; border: none!important; box-shadow: none!important; color: #50575e!important; font-size: 0.9rem!important; padding: 4px 12px!important; height: auto!important; line-height: 1.4!important; }
.fmt-settings-mode-toggle .button.is-primary { background: #fff!important; color: #1d2327!important; box-shadow: 0 1px 2px rgba(0,0,0,0.1)!important; }
.fmt-modal-close {
    position: absolute;
    top: 14px;
    right: 14px;
}
.fmt-modal__footer { border-bottom: 0; border-top: 1px solid #dcdcde; display: flex; justify-content: flex-end; gap: 8px; background: #fff; }
.fmt-modal__body { flex: 1; display: flex; flex-direction: column; padding: 0; max-height: calc(90vh - 112px); }
.fmt-modal__tabs {
    display: flex;
    flex-wrap: nowrap;
    gap: 4px;
    padding: 12px 20px 0;
    border-bottom: 1px solid #dcdcde;
    background: #f6f7f7;
    overflow-x: auto;
    overflow-y: hidden;
    flex-shrink: 0;
    scroll-padding-inline: 20px;
}

.fmt-modal__tabs > * {
    flex-shrink: 0;
    white-space: nowrap;
}
.fmt-tab { background: transparent; border: none; padding: 0 12px 12px; font-size: 1rem; font-weight: 600; cursor: pointer; color: #50575e; border-bottom: 3px solid transparent; }
.fmt-tab:hover { color: #1d2327; }
.fmt-tab--active { color: #1d2327; border-bottom-color: #2271b1; }
.fmt-modal__panels { flex: 1; overflow-y: auto; padding: 20px; display: flex; }
.fmt-modal__panel { display: grid; gap: 16px; flex: 1; }
.fmt-setting { display: flex; flex-direction: column; gap: 6px; }
.fmt-setting label > span:first-child, .fmt-setting > span:first-child { font-size: 0.98rem; font-weight: 500; }
.fmt-setting--switch { flex-direction: row; align-items: center; justify-content: space-between; }
.fmt-setting--split { display: flex; gap: 12px; }
.fmt-setting--split label, .fmt-setting__inline label { flex: 1; display: flex; flex-direction: column; gap: 6px; }
.fmt-setting--stacked { display: flex; flex-direction: column; gap: 6px; }
.fmt-setting-group { display: grid; gap: 16px; }
.fmt-setting__inline { display: flex; gap: 12px; margin-bottom: 10px; }
.fmt-setting__hint { color: #6c757d; font-size: 0.92rem; display: block; margin-top: 4px; }
textarea, input:not([type="checkbox"]):not([type="radio"]), select { width: 100%; font-size: 1rem; padding: 6px 8px; }
textarea { min-height: 100px; }
.fmt-integration-card { border: 1px solid #dcdcde; border-radius: 8px; padding: 20px; background: #f9f9f9; display: grid; gap: 16px; }
.fmt-setting.fmt-setting--switch { justify-content: flex-start; }
.fmt-integration-header { display: flex; gap: 12px; align-items: flex-start; }
.fmt-integration-icon { font-size: 32px; line-height: 1; }
.fmt-integration-header h3 { margin: 0 0 4px; font-size: 1.1rem; font-weight: 600; }
.fmt-integration-description { margin: 0; font-size: 0.92rem; color: #50575e; }
.fmt-integration-hint { display: block; margin-top: 4px; color: #6c757d; font-size: 0.92rem; }
.fmt-integration-inline-error { margin-top: 6px; color: #b32d2e; font-size: 0.92rem; }
.fmt-integration-mappings { display: flex; flex-direction: column; gap: 10px; }
.fmt-integration-mapping__row {
    display: grid;
    /* two flexible columns for main selects, a medium column for mode select, and a compact button */
    grid-template-columns: minmax(200px, 1fr) minmax(200px, 1fr) minmax(120px, 180px) 44px;
    gap: 8px;
    align-items: center;
}

/* allow inputs/selects inside the grid to shrink below their content width */
.fmt-integration-mapping__row input,
.fmt-integration-mapping__row select,
.fmt-integration-mapping__row textarea {
    min-width: 0;
    width: 100%;
    box-sizing: border-box;
}

/* compact action button: fixed small width and centered content */
.fmt-integration-mapping__row button {
    white-space: nowrap;
    width: 44px;
    min-width: 44px;
    padding: 6px 8px;
    text-align: center;
    background: none!important;
    border: none!important;
}

/* Responsive fallbacks: keep button in a compact column, let fields wrap neatly */
@media (max-width: 880px) {
    .fmt-integration-mapping__row {
        grid-template-columns: minmax(200px, 1fr) minmax(200px, 1fr) 44px;
    }
}

@media (max-width: 640px) {
    .fmt-integration-mapping__row {
        grid-template-columns: 1fr 44px;
    }
}
.fmt-integration-card textarea { width: 100%; min-height: 80px; }
</style>
