function formatTime(seconds) {
    var minutes = Math.floor(seconds / 60);
    var secs = seconds % 60;

    return (minutes < 10 ? "0" : "") + minutes + ":" +
        (secs < 10 ? "0" : "") + secs;
}

function executeMfa(url, requestId, selectedMfaId, expirationTime, startTimerBeforeRequest, timerInterval) {
    if (startTimerBeforeRequest) {
        startTimer(expirationTime, timerInterval);
    }
    $.post(url,
        { requestId: requestId, selectedMfaId: selectedMfaId },
        function (result) {

        })
        .done(function (result) {
            if (result.IsRedirect) {
                //Error For MFA License
                window.location.href = result.Data;
            }
            if (result.Success && result.IsOTP && expirationTime) {
                startTimer(expirationTime, timerInterval);
            }
            if (!result.Success) {
                clearInterval(timerInterval);
            }
        })
        .fail(function (response) {
            OnAuthenticationError(response);
        })
        .always(function () {
            $("#mfaLinkModalV2").modal("hide");
            $("#mfaAvailableSelection").modal("hide");
        });
}

function startTimer(duration, timerInterval) {
    clearInterval(timerInterval); // prevent multiple timers

    var timeLeft = duration;

    timerInterval = setInterval(function () {
        $("#lblTimeout").text(formatTime(timeLeft));

        if (timeLeft <= 0) {
            clearInterval(timerInterval);
            $("#btnCancel").click();
        }

        timeLeft--;
    }, 1000);
}

// Cancel MFA Request
function cancelMfaRequest(url, redirectMessageText) {
    //url = '@Url.Action("CancelMfa", "Mfa", new { area = "VGAccount" })'
    const data = {
        RequestId: $("#RequestId").val(),
        MfaId: $("#MfaId").val()
    };
    performMfaAction(url, data, redirectMessageText);
}

function updateRedirectMessage(label, redirectMessageText, timeLeft) {
    let redirectMessage = redirectMessageText;
    redirectMessage = redirectMessage.replace("{0}", timeLeft);
    label.text(redirectMessage);
}

// Common AJAX handler
function performMfaAction(url, data, redirectMessageText) {
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        success: function (response) {
            if (response.isRedirect && response.redirectUrl) {
                handleRedirect(response.redirectUrl, response.isCancelled, redirectMessageText);
                return;
            }

            handleError(response);
        },
        error: function () {
            showError("Something went wrong. Please try again.");
        }
    });
}

function handleRedirect(url, isCancelled, redirectMessageText) {
    if (isCancelled) {
        $(".mfa-timeout-active").removeClass("d-flex").addClass("d-none");
        startRedirectTimer(url, redirectMessageText);
        return;
    }

    window.location.href = url;
}
function handleError(response) {
    $("#dvError").removeClass("d-none");
    $("#dvInfo").addClass("d-none");
    if (response.isCancelled) {
        $(".mfa-timeout-active").addClass("d-none");
    }
    showError(response.message || "Something went wrong");
}

function showError(message) {
    $("#dvError").text(message);
}

// Redirect countdown (5 seconds)
function startRedirectTimer(redirectUrl, redirectMessageText) {

    clearInterval(timerInterval);

    let timeLeft = 5;
    const label = $("#dvError");
    label.removeClass("d-none");
    updateRedirectMessage(label, redirectMessageText, timeLeft);

    const timer = setInterval(function () {

        timeLeft--;
        updateRedirectMessage(label, redirectMessageText, timeLeft);

        if (timeLeft <= 0) {
            clearInterval(timer);
            window.location.href = redirectUrl;
        }

    }, 1000);
}