(function ($) {
    'use strict';

    function showMessage(text, isError) {
        var $msg = $('#maca-license-message');
        $msg.text(text).css('color', isError ? '#b32d2e' : '#00a32a');
    }

    $('#maca-activate-license').on('click', function () {
        var $btn = $(this);
        var key = $('#maca-license-key').val();

        $btn.prop('disabled', true);
        showMessage(macaMenulistProLicense.strings.activating, false);

        $.post(macaMenulistProLicense.ajaxUrl, {
            action: 'maca_menulist_activate_license',
            nonce: macaMenulistProLicense.nonce,
            license_key: key
        })
            .done(function (res) {
                if (res.success) {
                    window.location.reload();
                    return;
                }
                showMessage((res.data && res.data.message) || macaMenulistProLicense.strings.error, true);
                $btn.prop('disabled', false);
            })
            .fail(function () {
                showMessage(macaMenulistProLicense.strings.error, true);
                $btn.prop('disabled', false);
            });
    });

    $('#maca-start-trial').on('click', function () {
        var $btn = $(this);

        $btn.prop('disabled', true);
        showMessage(macaMenulistProLicense.strings.startingTrial, false);

        $.post(macaMenulistProLicense.ajaxUrl, {
            action: 'maca_menulist_start_trial',
            nonce: macaMenulistProLicense.nonce
        })
            .done(function (res) {
                if (res.success) {
                    window.location.reload();
                    return;
                }
                showMessage((res.data && res.data.message) || macaMenulistProLicense.strings.error, true);
                $btn.prop('disabled', false);
            })
            .fail(function () {
                showMessage(macaMenulistProLicense.strings.error, true);
                $btn.prop('disabled', false);
            });
    });

    $('#maca-deactivate-license').on('click', function () {
        if (!window.confirm('Remove the license from this site?')) {
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true);
        showMessage(macaMenulistProLicense.strings.deactivating, false);

        $.post(macaMenulistProLicense.ajaxUrl, {
            action: 'maca_menulist_deactivate_license',
            nonce: macaMenulistProLicense.nonce
        })
            .done(function (res) {
                if (res.success) {
                    window.location.reload();
                    return;
                }
                showMessage((res.data && res.data.message) || macaMenulistProLicense.strings.error, true);
                $btn.prop('disabled', false);
            })
            .fail(function () {
                showMessage(macaMenulistProLicense.strings.error, true);
                $btn.prop('disabled', false);
            });
    });
})(jQuery);
