<?php

namespace GriffinForms\Admin\App\Html\Modals\Accounts;

trait Scripts
{
    public function getModalJs()
    {
        $this->printGuidedFlowShellJs();
        $this->modalPreludeJs();
        $this->modalRenderersJs();
        $this->modalEventBindingsJs();
        $this->getRequestsJs();
    }

    protected function modalPreludeJs()
    {
        $discard_draft_label = wp_json_encode(__('Discard this draft?', 'griffinforms-form-builder'));
        $unsaved_changes_lost_label = wp_json_encode(__('Your unsaved changes will be lost.', 'griffinforms-form-builder'));
        $keep_editing_label = wp_json_encode(__('Keep editing', 'griffinforms-form-builder'));
        $discard_label = wp_json_encode(__('Discard', 'griffinforms-form-builder'));
        $add_email_before_registration_label = wp_json_encode(__('Add an email field to this form before creating user registration.', 'griffinforms-form-builder'));
        $all_email_fields_used_label = wp_json_encode(__('All email fields in this form are already used by user registration.', 'griffinforms-form-builder'));
        $user_registration_label = wp_json_encode(__('User Registration', 'griffinforms-form-builder'));
        $handle_user_registration_label = wp_json_encode(__('Choose how this form should handle user registration.', 'griffinforms-form-builder'));
        $create_workflow_label = wp_json_encode(__('Create workflow', 'griffinforms-form-builder'));
        $choose_signups_label = wp_json_encode(__('Follow the steps to choose how this form should handle sign-ups.', 'griffinforms-form-builder'));
        $save_user_registration_label = wp_json_encode(__('Save user registration', 'griffinforms-form-builder'));
        $edit_workflow_label = wp_json_encode(__('Edit workflow', 'griffinforms-form-builder'));
        $review_update_registration_label = wp_json_encode(__('Review and update how this form should handle user registration.', 'griffinforms-form-builder'));
        $save_changes_label = wp_json_encode(__('Save changes', 'griffinforms-form-builder'));
        echo '
        const accountsModalId = "#griffinforms-builder-modal-accounts";
        const accountsMessageContainer = jQuery(".griffinforms-accounts-message-container");
        const accountsListWrapper = jQuery(".griffinforms-accounts-list-wrapper");
        const accountsEditorHeader = jQuery(".griffinforms-accounts-editor-header");
        const accountsEditorWrapper = jQuery(".griffinforms-accounts-editor-wrapper");
        const accountsRulesList = jQuery("#griffinforms-accounts-rules-list");
        const accountsEditor = jQuery("#griffinforms-accounts-editor");
        const accountsRuleTitle = jQuery(".griffinforms-accounts-active-rule-title");
        const accountsModal = jQuery(accountsModalId);
        const accountsGuidedFlowProgress = jQuery("#griffinforms-accounts-guided-flow-progress");
        const accountsGuidedFlowNav = jQuery("#griffinforms-accounts-guided-flow-nav");
        const accountsActionButton = jQuery("#griffinforms-builder-modal-accounts-action-btn");
        const accountsEditorHeading = jQuery("#griffinforms-accounts-editor-heading");
        const accountsEditorDescription = jQuery("#griffinforms-accounts-editor-description");
        const accountsDiscardConfirmationHost = jQuery("#griffinforms-accounts-discard-confirmation-host");
        let accountsAllowModalClose = false;
        let accountsPendingCloseTrigger = jQuery();
        let accountsMessageState = null;

        window.griffinformsAccountsState = {
            settings: { mode: "custom", settings: { rules: [] } },
            editorData: null,
            activeRuleId: null,
            persistedRuleIds: [],
            isRequestInFlight: false,
            activeRequestCount: 0,
            guidedFlow: null
        };

        function griffinformsScrollAccountsNoticeIntoView() {
            if (!accountsMessageContainer.length || !accountsEditorWrapper.length || accountsEditorWrapper.hasClass("d-none")) {
                return;
            }

            const modalBody = jQuery(accountsModalId).find(".modal-body").first();
            const noticeElement = accountsMessageContainer.get(0);

            if (noticeElement && typeof noticeElement.scrollIntoView === "function") {
                noticeElement.scrollIntoView({
                    behavior: "smooth",
                    block: "start",
                    inline: "nearest"
                });
            }

            if (modalBody.length) {
                modalBody.stop(true).animate({
                    scrollTop: 0
                }, 180);
            }
        }

        function griffinformsShowAccountsMessage(type, message) {
            const noticeClass = type === "success" ? "gf-notice-success" : "gf-notice-danger";
            const notice = jQuery("<div>", { class: "gf-notice " + noticeClass, role: "alert" }).text(message || "");
            accountsMessageState = { type: type || "", message: message || "", source: "generic" };
            accountsMessageContainer.empty().append(notice);

            if (type !== "success") {
                griffinformsScrollAccountsNoticeIntoView();
            }
        }

        function griffinformsShowAccountsValidationMessage(message) {
            accountsMessageState = { type: "danger", message: message || "", source: "validation" };
            const notice = jQuery("<div>", { class: "gf-notice gf-notice-danger", role: "alert" }).text(message || "");
            accountsMessageContainer.empty().append(notice);
            griffinformsScrollAccountsNoticeIntoView();
        }

        function griffinformsHideAccountsMessage() {
            accountsMessageState = null;
            accountsMessageContainer.empty();
        }

        function griffinformsMaybeClearAccountsValidationMessage() {
            if (!accountsMessageState || accountsMessageState.source !== "validation") {
                return;
            }

            if (!griffinformsIsAccountsGuidedFlowActive()) {
                griffinformsHideAccountsMessage();
                return;
            }

            const guidedFlow = window.griffinformsAccountsState.guidedFlow;
            if (!guidedFlow || typeof guidedFlow.validateStep !== "function") {
                return;
            }

            const currentStepId = String(guidedFlow.currentStepId || "");
            if (!currentStepId) {
                return;
            }

            const result = guidedFlow.validateStep(currentStepId) || {};
            if (result.valid !== false) {
                griffinformsHideAccountsMessage();
            }
        }

        function griffinformsHideDiscardConfirmation() {
            accountsDiscardConfirmationHost.empty().addClass("d-none").removeClass("is-below").css({ left: "", top: "" });
        }

        function griffinformsHasUnsavedGuidedDraft() {
            const activeRuleId = window.griffinformsAccountsState.activeRuleId;
            if (!activeRuleId) {
                return false;
            }

            return window.griffinformsAccountsState.persistedRuleIds.indexOf(activeRuleId) === -1;
        }

        function griffinformsBuildDiscardConfirmationHtml() {
            return "<div class=\"gf-accounts-discard-confirmation\" role=\"dialog\" aria-label=" + ' . $discard_draft_label . ' + ">" +
                "<div class=\"gf-accounts-discard-confirmation-title\">" + ' . $discard_draft_label . ' + "</div>" +
                "<div class=\"gf-accounts-discard-confirmation-copy\">" + ' . $unsaved_changes_lost_label . ' + "</div>" +
                "<div class=\"gf-accounts-discard-confirmation-actions d-flex justify-content-end gap-2 mt-3\">" +
                    "<button type=\"button\" class=\"gf-btn gf-btn-secondary gf-accounts-discard-keep-editing\">" + ' . $keep_editing_label . ' + "</button>" +
                    "<button type=\"button\" class=\"gf-btn gf-btn-primary gf-accounts-discard-confirm\">" + ' . $discard_label . ' + "</button>" +
                "</div>" +
            "</div>";
        }

        function griffinformsShowDiscardConfirmation($trigger) {
            if (!$trigger || !$trigger.length || !accountsDiscardConfirmationHost.length) {
                return;
            }

            const $content = accountsModal.find(".modal-content").first();
            if (!$content.length) {
                return;
            }

            accountsDiscardConfirmationHost.html(griffinformsBuildDiscardConfirmationHtml()).removeClass("d-none");

            const triggerOffset = $trigger.offset();
            const contentOffset = $content.offset();
            if (!triggerOffset || !contentOffset) {
                return;
            }

            const bubbleWidth = accountsDiscardConfirmationHost.outerWidth() || 280;
            const bubbleHeight = accountsDiscardConfirmationHost.outerHeight() || 140;
            const contentWidth = $content.innerWidth() || 0;
            let left = (triggerOffset.left - contentOffset.left) + ($trigger.outerWidth() / 2);
            const minLeft = (bubbleWidth / 2) + 16;
            const maxLeft = Math.max(minLeft, contentWidth - (bubbleWidth / 2) - 16);
            left = Math.min(Math.max(left, minLeft), maxLeft);

            let top = (triggerOffset.top - contentOffset.top) - 10;
            const showBelow = top < bubbleHeight + 12;
            if (showBelow) {
                top = (triggerOffset.top - contentOffset.top) + $trigger.outerHeight() + 10;
                accountsDiscardConfirmationHost.addClass("is-below");
            } else {
                accountsDiscardConfirmationHost.removeClass("is-below");
            }

            accountsDiscardConfirmationHost.css({
                left: left + "px",
                top: top + "px"
            });
        }

        function griffinformsRequestAccountsCloseConfirmation($trigger) {
            if (!griffinformsHasUnsavedGuidedDraft()) {
                return false;
            }

            accountsPendingCloseTrigger = $trigger && $trigger.length ? $trigger : jQuery();
            griffinformsShowDiscardConfirmation($trigger);
            return true;
        }

        function griffinformsHideAccountsModal() {
            accountsAllowModalClose = true;
            const modalElement = accountsModal.get(0);
            if (window.bootstrap && window.bootstrap.Modal && modalElement) {
                const instance = window.bootstrap.Modal.getInstance(modalElement);
                if (instance) {
                    instance.hide();
                    return;
                }
            }

            accountsModal.modal("hide");
        }

        function griffinformsRenderAccountsListLoadingPlaceholder() {
            if (!accountsRulesList.length) {
                return;
            }

            accountsRulesList.html(
                "<div class=\"border rounded-3 p-4 bg-white gf-accounts-loading-placeholder\">" +
                    "<div class=\"placeholder-glow mb-3\"><span class=\"placeholder col-3\"></span></div>" +
                    "<div class=\"placeholder-glow mb-2\"><span class=\"placeholder col-8\"></span></div>" +
                    "<div class=\"placeholder-glow mb-4\"><span class=\"placeholder col-5\"></span></div>" +
                    "<div class=\"placeholder-glow\"><span class=\"placeholder col-12\" style=\"height: 64px;\"></span></div>" +
                "</div>"
            );
        }

        function griffinformsRenderAccountsEditorLoadingPlaceholder() {
            if (!accountsEditor.length) {
                return;
            }

            accountsEditor.html(
                "<div class=\"gf-accounts-editor-loading-placeholder\">" +
                    "<div class=\"placeholder-glow mb-4\"><span class=\"placeholder col-4\"></span></div>" +
                    "<div class=\"placeholder-glow mb-3\"><span class=\"placeholder col-12\" style=\"height: 52px;\"></span></div>" +
                    "<div class=\"placeholder-glow mb-3\"><span class=\"placeholder col-12\" style=\"height: 52px;\"></span></div>" +
                    "<div class=\"placeholder-glow\"><span class=\"placeholder col-12\" style=\"height: 180px;\"></span></div>" +
                "</div>"
            );
        }

        function griffinformsApplyAccountsBusyState(isBusy) {
            const closeButton = jQuery("#griffinforms-builder-modal-accounts-close-btn");
            const backButton = accountsEditorHeader.find(".griffinforms-accounts-back-to-list");

            window.griffinformsAccountsState.isRequestInFlight = !!isBusy;
            accountsModal.toggleClass("gf-accounts-busy", !!isBusy);

            accountsActionButton.prop("disabled", !!isBusy);
            closeButton.prop("disabled", !!isBusy);
            backButton.prop("disabled", !!isBusy).toggleClass("opacity-50", !!isBusy);

            accountsRulesList.find(".griffinforms-add-rule-slab, .griffinforms-accounts-rule-edit, .griffinforms-accounts-rule-delete")
                .toggleClass("pe-none opacity-50", !!isBusy)
                .prop("disabled", !!isBusy);

            accountsEditor.find("input, select, textarea, button").prop("disabled", !!isBusy);
            if (window.griffinformsAccountsState.guidedFlow && griffinformsIsAccountsGuidedFlowActive()) {
                window.griffinformsAccountsState.guidedFlow.isBusy = !!isBusy;
                griffinformsSyncAccountsGuidedFlow();
            }

            if (isBusy) {
                griffinformsHideDiscardConfirmation();
            }
        }

        function griffinformsBeginAccountsRequest(options = {}) {
            const requestCount = parseInt(window.griffinformsAccountsState.activeRequestCount || 0, 10) || 0;
            window.griffinformsAccountsState.activeRequestCount = requestCount + 1;

            if (options.listPlaceholder) {
                griffinformsRenderAccountsListLoadingPlaceholder();
            }

            if (options.editorPlaceholder) {
                griffinformsRenderAccountsEditorLoadingPlaceholder();
            }

            griffinformsApplyAccountsBusyState(true);
            griffinformsToggleModalSpinner(true);
        }

        function griffinformsEndAccountsRequest() {
            const requestCount = parseInt(window.griffinformsAccountsState.activeRequestCount || 0, 10) || 0;
            const nextCount = Math.max(0, requestCount - 1);
            window.griffinformsAccountsState.activeRequestCount = nextCount;

            if (nextCount > 0) {
                return;
            }

            griffinformsApplyAccountsBusyState(false);
            griffinformsToggleModalSpinner(false);
        }

        function griffinformsGetAccountsRules() {
            const payload = window.griffinformsAccountsState.settings || {};
            const inner = payload.settings || {};
            return Array.isArray(inner.rules) ? inner.rules : [];
        }

        function griffinformsFindAccountRule(ruleId) {
            return griffinformsGetAccountsRules().find(function(rule) {
                return rule && rule.id === ruleId;
            }) || null;
        }

        function griffinformsCreateDefaultAccountRule() {
            return {
                id: "wa_rule_" + Date.now(),
                enabled: true,
                email_field_id: 0,
                password_mode: "generate_password",
                password_field_id: 0,
                first_name_mode: "none",
                first_name_field_id: 0,
                last_name_mode: "none",
                last_name_field_id: 0,
                username_mode: "generate_only",
                username_field_id: 0,
                profile_image_mode: "none",
                profile_image_field_id: 0,
                send_confirmation_email: true,
                confirmation_message_id: 0,
                role: "subscriber",
                creation_mode: "immediate_create",
                existing_account_behavior: "error"
            };
        }

        function griffinformsGetAvailableEmailFieldsForNewRule() {
            const editorData = window.griffinformsAccountsState.editorData || {};
            const fields = editorData.fields || {};
            const emailFields = Array.isArray(fields.email_fields) ? fields.email_fields : [];
            const usedEmailFieldIds = griffinformsGetAccountsRules().map(function(rule) {
                return parseInt((rule && rule.email_field_id) || 0, 10) || 0;
            }).filter(function(fieldId) {
                return fieldId > 0;
            });

            return emailFields.filter(function(field) {
                const fieldId = parseInt((field && field.id) || 0, 10) || 0;
                return fieldId > 0 && usedEmailFieldIds.indexOf(fieldId) === -1;
            });
        }

        function griffinformsGetAccountsAddRuleDisabledMessage() {
            const editorData = window.griffinformsAccountsState.editorData || {};
            const fields = editorData.fields || {};
            const emailFields = Array.isArray(fields.email_fields) ? fields.email_fields : [];
            const availableEmailFields = griffinformsGetAvailableEmailFieldsForNewRule();

            if (!emailFields.length) {
                return ' . $add_email_before_registration_label . ';
            }

            if (!availableEmailFields.length) {
                return ' . $all_email_fields_used_label . ';
            }

            return "";
        }

        function griffinformsResolveOptionLabel(groupKey, selectedValue) {
            const editorData = window.griffinformsAccountsState.editorData || {};
            const fields = editorData.fields || {};
            const source = fields[groupKey] || editorData[groupKey] || [];
            const options = Array.isArray(source) ? source : [];
            const match = options.find(function(option) {
                const rawValue = typeof option.value !== "undefined" ? option.value : option.id;
                return String(rawValue || "") === String(selectedValue || "");
            });
            return match ? (match.label || "") : "";
        }

        function griffinformsGetFieldOption(groupKey, selectedValue) {
            const editorData = window.griffinformsAccountsState.editorData || {};
            const fields = editorData.fields || {};
            const source = fields[groupKey] || editorData[groupKey] || [];
            const options = Array.isArray(source) ? source : [];

            return options.find(function(option) {
                const rawValue = typeof option.value !== "undefined" ? option.value : option.id;
                return String(rawValue || "") === String(selectedValue || "");
            }) || null;
        }

        function griffinformsIsActiveAccountEmailIterable() {
            const rule = griffinformsFindAccountRule(window.griffinformsAccountsState.activeRuleId) || {};
            const emailField = griffinformsGetFieldOption("email_fields", rule.email_field_id);
            return !!(emailField && emailField.is_iterable);
        }

        function griffinformsSetAccountsRuleTitle(ruleId) {
            if (!accountsRuleTitle.length) {
                return;
            }

            const rules = griffinformsGetAccountsRules();
            const index = rules.findIndex(function(rule) {
                return rule && rule.id === ruleId;
            });
            const rule = index >= 0 ? rules[index] : null;

            if (!rule) {
                accountsRuleTitle.html("").addClass("d-none");
                return;
            }

            const fallbackTitle = ' . $user_registration_label . ' + " " + (index + 1);
            const emailLabel = griffinformsResolveOptionLabel("email_fields", rule.email_field_id);
            const title = emailLabel ? (fallbackTitle + ": " + emailLabel) : fallbackTitle;

            accountsRuleTitle.text(title).removeClass("d-none");
        }

        function griffinformsResetAccountsEditorModeUi() {
            const defaultLabel = String(accountsActionButton.data("default-label") || ' . $save_changes_label . ');
            accountsEditorHeading.text(' . $user_registration_label . ');
            accountsEditorDescription.text(' . $handle_user_registration_label . ');
            accountsActionButton.text(defaultLabel).removeClass("d-none");
            accountsRuleTitle.removeClass("d-none");
            accountsEditor.find(".gf-accounts-enabled-toggle").removeClass("d-none");
            accountsEditorWrapper.removeClass("gf-accounts-guided-add-mode gf-accounts-edit-mode");
        }

        function griffinformsApplyAccountsEditorModeUi() {
            const isGuidedAdd = griffinformsIsAccountsGuidedFlowActive();
            if (isGuidedAdd) {
                accountsEditorHeading.text(' . $create_workflow_label . ');
                accountsEditorDescription.text(' . $choose_signups_label . ');
                accountsActionButton.text(' . $save_user_registration_label . ');
                accountsRuleTitle.addClass("d-none");
                accountsEditor.find(".gf-accounts-enabled-toggle").addClass("d-none");
                accountsEditorWrapper.addClass("gf-accounts-guided-add-mode").removeClass("gf-accounts-edit-mode");
                return;
            }

            accountsEditorHeading.text(' . $edit_workflow_label . ');
            accountsEditorDescription.text(' . $review_update_registration_label . ');
            accountsActionButton.text(String(accountsActionButton.data("default-label") || ' . $save_changes_label . '));
            accountsRuleTitle.removeClass("d-none");
            accountsEditor.find(".gf-accounts-enabled-toggle").removeClass("d-none");
            accountsEditorWrapper.addClass("gf-accounts-edit-mode").removeClass("gf-accounts-guided-add-mode");
        }

        function griffinformsFadeSwap(hideEl, showEl) {
            const duration = 180;

            const reveal = function(el) {
                if (!el || !el.length) {
                    return;
                }

                if (!el.hasClass("d-none") && el.is(":visible")) {
                    return;
                }

                el.removeClass("d-none")
                    .stop(true, true)
                    .css("display", "none")
                    .fadeIn(duration, function() {
                        jQuery(this).css("display", "");
                    });
            };

            if (hideEl && hideEl.length && !hideEl.hasClass("d-none")) {
                hideEl.stop(true, true).fadeOut(duration, function() {
                    hideEl.addClass("d-none").css("display", "");
                    reveal(showEl);
                });
                return;
            }

            reveal(showEl);
        }
        ';
    }

