jQuery(document).ready(function ($) {
    'use strict';

    $('#mdi-import-button').on('click', function (e) {
        e.preventDefault();

        var button = $(this);
        var feedback = $('#mdi-feedback');

        // Disable button and show feedback
        button.attr('disabled', true).text('Importing...');
        feedback.show().html('Starting import process... Please wait.');

        // AJAX request
        $.ajax({
            url: mdi_ajax_obj.ajax_url,
            type: 'POST',
            data: {
                action: 'mdi_do_import', // Matches our PHP wp_ajax_ hook
                _ajax_nonce: mdi_ajax_obj.nonce // Security nonce
            },
            success: function (response) {
                if (response.success) {
                    // On success, show the log from the importer
                    feedback.append('<p style="color: green;"><strong>Success!</strong></p>');
                    feedback.append(response.data); // 'data' contains the output buffer from PHP
                    button.text('Import Complete!');
                    // Keep the button disabled to prevent re-import.
                } else {
                    // On failure, show the error message
                    feedback.append('<p style="color: red;"><strong>Error:</strong> ' + response.data + '</p>');
                    button.attr('disabled', false).text('Try Again');
                }
            },
            error: function (xhr, status, error) {
                // Handle server-side errors
                feedback.append('<p style="color: red;"><strong>Server Error:</strong> An unexpected error occurred. Check the browser console for more details.</p>');
                button.attr('disabled', false).text('Try Again');
                console.log(xhr.responseText);
            }
        });
    });
});