(function ($) {
    'use strict';

    const SifencyAdmin = {
        init: function() {
            this.bindEvents();
        },

        bindEvents: function() {
            // Settings Saving Events
            $(document).on('change', '.sifency-ajax-save[type="checkbox"]', this.handleCheckboxChange.bind(this));
            $(document).on('keyup', '.sifency-ajax-save.sifency-textarea', this.debounce(this.handleTextInput.bind(this), 1000));
            $(document).on('click', '#sifency-reset-cpt-defaults', this.handleResetDefaults.bind(this));
            
            // Rollback Events
            $(document).on('click', '.sifency-rollback-btn', this.handleRollback.bind(this));
        },

        debounce: function(func, wait) {
            let timeout;
            return function (...args) {
                const context = this;
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(context, args), wait);
            };
        },

        // --- Settings Logic ---

        handleCheckboxChange: function(e) {
            this.sendSettingsRequest(e.target);
        },

        handleTextInput: function(e) {
            this.sendSettingsRequest(e.target);
        },

        sendSettingsRequest: function(inputElement) {
            const $input = $(inputElement);
            const settingIdentifier = $input.data('setting');
            if (!settingIdentifier) return;

            const settingValue = $input.is(':checkbox') ? ($input.is(':checked') ? 'on' : 'off') : $input.val();
            const $feedback = $('#sifency-ajax-feedback');
            
            this.showFeedback($feedback, 'loading', sifencyAdminParams.texts.saving);

            const data = {
                action: 'sifency_save_admin_data',
                nonce: sifencyAdminParams.nonce,
                param3: settingValue
            };

            if (settingIdentifier.includes('|')) {
                const parts = settingIdentifier.split('|');
                data.param1 = parts[0];
                data.param2 = parts[1];
            } else {
                data.param1 = settingIdentifier;
                data.param2 = '';
            }

            $.post(sifencyAdminParams.ajax_url, data, (response) => {
                if (response.success) {
                    this.showFeedback($feedback, 'success', sifencyAdminParams.texts.saved);
                    this.updateModuleCardUI($input, settingIdentifier);
                } else {
                    this.showFeedback($feedback, 'error', 'Error: ' + (response.data ? response.data.message : 'Unknown'));
                }
            }).fail((jqXHR) => {
                this.showFeedback($feedback, 'error', 'Server Error');
            });
        },

        updateModuleCardUI: function($input, settingIdentifier) {
            if ($input.hasClass('sifency-cpt-module-toggle')) {
                const $card = $input.closest('.sifency-module-card');
                const $status = $card.find('.sifency-module-status');
                const isNowEnabled = $input.is(':checked');
                
                if (isNowEnabled) {
                    $status.removeClass('status-disabled').addClass('status-enabled').text(sifencyAdminParams.texts.enabled);
                } else {
                    $status.removeClass('status-enabled').addClass('status-disabled').text(sifencyAdminParams.texts.disabled);
                }
            }
        },

        handleResetDefaults: function(e) {
            e.preventDefault();
            if (!confirm(sifencyAdminParams.texts.confirm_reset)) return;
            
            const $feedback = $('#sifency-ajax-feedback');
            this.showFeedback($feedback, 'loading', sifencyAdminParams.texts.resetting);
            
            const data = {
                action: 'sifency_save_admin_data',
                nonce: sifencyAdminParams.nonce,
                param1: 'cpt_reset_defaults',
                param2: '',
                param3: 'reset'
            };
            
            $.post(sifencyAdminParams.ajax_url, data, (response) => {
                if (response.success) {
                    this.showFeedback($feedback, 'success', sifencyAdminParams.texts.reset_success);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    this.showFeedback($feedback, 'error', response.data.message);
                }
            });
        },

        // --- Rollback Logic ---

        handleRollback: function(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const version = $btn.data('version');
            const nonce = $btn.data('nonce');

            if (!confirm(sifencyAdminParams.texts.confirm_rollback + ' ' + version + '?')) return;

            $btn.prop('disabled', true).text(sifencyAdminParams.texts.rolling_back);

            $.ajax({
                url: sifencyAdminParams.ajax_url,
                type: 'POST',
                data: {
                    action: 'sifency_rollback_version',
                    version: version,
                    nonce: nonce
                },
                success: (response) => {
                    if (response.success) {
                        alert(sifencyAdminParams.texts.rollback_success);
                        location.reload();
                    } else {
                        alert(sifencyAdminParams.texts.rollback_failed + ' ' + (response.data ? response.data.message : ''));
                        $btn.prop('disabled', false).text(sifencyAdminParams.texts.rollback_btn);
                    }
                },
                error: () => {
                    alert(sifencyAdminParams.texts.server_error);
                    $btn.prop('disabled', false).text(sifencyAdminParams.texts.rollback_btn);
                }
            });
        },

        showFeedback: function($el, type, message) {
            let className = 'notice-info';
            if (type === 'success') className = 'notice-success';
            if (type === 'error') className = 'notice-error';

            $el.html('<p>' + message + '</p>')
               .removeClass('notice-error notice-success notice-info')
               .addClass('notice ' + className)
               .fadeIn();

            if (type !== 'loading') {
                setTimeout(() => {
                    $el.fadeOut(() => $el.removeClass('notice-error notice-success notice-info').html(''));
                }, 2000);
            }
        }
    };

    $(document).ready(function() {
        SifencyAdmin.init();
    });

})(jQuery);