    protected function modalRenderersJs()
    {
        $please_wait_loading_label = wp_json_encode(__('Please wait while user registration finishes loading.', 'griffinforms-form-builder'));
        $failed_load_registration_label = wp_json_encode(__('Failed to load user registration.', 'griffinforms-form-builder'));
        $select_or_add_workflow_label = wp_json_encode(__('Select a user registration workflow from the list or add a new one to begin.', 'griffinforms-form-builder'));
        $step_label = wp_json_encode(__('Step', 'griffinforms-form-builder'));
        $choose_email_before_continue_label = wp_json_encode(__('Choose the email field for this user registration before continuing.', 'griffinforms-form-builder'));
        $choose_workflow_role_before_continue_label = wp_json_encode(__('Choose the registration workflow and role before continuing.', 'griffinforms-form-builder'));
        $choose_password_strategy_before_continue_label = wp_json_encode(__('Choose a password strategy before continuing.', 'griffinforms-form-builder'));
        $choose_confirmation_message_before_continue_label = wp_json_encode(__('Choose a confirmation email message before continuing.', 'griffinforms-form-builder'));
        $previous_label = wp_json_encode(__('Previous', 'griffinforms-form-builder'));
        $next_label = wp_json_encode(__('Next', 'griffinforms-form-builder'));
        $failed_refresh_registration_label = wp_json_encode(__('Failed to refresh user registration.', 'griffinforms-form-builder'));
        $failed_load_registration_settings_label = wp_json_encode(__('Failed to load user registration settings.', 'griffinforms-form-builder'));
        $failed_load_registration_data_label = wp_json_encode(__('Failed to load user registration data.', 'griffinforms-form-builder'));
        echo '
        function griffinformsApplyAccountsAddRuleState() {
            const addRuleSlab = accountsRulesList.find(".griffinforms-add-rule-slab");
            if (!addRuleSlab.length) {
                return;
            }

            const availableEmailFields = griffinformsGetAvailableEmailFieldsForNewRule();
            const hasAvailableEmailFields = availableEmailFields.length > 0;
            const disabledMessage = griffinformsGetAccountsAddRuleDisabledMessage();
            const isBusy = !!window.griffinformsAccountsState.isRequestInFlight;
            const isDisabled = isBusy || !hasAvailableEmailFields;

            addRuleSlab.toggleClass("opacity-50", isDisabled);
            addRuleSlab.toggleClass("pe-none", isBusy);
            addRuleSlab.attr("aria-disabled", isDisabled ? "true" : "false");
            addRuleSlab.attr("title", isBusy ? ' . $please_wait_loading_label . ' : (hasAvailableEmailFields ? "" : disabledMessage));
        }

        function griffinformsRenderAccountsRulesList() {
            if (!accountsRulesList.length) {
                return;
            }

            griffinformsBeginAccountsRequest({ listPlaceholder: true });
            griffinformsGetAccountRulesListHtml(window.griffinformsAccountsState.settings.settings || {}).done(function(response) {
                if (!response || !response.success || !response.data || typeof response.data.html === "undefined") {
                    griffinformsShowAccountsMessage("danger", (response && response.data && response.data.msg) ? response.data.msg : ' . $failed_load_registration_label . ');
                    return;
                }

                accountsRulesList.html(response.data.html);
                griffinformsApplyAccountsAddRuleState();
            }).fail(function() {
                griffinformsShowAccountsMessage("danger", ' . $failed_load_registration_label . ');
            }).always(function() {
                griffinformsEndAccountsRequest();
            });
        }

        function griffinformsRenderAccountsEmptyState() {
            if (!accountsEditor.length) {
                return;
            }

            accountsEditor.html("<div class=\"text-muted small\">" + ' . $select_or_add_workflow_label . ' + "</div>");
        }

        function griffinformsApplyAccountsEditorVisibility() {
            if (!griffinformsIsAccountsGuidedFlowActive()) {
                accountsEditor.find("[data-accounts-stage]").removeClass("d-none");
            }
            const rule = griffinformsFindAccountRule(window.griffinformsAccountsState.activeRuleId) || {};
            accountsEditor.find("[data-accounts-visible-when]").each(function() {
                const el = jQuery(this);
                const condition = String(el.data("accounts-visible-when") || "");
                const parts = condition.split(":");
                const field = parts[0] || "";
                const expected = parts[1] || "";

                let actual = rule[field];
                if (typeof actual === "boolean") {
                    actual = actual ? "1" : "0";
                }

                const shouldShow = String(actual || "") === expected;
                const container = el.closest(".gf-app-control, .col-md-6, .col-lg-6, .col-sm-12");
                if (container.length) {
                    container.toggleClass("d-none", !shouldShow);
                } else {
                    el.toggleClass("d-none", !shouldShow);
                }
            });
        }

        function griffinformsApplyAccountsPasswordModeRules() {
            const passwordModeSelect = accountsEditor.find("[data-accounts-field=\"password_mode\"]");
            if (!passwordModeSelect.length) {
                return;
            }

            const hasPasswordFields = Array.isArray(((window.griffinformsAccountsState.editorData || {}).fields || {}).password_fields)
                && (((window.griffinformsAccountsState.editorData || {}).fields || {}).password_fields).length > 0;
            const isIterableEmail = griffinformsIsActiveAccountEmailIterable();
            const mappedPasswordOption = passwordModeSelect.find("option[value=\"mapped_password\"]");
            const shouldDisableMappedPassword = !hasPasswordFields || isIterableEmail;

            mappedPasswordOption.prop("disabled", shouldDisableMappedPassword);
            accountsEditor.find(".gf-accounts-iterable-email-password-note").toggleClass("d-none", !isIterableEmail);
        }

        function griffinformsApplyAccountsStageFlow() {
            if (!griffinformsIsAccountsGuidedFlowActive()) {
                accountsEditor.find("[data-accounts-stage]").removeClass("d-none");
                return;
            }
            const rule = griffinformsFindAccountRule(window.griffinformsAccountsState.activeRuleId) || {};
            const hasEmail = parseInt(rule.email_field_id || 0, 10) > 0;
            const hasCreationMode = String(rule.creation_mode || "").length > 0;
            const hasPasswordMode = String(rule.password_mode || "").length > 0;

            accountsEditor.find("[data-accounts-stage]").addClass("d-none");
            accountsEditor.find("[data-accounts-stage=\"step_1\"]").removeClass("d-none");

            if (!hasEmail) {
                return;
            }

            accountsEditor.find("[data-accounts-stage=\"step_2\"]").removeClass("d-none");

            if (!hasCreationMode) {
                return;
            }

            accountsEditor.find("[data-accounts-stage=\"step_3\"]").removeClass("d-none");

            if (!hasPasswordMode) {
                return;
            }

            accountsEditor.find("[data-accounts-stage=\"step_4\"]").removeClass("d-none");
            accountsEditor.find("[data-accounts-stage=\"step_5\"]").removeClass("d-none");
            accountsEditor.find("[data-accounts-stage=\"step_6\"]").removeClass("d-none");
        }

        function griffinformsGetAccountsGuidedFlowStepIds() {
            return ["step_1", "step_2", "step_3", "step_4", "step_5", "step_6"];
        }

        function griffinformsIsAccountsGuidedFlowActive() {
            const activeRuleId = window.griffinformsAccountsState.activeRuleId;
            if (!activeRuleId) {
                return false;
            }

            return window.griffinformsAccountsState.persistedRuleIds.indexOf(activeRuleId) === -1;
        }

        function griffinformsGetAccountsGuidedFlowSteps() {
            return griffinformsGetAccountsGuidedFlowStepIds().map(function(stepId, index) {
                const stage = accountsEditor.find("[data-guided-flow-step=\"" + stepId + "\"]").first();
                return {
                    id: stepId,
                    label: String(stage.data("guided-flow-short-label") || stage.data("guided-flow-label") || (' . $step_label . ' + " " + (index + 1)))
                };
            }).filter(function(step) {
                return !!step.id;
            });
        }

        function griffinformsGetAccountsGuidedStepValidation(stepId) {
            const rule = griffinformsFindAccountRule(window.griffinformsAccountsState.activeRuleId) || {};

            if (stepId === "step_1") {
                const isValid = parseInt(rule.email_field_id || 0, 10) > 0;
                return {
                    valid: isValid,
                    message: ' . $choose_email_before_continue_label . '
                };
            }

            if (stepId === "step_2") {
                const hasCreationMode = String(rule.creation_mode || "").length > 0;
                const hasRole = String(rule.role || "").length > 0;
                return {
                    valid: hasCreationMode && hasRole,
                    message: ' . $choose_workflow_role_before_continue_label . '
                };
            }

            if (stepId === "step_3") {
                const hasPasswordMode = String(rule.password_mode || "").length > 0;
                const hasMappedPasswordField = parseInt(rule.password_field_id || 0, 10) > 0;
                const isValid = hasPasswordMode && (rule.password_mode !== "mapped_password" || hasMappedPasswordField);
                return {
                    valid: isValid,
                    message: ' . $choose_password_strategy_before_continue_label . '
                };
            }

            if (stepId === "step_5") {
                const sendsConfirmation = !!rule.send_confirmation_email;
                const hasConfirmationMessage = parseInt(rule.confirmation_message_id || 0, 10) > 0;
                return {
                    valid: !sendsConfirmation || hasConfirmationMessage,
                    message: ' . $choose_confirmation_message_before_continue_label . '
                };
            }

            return { valid: true };
        }

        function griffinformsEnsureAccountsGuidedFlow() {
            const activeRuleId = window.griffinformsAccountsState.activeRuleId;
            if (!activeRuleId) {
                window.griffinformsAccountsState.guidedFlow = null;
                return null;
            }

            const guidedFlow = window.griffinformsAccountsState.guidedFlow || {};
            if (guidedFlow.ruleId !== activeRuleId) {
                guidedFlow.ruleId = activeRuleId;
                guidedFlow.currentStepId = griffinformsGetAccountsGuidedFlowStepIds()[0] || "";
            }

            guidedFlow.progressContainer = accountsGuidedFlowProgress;
            guidedFlow.navContainer = accountsGuidedFlowNav;
            guidedFlow.getSteps = griffinformsGetAccountsGuidedFlowSteps;
            guidedFlow.validateStep = function(stepId) {
                return griffinformsGetAccountsGuidedStepValidation(stepId);
            };
            guidedFlow.onInvalid = function(result) {
                if (result && result.message) {
                    griffinformsShowAccountsValidationMessage(result.message);
                }
            };
            guidedFlow.onSync = function(normalized) {
                accountsEditor.find("[data-guided-flow-step]").addClass("d-none");
                if (normalized.currentStepId) {
                    accountsEditor.find("[data-guided-flow-step=\"" + normalized.currentStepId + "\"]").removeClass("d-none");
                }

                const shouldShowSave = !!normalized.isLast;
                accountsActionButton.toggleClass("d-none", !shouldShowSave);
                griffinformsMaybeClearAccountsValidationMessage();
            };
            guidedFlow.backLabel = ' . $previous_label . ';
            guidedFlow.nextLabel = ' . $next_label . ';
            guidedFlow.isBusy = !!window.griffinformsAccountsState.isRequestInFlight;

            window.griffinformsAccountsState.guidedFlow = guidedFlow;
            return guidedFlow;
        }

        function griffinformsSyncAccountsGuidedFlow() {
            if (!griffinformsIsAccountsGuidedFlowActive()) {
                accountsEditorWrapper.removeClass("gf-guided-flow-active");
                accountsGuidedFlowProgress.empty().addClass("d-none");
                accountsGuidedFlowNav.empty().addClass("d-none");
                accountsActionButton.removeClass("d-none");
                window.griffinformsAccountsState.guidedFlow = null;
                griffinformsApplyAccountsEditorModeUi();
                griffinformsApplyAccountsStageFlow();
                return;
            }

            const guidedFlow = griffinformsEnsureAccountsGuidedFlow();
            if (!guidedFlow || !window.griffinformsGuidedFlowShell) {
                griffinformsApplyAccountsStageFlow();
                return;
            }

            accountsEditorWrapper.addClass("gf-guided-flow-active");
            griffinformsApplyAccountsEditorModeUi();
            window.griffinformsGuidedFlowShell.sync(guidedFlow);
        }

        function griffinformsRefreshAccountsEditor() {
            const ruleId = window.griffinformsAccountsState.activeRuleId;
            if (!ruleId) {
                return;
            }

            const rule = griffinformsFindAccountRule(ruleId);
            if (!rule) {
                return;
            }

            griffinformsBeginAccountsRequest({ editorPlaceholder: true });
            const isPersistedRule = window.griffinformsAccountsState.persistedRuleIds.indexOf(ruleId) !== -1;

            griffinformsGetAccountRuleEditorHtml(rule, window.griffinformsAccountsState.settings.settings || {}, isPersistedRule).done(function(response) {
                if (!response || !response.success || !response.data || !response.data.html) {
                    griffinformsShowAccountsMessage("danger", (response && response.data && response.data.msg) ? response.data.msg : ' . $failed_refresh_registration_label . ');
                    return;
                }

                if (response.data.rule && typeof response.data.rule === "object") {
                    const rules = griffinformsGetAccountsRules();
                    const ruleIndex = rules.findIndex(function(existingRule) {
                        return existingRule && existingRule.id === rule.id;
                    });
                    if (ruleIndex >= 0) {
                        rules[ruleIndex] = response.data.rule;
                        window.griffinformsAccountsState.settings.settings.rules = rules;
                    }
                }

                accountsEditor.html(response.data.html);
                griffinformsBindAccountsEditorInputs();
                griffinformsSyncAccountsGuidedFlow();
                griffinformsApplyAccountsEditorVisibility();
                griffinformsApplyAccountsPasswordModeRules();
                griffinformsSetAccountsRuleTitle(ruleId);
            }).fail(function() {
                griffinformsShowAccountsMessage("danger", ' . $failed_refresh_registration_label . ');
            }).always(function() {
                griffinformsEndAccountsRequest();
            });
        }

        function griffinformsBindAccountsEditorInputs() {
            accountsEditor.find("[data-accounts-field]").on("change", function() {
                const field = jQuery(this).data("accounts-field");
                let value;

                if (jQuery(this).is(":checkbox")) {
                    value = jQuery(this).is(":checked");
                } else {
                    value = jQuery(this).val();
                }

                griffinformsUpdateActiveAccountRule(field, value);
                if (field === "email_field_id") {
                    griffinformsRefreshAccountsEditor();
                    return;
                }
                griffinformsSyncAccountsGuidedFlow();
                griffinformsApplyAccountsEditorVisibility();
                griffinformsApplyAccountsPasswordModeRules();
                griffinformsSetAccountsRuleTitle(window.griffinformsAccountsState.activeRuleId);
                griffinformsMaybeClearAccountsValidationMessage();
            });
        }

        function griffinformsShowAccountsListScreen(shouldRefreshList) {
            griffinformsHideAccountsMessage();
            griffinformsHideDiscardConfirmation();
            accountsEditorHeader.addClass("d-none");
            griffinformsSetAccountsRuleTitle(null);
            griffinformsResetAccountsEditorModeUi();
            accountsEditorWrapper.removeClass("gf-guided-flow-active");
            accountsGuidedFlowProgress.empty().addClass("d-none");
            accountsGuidedFlowNav.empty().addClass("d-none");
            accountsActionButton.removeClass("d-none");
            window.griffinformsAccountsState.guidedFlow = null;
            griffinformsFadeSwap(accountsEditorWrapper, accountsListWrapper);

            if (shouldRefreshList) {
                griffinformsRenderAccountsRulesList();
            }
        }

        function griffinformsShowAccountsEditorScreen(ruleId) {
            if (!accountsEditor.length) {
                return;
            }

            griffinformsHideAccountsMessage();
            const rule = griffinformsFindAccountRule(ruleId) || griffinformsCreateDefaultAccountRule();
            window.griffinformsAccountsState.activeRuleId = rule.id;
            griffinformsSetAccountsRuleTitle(rule.id);

            accountsEditorHeader.removeClass("d-none");
            griffinformsFadeSwap(accountsListWrapper, accountsEditorWrapper);

            griffinformsBeginAccountsRequest({ editorPlaceholder: true });
            const isPersistedRule = window.griffinformsAccountsState.persistedRuleIds.indexOf(rule.id) !== -1;

            griffinformsGetAccountRuleEditorHtml(rule, window.griffinformsAccountsState.settings.settings || {}, isPersistedRule).done(function(response) {
                if (!response || !response.success || !response.data || !response.data.html) {
                    griffinformsShowAccountsMessage("danger", (response && response.data && response.data.msg) ? response.data.msg : ' . $failed_load_registration_label . ');
                    return;
                }

                if (response.data.rule && typeof response.data.rule === "object") {
                    const rules = griffinformsGetAccountsRules();
                    const ruleIndex = rules.findIndex(function(existingRule) {
                        return existingRule && existingRule.id === rule.id;
                    });
                    if (ruleIndex >= 0) {
                        rules[ruleIndex] = response.data.rule;
                        window.griffinformsAccountsState.settings.settings.rules = rules;
                    }
                }

                accountsEditor.html(response.data.html);
                griffinformsBindAccountsEditorInputs();
                griffinformsSyncAccountsGuidedFlow();
                griffinformsApplyAccountsEditorVisibility();
                griffinformsApplyAccountsPasswordModeRules();
            }).fail(function() {
                griffinformsShowAccountsMessage("danger", ' . $failed_load_registration_label . ');
            }).always(function() {
                griffinformsEndAccountsRequest();
            });
        }

        function griffinformsUpdateActiveAccountRule(field, value) {
            const rules = griffinformsGetAccountsRules();
            const ruleId = window.griffinformsAccountsState.activeRuleId;
            const index = rules.findIndex(function(rule) {
                return rule && rule.id === ruleId;
            });

            if (index < 0) {
                return;
            }

            const numericFields = [
                "email_field_id",
                "password_field_id",
                "first_name_field_id",
                "last_name_field_id",
                "username_field_id",
                "profile_image_field_id",
                "confirmation_message_id"
            ];

            rules[index][field] = numericFields.indexOf(field) >= 0 ? parseInt(value || 0, 10) || 0 : value;
            window.griffinformsAccountsState.settings.settings.rules = rules;
        }

        function griffinformsDiscardUnsavedActiveRule() {
            const activeRuleId = window.griffinformsAccountsState.activeRuleId;
            if (!activeRuleId) {
                return;
            }

            if (window.griffinformsAccountsState.persistedRuleIds.indexOf(activeRuleId) !== -1) {
                return;
            }

            const payload = window.griffinformsAccountsState.settings || { mode: "custom", settings: { rules: [] } };
            const settings = payload.settings || { rules: [] };
            const rules = Array.isArray(settings.rules) ? settings.rules : [];
            settings.rules = rules.filter(function(rule) {
                return !rule || rule.id !== activeRuleId;
            });
            payload.settings = settings;
            window.griffinformsAccountsState.settings = payload;
            window.griffinformsAccountsState.activeRuleId = null;
            window.griffinformsAccountsState.guidedFlow = null;
        }

        function griffinformsLoadAccountsModal() {
            griffinformsHideAccountsMessage();
            griffinformsHideDiscardConfirmation();
            griffinformsRenderAccountsEmptyState();
            griffinformsRenderAccountsListLoadingPlaceholder();
            griffinformsBeginAccountsRequest();

            jQuery.when(
                griffinformsGetAccountRegistrationConfig(),
                griffinformsGetAccountRuleEditorData()
            ).done(function(configResponse, editorResponse) {
                const config = configResponse && configResponse[0] ? configResponse[0] : null;
                const editor = editorResponse && editorResponse[0] ? editorResponse[0] : null;

                if (!config || !config.success) {
                    griffinformsShowAccountsMessage("danger", (config && config.data && config.data.msg) ? config.data.msg : ' . $failed_load_registration_settings_label . ');
                    return;
                }

                if (!editor || !editor.success) {
                    griffinformsShowAccountsMessage("danger", (editor && editor.data && editor.data.msg) ? editor.data.msg : ' . $failed_load_registration_data_label . ');
                    return;
                }

                window.griffinformsAccountsState.settings = config.data.settings || { mode: "custom", settings: { rules: [] } };
                window.griffinformsAccountsState.editorData = editor.data.editor_data || {};
                window.griffinformsAccountsState.persistedRuleIds = griffinformsGetAccountsRules().map(function(rule) {
                    return rule && rule.id ? rule.id : null;
                }).filter(Boolean);
                window.griffinformsAccountsState.activeRuleId = null;
                window.griffinformsAccountsState.guidedFlow = null;

                griffinformsRenderAccountsEmptyState();
                griffinformsShowAccountsListScreen(true);
            }).fail(function() {
                griffinformsShowAccountsMessage("danger", ' . $failed_load_registration_settings_label . ');
            }).always(function() {
                griffinformsEndAccountsRequest();
            });
        }
        ';
    }

