(function($) {
    'use strict';

    // Inicializar quando o DOM estiver pronto
    $(document).ready(function() {
        SibsAdmin.init();
    });

    const SibsAdmin = {
        init: function() {
            this.bindEvents();
            this.initFormValidation();
            this.initFileUpload();
        },

        bindEvents: function() {
            // Form submission com AJAX (opcional)
            $('.sibs-settings-form').on('submit', this.handleFormSubmission.bind(this));
            
            // Test blocks compatibility
            $('#sibs-test-blocks').on('click', this.testBlocksCompatibility.bind(this));
            
            // Migration buttons
            $('[name="migrate_to_blocks"]').closest('form').on('submit', this.confirmMigration.bind(this));
            $('[name="rollback_blocks"]').closest('form').on('submit', this.confirmRollback.bind(this));
        },

        initFormValidation: function() {
            // Validação em tempo real
            $('.sibs-input[required], .sibs-textarea[required]').on('blur', function() {
                const $field = $(this);
                const $group = $field.closest('.sibs-form-group');
                
                if (!$field.val().trim()) {
                    $group.addClass('has-error');
                    if (!$group.find('.error-message').length) {
                        $field.after('<span class="error-message" style="color: #dc3545; font-size: 0.875em;">' + 
                                   sibsAdmin.strings.required_field + '</span>');
                    }
                } else {
                    $group.removeClass('has-error');
                    $group.find('.error-message').remove();
                }
            });
        },

        initFileUpload: function() {
            $('.sibs-file-input').on('change', function() {
                const $input = $(this);
                const fileName = $input.val().split('\\').pop();
                const $helpText = $input.siblings('.sibs-help-text');
                
                if (fileName) {
                    $helpText.prepend('<strong style="color: #28a745;">' + 
                                    sibsAdmin.strings.selected_file + ': ' + fileName + '</strong><br>');
                }
            });
        },

        handleFormSubmission: function(e) {
            const $form = $(e.target);
            const $submitBtn = $form.find('button[type="submit"]');
            const originalText = $submitBtn.html();
            
            // Validação básica
            let hasErrors = false;
            $form.find('[required]').each(function() {
                if (!$(this).val().trim()) {
                    hasErrors = true;
                    $(this).focus();
                    return false;
                }
            });
            
            if (hasErrors) {
                this.showNotice(sibsAdmin.strings.required_fields, 'error');
                return false;
            }
            
            // Loading state
            $submitBtn.prop('disabled', true)
                     .html('<span class="dashicons dashicons-update spin"></span> ' + 
                           sibsAdmin.strings.saving);
            
            // Reset após envio (será executado independente do resultado)
            setTimeout(function() {
                $submitBtn.prop('disabled', false).html(originalText);
            }, 2000);
        },

        testBlocksCompatibility: function(e) {
            e.preventDefault();
            
            const $button = $(e.target);
            const $results = $('#sibs-test-results');
            const $output = $('#sibs-test-output');
            const originalText = $button.text();
            
            $button.prop('disabled', true).text(sibsAdmin.strings.testing);
            
            $.ajax({
                url: sibsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'sibs_test_blocks_compatibility',
                    nonce: sibsAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $output.html(response.data);
                        $results.slideDown();
                    } else {
                        SibsAdmin.showNotice(sibsAdmin.strings.test_failed, 'error');
                    }
                },
                error: function() {
                    SibsAdmin.showNotice(sibsAdmin.strings.ajax_error, 'error');
                },
                complete: function() {
                    $button.prop('disabled', false).text(originalText);
                }
            });
        },

        confirmMigration: function(e) {
            return confirm(sibsAdmin.strings.confirm_migrate);
        },

        confirmRollback: function(e) {
            return confirm(sibsAdmin.strings.confirm_rollback);
        },

        showNotice: function(message, type = 'info') {
            const $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
            $('.sibs-admin-wrap').prepend($notice);
            
            // Auto-hide after 5 seconds
            setTimeout(function() {
                $notice.fadeOut();
            }, 5000);
        }
    };

    // Tornar disponível globalmente
    window.SibsAdmin = SibsAdmin;

})(jQuery);