(function ($) {
    'use strict';

    function renderNotice(message, type) {
        var cssClass = type === 'error' ? 'notice notice-error' : 'notice notice-success';

        $('#ug-two-factor-setup-notice').remove();

        if (!message) {
            return;
        }

        $('#ug-two-factor-setup-target').before(
            '<div id="ug-two-factor-setup-notice" class="' + cssClass + ' is-dismissible"><p>' + message + '</p></div>'
        );
    }

    function getErrorMessage(response, fallback) {
        if (response && response.data && response.data.message) {
            return response.data.message;
        }

        return fallback;
    }

    function request(action, data) {
        return $.post(ultraguardTwoFactor.ajaxUrl, $.extend({
            action: action,
            nonce: ultraguardTwoFactor.nonce
        }, data || {}));
    }

    $(document).on('click', '[data-ug-2fa-setup]', function (event) {
        event.preventDefault();
        renderNotice('', 'success');

        request('ultraguard_2fa_setup_begin').done(function (response) {
            if (!response || !response.success) {
                renderNotice(getErrorMessage(response, ultraguardTwoFactor.i18n.setupFailed), 'error');
                return;
            }

            var codes = (response.data.backup_codes || []).map(function (code) {
                return '<code>' + code + '</code>';
            }).join('');
            var qrMarkup = response.data.qr_datauri
                ? '<div><img src="' + response.data.qr_datauri + '" alt="' + ultraguardTwoFactor.i18n.qrAlt + '"><p><a href="' + response.data.qr_datauri + '" target="_blank" rel="noopener noreferrer">' + ultraguardTwoFactor.i18n.openQr + '</a></p></div>'
                : '';

            var html = '' +
                '<div class="ultraguard-two-factor-setup">' +
                qrMarkup +
                '<div>' +
                '<p>' + ultraguardTwoFactor.i18n.scanInstructions + '</p>' +
                '<p><strong>Secret:</strong> <code>' + response.data.secret + '</code></p>' +
                '<p>' + ultraguardTwoFactor.i18n.verifyInstructions + '</p>' +
                '<p><label>' + ultraguardTwoFactor.i18n.codeLabel + ' <input type="text" id="ug-2fa-verify-code" inputmode="numeric" autocomplete="one-time-code" maxlength="6"></label></p>' +
                '<p><button class="button button-primary" id="ug-2fa-confirm">Confirm</button></p>' +
                '<p><strong>' + ultraguardTwoFactor.i18n.backupCodesTitle + '</strong></p>' +
                '<p>' + ultraguardTwoFactor.i18n.backupCodesHelp + '</p>' +
                '<div class="ultraguard-two-factor-codes">' + codes + '</div>' +
                '</div>' +
                '</div>';

            renderNotice(response.data.message, 'success');
            $('#ug-two-factor-setup-target').html(html);
        }).fail(function (xhr) {
            renderNotice(getErrorMessage(xhr.responseJSON, ultraguardTwoFactor.i18n.setupFailed), 'error');
        });
    });

    $(document).on('click', '#ug-2fa-confirm', function (event) {
        event.preventDefault();
        var code = $('#ug-2fa-verify-code').val();
        renderNotice('', 'success');

        request('ultraguard_2fa_setup_verify', { code: code }).done(function (response) {
            if (!response || !response.success) {
                renderNotice(getErrorMessage(response, ultraguardTwoFactor.i18n.setupFailed), 'error');
                return;
            }

            renderNotice(response.data.message || ultraguardTwoFactor.i18n.setupConfirmed, 'success');

            request('ultraguard_2fa_setup_complete').done(function (completeResponse) {
                if (completeResponse && completeResponse.success) {
                    renderNotice(completeResponse.data.message || ultraguardTwoFactor.i18n.setupConfirmed, 'success');
                    window.location.reload();
                    return;
                }

                renderNotice(getErrorMessage(completeResponse, ultraguardTwoFactor.i18n.setupFailed), 'error');
            }).fail(function (xhr) {
                renderNotice(getErrorMessage(xhr.responseJSON, ultraguardTwoFactor.i18n.setupFailed), 'error');
            });
        }).fail(function (xhr) {
            renderNotice(getErrorMessage(xhr.responseJSON, ultraguardTwoFactor.i18n.setupFailed), 'error');
        });
    });
})(jQuery);
