(function ($) {
    'use strict';

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

    $('#maca-support-form').on('submit', function (event) {
        event.preventDefault();

        var $form = $(this);
        var $btn = $('#maca-support-submit');
        var subject = $.trim($('#maca-support-subject').val());
        var message = $.trim($('#maca-support-body').val());
        var email = $.trim($('#maca-support-email').val());

        if (!subject || !message || !email) {
            showMessage(macaMenulistProSupport.strings.validation, true);
            return;
        }

        $btn.prop('disabled', true);
        showMessage(macaMenulistProSupport.strings.sending, false);

        $.post(macaMenulistProSupport.ajaxUrl, {
            action: 'maca_menulist_submit_support',
            nonce: macaMenulistProSupport.nonce,
            name: $('#maca-support-name').val(),
            email: email,
            subject: subject,
            message: message,
            include_system_info: $('#maca-support-include-info').is(':checked') ? 1 : 0
        })
            .done(function (res) {
                if (res.success) {
                    showMessage(
                        (res.data && res.data.message) || macaMenulistProSupport.strings.success,
                        false
                    );
                    $form[0].reset();
                    $('#maca-support-include-info').prop('checked', true);
                    $btn.prop('disabled', false);
                    return;
                }

                showMessage(
                    (res.data && res.data.message) || macaMenulistProSupport.strings.error,
                    true
                );
                $btn.prop('disabled', false);
            })
            .fail(function (xhr) {
                var msg = macaMenulistProSupport.strings.error;
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    msg = xhr.responseJSON.data.message;
                }
                showMessage(msg, true);
                $btn.prop('disabled', false);
            });
    });
})(jQuery);
