(function ($) {
    $(window).on('elementor:init', function () {

        // ✅ Grab the BaseIntegrationModule prototype from Elementor Pro’s GetResponse module
        const BaseIntegrationModule = Object.getPrototypeOf(elementorPro.modules.forms.getresponse).constructor;

        /**
         * Registers a conditional GetResponse integration module
         * @param {string} name - Module name
         * @param {string} suffix - Field suffix (e.g., "_cond_rp")
         */
        function registerConditionalGetresponseModule(name, suffix) {

            const ConditionalGetresponseModule = BaseIntegrationModule.extend({

                getName() {
                    return name;
                },

                onElementChange(setting) {
                    switch (setting) {
                        case `getresponse_api_key_source${suffix}`:
                        case `getresponse_custom_api_key${suffix}`:
                            this.onApiUpdate();
                            break;

                        case `getresponse_list${suffix}`:
                            this.onGetresponseListUpdate();
                            break;
                    }
                },

                onApiUpdate() {
                    const self = this;
                    const apiKeyControl = self.getEditorControlView(`getresponse_custom_api_key${suffix}`);
                    const globalKeyControl = self.getEditorControlView(`getresponse_api_key_source${suffix}`);

                    if (!apiKeyControl || !globalKeyControl) return;

                    // If using a non-default global key but no custom key → clear lists
                    if ('default' !== globalKeyControl.getControlValue() && '' === apiKeyControl.getControlValue()) {
                        self.updateOptions(`getresponse_list${suffix}`, []);
                        const listControl = self.getEditorControlView(`getresponse_list${suffix}`);
                        if (listControl) listControl.setValue('');
                        return;
                    }

                    self.resetControlIndicators(`getresponse_list${suffix}`);
                    self.addControlSpinner(`getresponse_list${suffix}`);

                    const cacheKey = self.getCacheKey({
                        type: 'lists',
                        controls: [globalKeyControl.getControlValue(), apiKeyControl.getControlValue()]
                    });

                    self.getGetresponseCache('lists', 'lists', cacheKey).done(function (data) {
                        self.updateOptions(`getresponse_list${suffix}`, data.lists || []);
                        self.updateGetresponseList();
                    }).fail(function (error) {
                        self.addControlError(`getresponse_list${suffix}`, error);
                    }).always(function () {
                        self.removeControlSpinner(`getresponse_list${suffix}`);
                    });
                },

                onGetresponseListUpdate() {
                    // When list changes, just reload field mappings
                    this.updateGetresponseList();
                },

                updateGetresponseList() {
                    const self = this;
                    const listControl = self.getEditorControlView(`getresponse_list${suffix}`);

                    if (!listControl || !listControl.getControlValue()) return;

                    self.addControlSpinner(`${name}_fields_map`);

                    const cacheKey = self.getCacheKey({
                        type: 'fields',
                        controls: [listControl.getControlValue()]
                    });

                    self.getGetresponseCache('fields', 'get_fields', cacheKey, {
                        getresponse_list: listControl.getControlValue()
                    }).done(function (data) {
                        const fieldsMap = self.getEditorControlView(`${name}_fields_map`);
                        if (fieldsMap && data.fields) {
                            fieldsMap.updateMap(data.fields);
                        }
                    }).fail(function (error) {
                        self.addControlError(`${name}_fields_map`, error);
                    }).always(function () {
                        self.removeControlSpinner(`${name}_fields_map`);
                    });
                },

                // ✅ Backward compatibility alias to prevent Elementor's internal call error
                updatGetResonseList() {
                    this.updateGetresponseList();
                },

                getGetresponseCache(type, action, cacheKey, requestArgs = {}, immediately = false) {
                    if (_.has(this.cache[type], cacheKey)) {
                        const data = {};
                        data[type] = this.cache[type][cacheKey];
                        return jQuery.Deferred().resolve(data);
                    }

                    requestArgs = _.extend({}, requestArgs, {
                        service: 'getresponse',
                        getresponse_action: action,
                        api_key: this.getEditorControlView(`getresponse_api_key_source${suffix}`).getControlValue(),
                        custom_api_key: this.getEditorControlView(`getresponse_custom_api_key${suffix}`).getControlValue()
                    });

                    return this.fetchCache(type, cacheKey, requestArgs, immediately);
                },

                onSectionActive() {
                    // Call parent safely, then refresh API/list
                    BaseIntegrationModule.prototype.onSectionActive.apply(this, arguments);
                    this.onApiUpdate();
                }
            });

            // ✅ Register module under Elementor Pro forms namespace
            elementorPro.modules.forms[name] = new ConditionalGetresponseModule('form');
        }

        // Register initial modules
        registerConditionalGetresponseModule('conditional_getresponse', '_cond_rp');
        registerConditionalGetresponseModule('conditional_getresponse_2', '_cond_rp_2');
        registerConditionalGetresponseModule('conditional_getresponse_3', '_cond_rp_3');
        registerConditionalGetresponseModule('conditional_getresponse_4', '_cond_rp_4');

        // Optionally register extra modules dynamically
        const maxModules = (typeof CoolGetresponseConfig !== 'undefined' && CoolGetresponseConfig.getresponse_conditionally)
            ? CoolGetresponseConfig.getresponse_conditionally
            : 5;

        for (let i = 5; i <= maxModules; i++) {
            registerConditionalGetresponseModule(`conditional_getresponse_${i}`, `_cond_rp_${i}`);
        }

        // ✅ Auto-trigger refresh when GetResponse conditional sections are activated
        elementor.channels.editor.on('section:activated', function (sectionName) {
            if (sectionName && sectionName.includes('getresponse_cond')) {
                setTimeout(() => {
                    Object.entries(elementorPro.modules.forms).forEach(([moduleName, moduleInstance]) => {
                        if (moduleName.startsWith('conditional_getresponse') && moduleInstance?.onSectionActive) {
                            moduleInstance.onSectionActive();
                        }
                    });
                }, 100);
            }
        });

    });
})(jQuery);
