(function($) {
    'use strict';
    $(document).ready(function() {
        PluginRecommendations.init();
    });
    var PluginRecommendations = {
        init: function() {
            this.bindEvents();
            this.initFilters();
            if (window.location.href.indexOf('wp-admin') !== -1) {
                this.checkRecommendedPluginsStatus();
            }
        },
        bindEvents: function() {
            $(document).on('click', '.install-plugin', this.installPlugin);
            $(document).on('click', '.activate-plugin', this.activatePlugin);
            $(document).on('click', '.update-plugin', this.updatePlugin);
            $(document).on('click', '.filter-tab', this.filterPlugins);
            $(document).on('click', '.install-dismiss, #install-dismiss', this.dismissInstallNotice);
            $(document).on('click', '#install-essential-plugins', this.bulkInstallEssential);
            $(document).on('click', '#install-recommended-plugins', this.bulkInstallRecommended);
            $(document).on('click', '#install-all-plugins', this.bulkInstallAll);
            $(document).on('click', '#update-all-plugins', this.updateAllPlugins);
        },
        initFilters: function() {
            this.updateFilterCounts();
        },
        installPlugin: function(e) {
            e.preventDefault();
            var $button = $(this);
            var slug = $button.data('slug');
            var isLocal = $button.data('is-local') === 1;
            $button.addClass('loading').prop('disabled', true);
            $.ajax({
                url: MagicalPluginActivation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'magical_plugin_activation_install_plugin',
                    slug: slug,
                    is_local: isLocal ? '1' : '0',
                    nonce: MagicalPluginActivation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.installed, 'success');
                        setTimeout(function() {
                            PluginRecommendations.updatePluginStatus(slug, 'inactive');
                            $button.removeClass('loading').trigger('click');
                        }, 1000);
                    } else {
                        PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.error, 'error');
                        $button.removeClass('loading').prop('disabled', false);
                    }
                },
                error: function() {
                    PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.error, 'error');
                    $button.removeClass('loading').prop('disabled', false);
                }
            });
        },
        activatePlugin: function(e) {
            e.preventDefault();
            var $button = $(this);
            var file = $button.data('file');
            var slug = $button.data('slug');
            $button.addClass('loading').prop('disabled', true);
            $.ajax({
                url: MagicalPluginActivation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'magical_plugin_activation_activate_plugin',
                    file: file,
                    nonce: MagicalPluginActivation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.activated, 'success');
                        setTimeout(function() {
                            PluginRecommendations.updatePluginStatus(slug, 'active');
                            PluginRecommendations.checkRecommendedPluginsStatus();
                            setTimeout(function() { location.reload(); }, 2000);
                        }, 1000);
                    } else {
                        PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.error, 'error');
                        $button.removeClass('loading').prop('disabled', false);
                    }
                },
                error: function() {
                    PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.error, 'error');
                    $button.removeClass('loading').prop('disabled', false);
                }
            });
        },
        updatePlugin: function(e) {
            e.preventDefault();
            var $button = $(this);
            var slug = $button.data('slug');
            var file = $button.data('file');
            var isLocal = $button.data('is-local') === 1;
            $button.addClass('loading').prop('disabled', true);
            $.ajax({
                url: MagicalPluginActivation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'magical_plugin_activation_update_plugin',
                    slug: slug,
                    file: file,
                    is_local: isLocal ? '1' : '0',
                    nonce: MagicalPluginActivation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.updated, 'success');
                        setTimeout(function() {
                            PluginRecommendations.updatePluginStatus(slug, 'active');
                            PluginRecommendations.checkRecommendedPluginsStatus();
                        }, 1000);
                    } else {
                        PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.error, 'error');
                        $button.removeClass('loading').prop('disabled', false);
                    }
                },
                error: function() {
                    PluginRecommendations.showMessage($button, MagicalPluginActivation.strings.error, 'error');
                    $button.removeClass('loading').prop('disabled', false);
                }
            });
        },
        filterPlugins: function(e) {
            e.preventDefault();
            var $tab = $(this);
            var filter = $tab.data('filter');
            $('.filter-tab').removeClass('active');
            $tab.addClass('active');
            $('.plugin-card').each(function() {
                var $card = $(this);
                var status = $card.data('status');
                var featured = $card.data('featured');
                var essential = $card.data('essential');
                var show = false;
                switch (filter) {
                    case 'all': show = true; break;
                    case 'featured': show = featured == 1; break;
                    case 'essential': show = essential == 1; break;
                    case 'active': show = status === 'active'; break;
                    case 'inactive': show = status === 'inactive'; break;
                    case 'not-installed': show = status === 'not-installed'; break;
                }
                if (show) { $card.removeClass('hidden').fadeIn(300); }
                else { $card.addClass('hidden').fadeOut(300); }
            });
            if (history.pushState) {
                var newUrl = window.location.href.split('?')[0] + '?page=magical-plugin-activation-plugins';
                if (filter !== 'all') { newUrl += '&filter=' + filter; }
                history.pushState(null, null, newUrl);
            }
        },
        updateFilterCounts: function() {
            var counts = { all: 0, featured: 0, essential: 0, active: 0, inactive: 0, 'not-installed': 0 };
            $('.plugin-card').each(function() {
                var $card = $(this);
                var status = $card.data('status');
                var featured = $card.data('featured');
                var essential = $card.data('essential');
                counts.all++;
                counts[status]++;
                if (featured == 1) counts.featured++;
                if (essential == 1) counts.essential++;
            });
            $('.filter-tab').each(function() {
                var $tab = $(this);
                var filter = $tab.data('filter');
                var count = counts[filter];
                var baseText = $tab.text().split(' (')[0];
                if (count > 0) { $tab.text(baseText + ' (' + count + ')'); }
                else { $tab.text(baseText); }
            });
        },
        showMessage: function($button, message, type) {
            var $card = $button.closest('.plugin-card');
            var $message = $('<div class="plugin-message"></div>')
                .text(message)
                .addClass(type === 'error' ? 'error' : '')
                .appendTo($card);
            setTimeout(function() { $message.addClass('show'); }, 100);
            setTimeout(function() {
                $message.removeClass('show');
                setTimeout(function() { $message.remove(); }, 300);
            }, 3000);
        },
        updatePluginStatus: function(slug, status) {
            var $card = $('.plugin-card[data-slug="' + slug + '"]');
            if (!$card.length) return;
            $card.attr('data-status', status)
                .removeClass('status-active status-inactive status-not-installed')
                .addClass('status-' + status);
            $card.find('.plugin-status').text(status.charAt(0).toUpperCase() + status.slice(1).replace('-', ' '));
            this.updateFilterCounts();
        },
        dismissInstallNotice: function(e) {
            e.preventDefault();
            var $button = $(this);
            var $notice = $button.closest('.notice');
            var noticeType = 'recommended';
            if ($notice.hasClass('magical-plugin-activation-pro-recommended-notice')) { noticeType = 'recommended'; }
            else if ($notice.hasClass('magical-plugin-activation-pro-update-notice')) { noticeType = 'update'; }
            else if ($notice.hasClass('magical-plugin-activation-pro-essential-notice')) { noticeType = 'install'; }
            if (noticeType === 'install') {
                if (!$button.data('confirm-dismiss')) {
                    $notice.find('.magical-plugin-activation-essential-warning').remove();
                    var warning = $('<div class="magical-plugin-activation-essential-warning" style="color:#b71c1c; margin-top:8px; font-weight:bold;">'+MagicalPluginActivation.strings.essentialWarning+'</div>');
                    $notice.find('p').append(warning);
                    $button.data('confirm-dismiss', true);
                    return;
                }
            }
            var requestData = {
                action: 'magical_plugin_activation_dismiss_plugin_notice',
                nonce: MagicalPluginActivation.nonce
            };
            if (noticeType === 'update') { requestData.action = 'magical_plugin_activation_dismiss_update_notice'; }
            else if (noticeType === 'install') { requestData.action = 'magical_plugin_activation_dismiss_install_notice'; }
            else { requestData.notice_type = noticeType; }
            $.post(MagicalPluginActivation.ajaxurl, requestData);
            $notice.fadeOut(300, function() { $(this).remove(); });
        },
        bulkInstallEssential: function(e) {
            e.preventDefault();
            var $button = $(this);
            $button.addClass('loading').prop('disabled', true);
            var $progress = $('<div class="bulk-install-progress active"><div class="progress-bar"><div class="progress-fill"></div></div><div class="progress-text">Preparing to install essential plugins...</div></div>');
            $button.after($progress);
            setTimeout(function() {
                $progress.find('.progress-fill').css('width', '30%');
                $progress.find('.progress-text').text('Installing essential plugins...');
            }, 200);
            setTimeout(function() {
                if ($progress.find('.progress-fill').css('width') === '30%') {
                    $progress.find('.progress-fill').css('width', '60%');
                    $progress.find('.progress-text').text('Activating plugins...');
                }
            }, 2000);
            setTimeout(function() {
                if ($progress.find('.progress-fill').css('width') === '60%') {
                    $progress.find('.progress-fill').css('width', '80%');
                    $progress.find('.progress-text').text('Finalizing installation...');
                }
            }, 4000);
            $.ajax({
                url: MagicalPluginActivation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'magical_plugin_activation_install_essential_plugins',
                    nonce: MagicalPluginActivation.nonce
                },
                success: function(response) {
                    $button.removeClass('loading').prop('disabled', false);
                    if (response.success) {
                        $progress.find('.progress-fill').css('width', '100%');
                        $progress.find('.progress-text').text('All essential plugins installed and activated!');
                        setTimeout(function() { $progress.fadeOut(300, function() { $(this).remove(); }); }, 2000);
                        $button.closest('.notice').fadeOut(300);
                        setTimeout(function() { location.reload(); }, 3000);
                    } else {
                        $progress.remove();
                    }
                },
                error: function() {
                    $button.removeClass('loading').prop('disabled', false);
                    $progress.remove();
                }
            });
        },
        bulkInstallRecommended: function(e) {
            e.preventDefault();
            var $button = $(this);
            $button.addClass('loading').prop('disabled', true);
            var $progress = $('<div class="bulk-install-progress active"><div class="progress-bar"><div class="progress-fill"></div></div><div class="progress-text">Preparing to install recommended plugins...</div></div>');
            $button.after($progress);
            setTimeout(function() {
                $progress.find('.progress-fill').css('width', '30%');
                $progress.find('.progress-text').text('Installing recommended plugins...');
            }, 200);
            setTimeout(function() {
                if ($progress.find('.progress-fill').css('width') === '30%') {
                    $progress.find('.progress-fill').css('width', '60%');
                    $progress.find('.progress-text').text('Activating plugins...');
                }
            }, 2000);
            setTimeout(function() {
                if ($progress.find('.progress-fill').css('width') === '60%') {
                    $progress.find('.progress-fill').css('width', '80%');
                    $progress.find('.progress-text').text('Finalizing installation...');
                }
            }, 4000);
            $.ajax({
                url: MagicalPluginActivation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'magical_plugin_activation_install_recommended_plugins',
                    nonce: MagicalPluginActivation.nonce
                },
                success: function(response) {
                    $button.removeClass('loading').prop('disabled', false);
                    if (response.success) {
                        $progress.find('.progress-fill').css('width', '100%');
                        $progress.find('.progress-text').text('All recommended plugins installed and activated!');
                        setTimeout(function() { $progress.fadeOut(300, function() { $(this).remove(); }); }, 2000);
                        $button.closest('.notice').fadeOut(300, function() { $(this).remove(); });
                        setTimeout(function() { location.reload(); }, 3000);
                    } else { $progress.remove(); }
                },
                error: function() {
                    $button.removeClass('loading').prop('disabled', false);
                    $progress.remove();
                }
            });
        },
        bulkInstallAll: function(e) {
            e.preventDefault();
            var $button = $(this);
            $button.addClass('loading').prop('disabled', true);
            var $progress = $('<div class="bulk-install-progress active"><div class="progress-bar"><div class="progress-fill"></div></div><div class="progress-text">Preparing to install plugins...</div></div>');
            $button.after($progress);
            setTimeout(function() {
                $progress.find('.progress-fill').css('width', '30%');
                $progress.find('.progress-text').text('Installing plugins...');
            }, 200);
            setTimeout(function() {
                if ($progress.find('.progress-fill').css('width') === '30%') {
                    $progress.find('.progress-fill').css('width', '60%');
                    $progress.find('.progress-text').text('Activating plugins...');
                }
            }, 2000);
            setTimeout(function() {
                if ($progress.find('.progress-fill').css('width') === '60%') {
                    $progress.find('.progress-fill').css('width', '80%');
                    $progress.find('.progress-text').text('Finalizing installation...');
                }
            }, 4000);
            $.ajax({
                url: MagicalPluginActivation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'magical_plugin_activation_install_all_plugins',
                    nonce: MagicalPluginActivation.nonce
                },
                success: function(response) {
                    $button.removeClass('loading').prop('disabled', false);
                    if (response.success) {
                        $progress.find('.progress-fill').css('width', '100%');
                        $progress.find('.progress-text').text('All plugins installed and activated!');
                        setTimeout(function() { $progress.fadeOut(300, function() { $(this).remove(); }); }, 2000);
                        $button.closest('.notice').fadeOut(300, function() { $(this).remove(); });
                        setTimeout(function() { location.reload(); }, 3000);
                    } else { $progress.remove(); }
                },
                error: function() {
                    $button.removeClass('loading').prop('disabled', false);
                    $progress.remove();
                }
            });
        },
        updateAllPlugins: function(e) {
            e.preventDefault();
            var $button = $(this);
            $button.addClass('loading').prop('disabled', true).text(MagicalPluginActivation.strings.updating);
            var $updateButtons = $('.update-plugin');
            var total = $updateButtons.length;
            var completed = 0;
            if (total === 0) {
                $button.removeClass('loading').prop('disabled', false);
                return;
            }
            $updateButtons.each(function() {
                var $updateBtn = $(this);
                var slug = $updateBtn.data('slug');
                var file = $updateBtn.data('file');
                var isLocal = $updateBtn.data('is-local');
                $.ajax({
                    url: MagicalPluginActivation.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'magical_plugin_activation_update_plugin',
                        slug: slug,
                        file: file,
                        is_local: isLocal,
                        nonce: MagicalPluginActivation.nonce
                    },
                    success: function(response) {
                        completed++;
                        if (response.success) { PluginRecommendations.updatePluginStatus(slug, 'active'); }
                        if (completed === total) {
                            setTimeout(function() {
                                $button.removeClass('loading').prop('disabled', false);
                                $('.magical-plugin-activation-pro-update-notice').fadeOut(300, function() { $(this).remove(); });
                                setTimeout(function() { window.location.reload(); }, 1500);
                            }, 500);
                        }
                    },
                    error: function() {
                        completed++;
                        if (completed === total) {
                            setTimeout(function() { $button.removeClass('loading').prop('disabled', false); }, 500);
                        }
                    }
                });
            });
        },
        checkRecommendedPluginsStatus: function() {
            $.ajax({
                url: MagicalPluginActivation.ajaxurl,
                type: 'POST',
                data: {
                    action: 'magical_plugin_activation_check_recommended_plugins_status',
                    nonce: MagicalPluginActivation.nonce
                },
                success: function(response) {
                    if (response.success && response.data.all_active) {
                        $('.magical-plugin-activation-pro-plugin-notice').fadeOut(300, function() { $(this).remove(); });
                    }
                }
            });
        }
    };
    window.PluginRecommendations = PluginRecommendations;
})(jQuery);
