/**
 * Blog Over — Plugin Install & Activate handler.
 *
 * Uses WordPress built-in wp.updates.installPlugin() API for reliable
 * plugin installation, then activates via the standard plugin activation URL.
 *
 * Based on the proven pattern from Formula theme.
 *
 * @package Blog_Over
 */

/* global blog_over_start_page */
/* global wp */

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

    var pluginInstall = {
        init: function () {
            this.handleInstall();
            this.handleActivate();
        },

        /**
         * Handle "Install and Activate" button clicks.
         */
        handleInstall: function () {
            var self = this;

            $('body').on('click', '.install-now', function (e) {
                e.preventDefault();

                var $btn = $(this);
                var slug = $btn.attr('data-slug');
                var url = $btn.attr('href');
                var redirect = $btn.data('redirect');

                $btn.text(wp.updates.l10n.installing);
                $btn.addClass('updating-message');

                wp.updates.installPlugin({
                    slug: slug,
                    success: function () {
                        $btn.text(blog_over_start_page.activating + '...');
                        self.activatePlugin(url, redirect);
                    }
                });
            });
        },

        /**
         * Handle "Activate" button clicks.
         */
        handleActivate: function () {
            var self = this;

            $('body').on('click', '.activate-now', function (e) {
                e.preventDefault();

                var $btn = $(this);
                var url = $btn.attr('href');
                var redirect = $btn.attr('data-redirect');

                $btn.addClass('updating-message');
                $btn.text(blog_over_start_page.activating + '...');

                self.activatePlugin(url, redirect);
            });
        },

        /**
         * Activate a plugin via its activation URL, then redirect or reload.
         */
        activatePlugin: function (url, redirect) {
            if (typeof url === 'undefined' || !url) {
                return;
            }

            $.ajax({
                async: true,
                type: 'GET',
                url: url,
                success: function () {
                    if (typeof redirect !== 'undefined' && redirect !== '') {
                        window.location.replace(redirect);
                    } else {
                        location.reload();
                    }
                },
                error: function () {
                    location.reload();
                }
            });
        }
    };

    pluginInstall.init();
});