    protected function modalEventBindingsJs()
    {
        $form_id = (int) $this->utility->getFormId();
        $user_registration_removed_label = wp_json_encode(__('User registration removed.', 'griffinforms-form-builder'));
        $failed_delete_registration_label = wp_json_encode(__('Failed to delete user registration.', 'griffinforms-form-builder'));
        $user_registration_deleted_label = wp_json_encode(__('User registration deleted.', 'griffinforms-form-builder'));
        $delete_rule_confirm_label = wp_json_encode(__('Deleting this rule is irreversible. Do you want to continue?', 'griffinforms-form-builder'));
        $failed_save_registration_label = wp_json_encode(__('Failed to save user registration.', 'griffinforms-form-builder'));
        $user_registration_saved_label = wp_json_encode(__('User registration saved.', 'griffinforms-form-builder'));
        echo '
        function griffinformsDeleteAccountsRule(ruleId) {
            if (!ruleId) {
                return;
            }

            if (window.griffinformsAccountsState.isRequestInFlight) {
                return;
            }

            if (window.griffinformsAccountsState.persistedRuleIds.indexOf(ruleId) === -1) {
                const payload = window.griffinformsAccountsState.settings || { mode: "custom", settings: { rules: [] } };
                const rules = Array.isArray(payload.settings && payload.settings.rules) ? payload.settings.rules : [];
                payload.settings.rules = rules.filter(function(rule) {
                    return !rule || rule.id !== ruleId;
                });
                window.griffinformsAccountsState.settings = payload;
                if (window.griffinformsAccountsState.activeRuleId === ruleId) {
                    window.griffinformsAccountsState.activeRuleId = null;
                }
                griffinformsShowAccountsMessage("success", ' . $user_registration_removed_label . ');
                griffinformsShowAccountsListScreen(true);
                return;
            }

            griffinformsBeginAccountsRequest();
            griffinformsDeleteAccountRegistrationRule(ruleId).done(function(response) {
                if (!response || !response.success) {
                    griffinformsShowAccountsMessage("danger", (response && response.data && response.data.msg) ? response.data.msg : ' . $failed_delete_registration_label . ');
                    return;
                }

                window.griffinformsAccountsState.settings = response.data.settings || { mode: "custom", settings: { rules: [] } };
                window.griffinformsAccountsState.persistedRuleIds = griffinformsGetAccountsRules().map(function(rule) {
                    return rule && rule.id ? rule.id : null;
                }).filter(Boolean);
                window.griffinformsAccountsState.activeRuleId = null;
                griffinformsShowAccountsMessage("success", response.data.msg || ' . $user_registration_deleted_label . ');
                griffinformsShowAccountsListScreen(true);
                document.dispatchEvent(new CustomEvent("form-updated", { detail: { type: "accounts", formId: ' . $form_id . ' } }));
            }).fail(function() {
                griffinformsShowAccountsMessage("danger", ' . $failed_delete_registration_label . ');
            }).always(function() {
                griffinformsEndAccountsRequest();
            });
        }

        jQuery(document).on("show.bs.modal", accountsModalId, function() {
            accountsAllowModalClose = false;
            accountsPendingCloseTrigger = jQuery();
            griffinformsLoadAccountsModal();
        });

        jQuery(document).on("hide.bs.modal", accountsModalId, function(event) {
            if (accountsAllowModalClose) {
                accountsAllowModalClose = false;
                griffinformsHideDiscardConfirmation();
                accountsPendingCloseTrigger = jQuery();
                return;
            }

            if (!griffinformsHasUnsavedGuidedDraft()) {
                griffinformsHideDiscardConfirmation();
                accountsPendingCloseTrigger = jQuery();
                return;
            }

            event.preventDefault();
            event.stopImmediatePropagation();

            const $fallbackTrigger = jQuery("#griffinforms-builder-modal-accounts-cancel-btn");
            const $trigger = accountsPendingCloseTrigger && accountsPendingCloseTrigger.length ? accountsPendingCloseTrigger : $fallbackTrigger;
            griffinformsShowDiscardConfirmation($trigger);
        });

        jQuery(document).on("click", ".griffinforms-add-rule-slab", function() {
            if (window.griffinformsAccountsState.isRequestInFlight) {
                return;
            }

            const availableEmailFields = griffinformsGetAvailableEmailFieldsForNewRule();
            if (!availableEmailFields.length) {
                griffinformsShowAccountsMessage("danger", griffinformsGetAccountsAddRuleDisabledMessage());
                griffinformsApplyAccountsAddRuleState();
                return;
            }

            const payload = window.griffinformsAccountsState.settings || { mode: "custom", settings: { rules: [] } };
            if (!payload.settings) {
                payload.settings = { rules: [] };
            }
            if (!Array.isArray(payload.settings.rules)) {
                payload.settings.rules = [];
            }

            const rule = griffinformsCreateDefaultAccountRule();
            if (availableEmailFields.length === 1) {
                rule.email_field_id = parseInt(availableEmailFields[0].id || 0, 10) || 0;
            }

            payload.settings.rules.push(rule);
            window.griffinformsAccountsState.settings = payload;
            griffinformsShowAccountsEditorScreen(rule.id);
        });

        jQuery(document).on("click", ".griffinforms-accounts-rule-edit", function() {
            if (window.griffinformsAccountsState.isRequestInFlight) {
                return;
            }

            const ruleId = jQuery(this).closest(".griffinforms-accounts-rule-item").data("gf-account-rule-id");
            griffinformsShowAccountsEditorScreen(ruleId);
        });

        jQuery(document).on("click", ".griffinforms-accounts-rule-delete", function() {
            if (window.griffinformsAccountsState.isRequestInFlight) {
                return;
            }

            const ruleId = jQuery(this).closest(".griffinforms-accounts-rule-item").data("gf-account-rule-id");
            if (!ruleId) {
                return;
            }

            const confirmMessage = ' . $delete_rule_confirm_label . ';
            if (!window.confirm(confirmMessage)) {
                return;
            }

            griffinformsDeleteAccountsRule(ruleId);
        });

        jQuery(document).on("click", ".griffinforms-accounts-back-to-list", function() {
            if (window.griffinformsAccountsState.isRequestInFlight) {
                return;
            }

            griffinformsDiscardUnsavedActiveRule();
            griffinformsShowAccountsListScreen(true);
        });

        jQuery(document).on("click", "#griffinforms-builder-modal-accounts-cancel-btn, " + accountsModalId + " .btn-close", function(event) {
            if (window.griffinformsAccountsState.isRequestInFlight) {
                return;
            }

            accountsPendingCloseTrigger = jQuery(this);
            if (!griffinformsRequestAccountsCloseConfirmation(jQuery(this))) {
                return;
            }

            event.preventDefault();
            event.stopImmediatePropagation();
        });

        jQuery(document).on("click", ".gf-accounts-discard-keep-editing", function(event) {
            event.preventDefault();
            griffinformsHideDiscardConfirmation();
            accountsPendingCloseTrigger = jQuery();
        });

        jQuery(document).on("click", ".gf-accounts-discard-confirm", function(event) {
            event.preventDefault();
            griffinformsDiscardUnsavedActiveRule();
            griffinformsHideDiscardConfirmation();
            accountsPendingCloseTrigger = jQuery();
            griffinformsHideAccountsModal();
        });

        jQuery(document).on("mousedown", function(event) {
            if (!accountsDiscardConfirmationHost.length || accountsDiscardConfirmationHost.hasClass("d-none")) {
                return;
            }

            const $target = jQuery(event.target);
            if ($target.closest("#griffinforms-accounts-discard-confirmation-host").length) {
                return;
            }

            if ($target.closest("#griffinforms-builder-modal-accounts-cancel-btn, " + accountsModalId + " .btn-close").length) {
                return;
            }

            griffinformsHideDiscardConfirmation();
            accountsPendingCloseTrigger = jQuery();
        });

        jQuery(document).on("click", "#griffinforms-accounts-guided-flow-nav .gf-guided-flow-back", function() {
            if (window.griffinformsAccountsState.isRequestInFlight || !griffinformsIsAccountsGuidedFlowActive()) {
                return;
            }

            if (window.griffinformsGuidedFlowShell && window.griffinformsAccountsState.guidedFlow) {
                window.griffinformsGuidedFlowShell.goBack(window.griffinformsAccountsState.guidedFlow);
            }
        });

        jQuery(document).on("click", "#griffinforms-accounts-guided-flow-nav .gf-guided-flow-next", function() {
            if (window.griffinformsAccountsState.isRequestInFlight || !griffinformsIsAccountsGuidedFlowActive()) {
                return;
            }

            if (window.griffinformsGuidedFlowShell && window.griffinformsAccountsState.guidedFlow) {
                window.griffinformsGuidedFlowShell.goNext(window.griffinformsAccountsState.guidedFlow);
            }
        });

        jQuery(document).on("click", "#griffinforms-builder-modal-accounts-action-btn", function() {
            if (window.griffinformsAccountsState.isRequestInFlight) {
                return;
            }

            const payload = window.griffinformsAccountsState.settings || { mode: "custom", settings: { rules: [] } };
            griffinformsBeginAccountsRequest();
            griffinformsSaveAccountRegistrationConfig(payload.settings || {}).done(function(response) {
                if (!response || !response.success) {
                    griffinformsShowAccountsMessage("danger", (response && response.data && response.data.msg) ? response.data.msg : ' . $failed_save_registration_label . ');
                    return;
                }

                window.griffinformsAccountsState.settings = response.data.settings || payload;
                window.griffinformsAccountsState.persistedRuleIds = griffinformsGetAccountsRules().map(function(rule) {
                    return rule && rule.id ? rule.id : null;
                }).filter(Boolean);
                window.griffinformsAccountsState.activeRuleId = null;
                griffinformsShowAccountsMessage("success", response.data.msg || ' . $user_registration_saved_label . ');
                griffinformsShowAccountsListScreen(true);
                document.dispatchEvent(new CustomEvent("form-updated", { detail: { type: "accounts", formId: ' . $form_id . ' } }));
            }).fail(function() {
                griffinformsShowAccountsMessage("danger", ' . $failed_save_registration_label . ');
            }).always(function() {
                griffinformsEndAccountsRequest();
            });
        });
        ';
    }
}
