jQuery(document).ready(function ($) {
    $('#install-wpopus').on('click', function (e) {
        e.preventDefault();

        var $button = $(this);
        var $notice = $button.closest('.notice'); // Target the notice container

        // Prevent multiple clicks
        if ($button.prop('disabled')) return;

        // Clear previous messages
        $notice.find('.wpopus-message').remove();

        // Disable button and show loading text
        $button.prop('disabled', true).text('Installing...');

        $.ajax({
            url: wpopusAjax.ajax_url,
            method: 'POST',
            data: {
                action: 'install_wpopus_plugin',
                nonce: wpopusAjax.nonce,
            },
            success: function (responseText) {
                try {
                    // Extract JSON from the response
                    var jsonString = responseText.match(/\{.*\}/s); // Find JSON part
                    var response = jsonString ? JSON.parse(jsonString[0]) : null;

                    // Clear old messages before appending a new one
                    $notice.find('.wpopus-message').remove();

                    if (response && response.success && response.data) {
                        var message = response.data.message || 'Operation completed successfully.';
                        $notice.append('<p class="wpopus-message success">' + message + '</p>');
                        
                        // Update button style and text
                        $button.text(wpopusAjax.success_label).removeClass('button-primary').addClass('button-disabled');

                        // Redirect after a slight delay to let user see the success message
                        setTimeout(function () {
                            window.location.href = 'admin.php?page=wpopus';
                        }, 1000);
                    } else {
                        var message = response && response.data && response.data.message ? response.data.message : 
                                      'An error occurred. Please try again.';
                        $notice.append('<p class="wpopus-message error">' + message + '</p>');
                        $button.prop('disabled', false).text(wpopusAjax.label);
                    }
                } catch (error) {
                    console.error("JSON Parsing Error:", error);
                    $notice.append('<p class="wpopus-message error">Invalid response received. Please try again.</p>');
                    $button.prop('disabled', false).text(wpopusAjax.label);
                }
            },
            error: function () {
                $notice.append('<p class="wpopus-message error">An error occurred. Please try again.</p>');
                $button.prop('disabled', false).text(wpopusAjax.label);
            }
        });
    });
});
