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

        // Steal BaseIntegrationModule from Elementor Pro Mailchimp
        const BaseIntegrationModule = Object.getPrototypeOf(CoolFormKit.modules.forms.mailchimp).constructor;

        function registerConditionalMailchimpModule(name, suffix) {

            const ConditionalMailchimpModule = BaseIntegrationModule.extend({

                getName() {
                    return name;
                },

                onElementChange(setting) {
                    switch (setting) {
                        case `mailchimp_api_key_source${suffix}`:
                        case `mailchimp_api_key${suffix}`:
                            this.onApiUpdate();
                            break;
                        case `mailchimp_list${suffix}`:
                            this.onMailchimpListUpdate();
                            break;
                    }
                },

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

                    if(!apiKeyControl && !globalKeyControl){
                        return
                    }
                    
                    if ('default' !== globalKeyControl.getControlValue() && '' === apiKeyControl.getControlValue()) {
                        self.updateOptions(`mailchimp_list${suffix}`, []);
                        self.getEditorControlView(`mailchimp_list${suffix}`).setValue('');
                        return;
                    }

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

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

                    self.getMailchimpCache('lists', 'lists', cacheKey).done(function (data) {
                        self.updateOptions(`mailchimp_list${suffix}`, data.lists);
                        self.updateMailchimpList();
                    }).fail(function (error) {
                        self.addControlError(`mailchimp_list${suffix}`, error);
                    }).always(function () {
                        self.removeControlSpinner(`mailchimp_list${suffix}`);
                    });
                },

                onMailchimpListUpdate() {
                    this.updateOptions(`mailchimp_groups${suffix}`, []);
                    this.getEditorControlView(`mailchimp_groups${suffix}`).setValue('');
                    this.updateMailchimpList();
                },

                updateMailchimpList() {
                    const self = this;
                    const controlView = self.getEditorControlView(`mailchimp_list${suffix}`);

                    if (!controlView.getControlValue()) return;

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

                    self.getMailchimpCache('list_details', 'list_details', controlView.getControlValue(), {
                        mailchimp_list: controlView.getControlValue() // ✅ FIX: always send correct key to PHP
                    }).done(function (data) {

                        self.updateOptions(`mailchimp_groups${suffix}`, data.list_details.groups);
                        self.getEditorControlView(`${name}_fields_map`).updateMap(data.list_details.fields);
                    }).fail(function (error) {
                        self.addControlError(`mailchimp_groups${suffix}`, error);
                    }).always(function () {
                        self.removeControlSpinner(`mailchimp_groups${suffix}`);
                    });

                    const args = {
                        type: 'fields',
                        action: 'fields',
                        cacheKey: controlView.getControlValue(),
                        args: {
                            mailchimp_list: controlView.getControlValue()
                        },
                        immediately: true
                    };

                    self.getMailchimpCache(...Object.values(args)).done(function (data) {
                        const fieldsMapControl = self.getEditorControlView(`${name}_fields_map`);
                        if (fieldsMapControl) {
                            fieldsMapControl.updateMap(data.fields);
                        }
                    });
                },

                getMailchimpCache(type, action, cacheKey, requestArgs) {
                    let immediately = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;

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

                    requestArgs = _.extend({}, requestArgs, {
                        service: name, 
                        conditional_mailchimp_action: action,
                        api_key: this.getEditorControlView(`mailchimp_api_key${suffix}`).getControlValue(),
                        use_global_api_key: this.getEditorControlView(`mailchimp_api_key_source${suffix}`).getControlValue()
                    });

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

                onSectionActive() {
                    BaseIntegrationModule.prototype.onSectionActive.apply(this, arguments);
                    this.onApiUpdate();
                }
            });

            CoolFormKit.modules.forms[name] = new ConditionalMailchimpModule('cool-form');

        }

        registerConditionalMailchimpModule('conditional_mailchimp', '_cond_mc');

        registerConditionalMailchimpModule('conditional_mailchimp_2', '_cond_mc_2');

        registerConditionalMailchimpModule('conditional_mailchimp_3', '_cond_mc_3');

        registerConditionalMailchimpModule('conditional_mailchimp_4', '_cond_mc_4');

        const maxModules = (typeof CoolMailchimpConfig !== 'undefined' && CoolMailchimpConfig.mailchimp_conditionally)
            ? CoolMailchimpConfig.mailchimp_conditionally
            : 5; 

        for (let i = 5; i <= maxModules; i++) {
            registerConditionalMailchimpModule(`conditional_mailchimp_${i}`, `_cond_mc_${i}`);
        }
        
        elementor.channels.editor.on('section:activated', function (sectionName, editor) {
            if (sectionName && sectionName.includes('mailchimp_cond')) {
                setTimeout(() => {
                    Object.keys(CoolFormKit.modules.forms).forEach(moduleName => {
                        if (moduleName.startsWith('conditional_mailchimp')) {
                            const moduleInstance = CoolFormKit.modules.forms[moduleName];
                            if (moduleInstance?.onSectionActive) {
                                moduleInstance.onSectionActive();
                            }
                        }
                    });
                }, 100);
            }
        });


    });
})(jQuery);
