jQuery(document).ready(function ($) {

    // AJAX Install Plugin from wordpress.org
    $('.speeinch-install-plugin').on('click', function (e) {
        e.preventDefault();
        var btn = $(this);
        var slug = btn.data('slug');
        var pluginFile = btn.data('plugin-file');
        var nonce = btn.data('nonce');

        btn.attr('disabled', true).text('Installing...');

        $.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'speeinch_install_plugin',
                slug: slug,
                security: nonce
            },
            success: function (response) {
                if (response.success) {
                    // Plugin installed — now show Activate button
                    btn.removeClass('speeinch-install-plugin')
                        .addClass('speeinch-activate-plugin')
                        .attr('disabled', false)
                        .text('Activate')
                        .data('nonce', speeinchBundle.activateNonce);
                } else {
                    btn.attr('disabled', false).text('Install Plugin');
                    alert('Install failed: ' + (response.data || 'Unknown error'));
                }
            },
            error: function (xhr) {
                btn.attr('disabled', false).text('Install Plugin');
                alert('Install request failed (HTTP ' + xhr.status + ')');
            }
        });
    });

    // AJAX Activate Plugin
    $(document).on('click', '.speeinch-activate-plugin', function (e) {
        e.preventDefault();
        var btn = $(this);
        var pluginFile = btn.data('plugin-file');
        var nonce = btn.data('nonce');

        btn.attr('disabled', true).text('Activating...');

        $.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {
                action: 'speeinch_activate_plugin',
                plugin_file: pluginFile,
                security: nonce
            },
            success: function (response) {
                if (response.success) {
                    // Replace button with grayed-out "Active"
                    btn.replaceWith('<span class="button" style="width: 100%; text-align: center; pointer-events: none; opacity: 0.7;">Active</span>');
                    // Update card border
                    btn.closest('.speeinch-bundle-card').css('border-color', '#2563eb');
                } else {
                    btn.attr('disabled', false).text('Activate');
                    alert('Activation failed: ' + (response.data || 'Unknown error'));
                }
            },
            error: function (xhr) {
                btn.attr('disabled', false).text('Activate');
                alert('Activation failed (HTTP ' + xhr.status + ')');
            }
        });
    });
});
