const otpInputs = document.querySelectorAll('#otpInputsCont input');
const ResendCodeBtn = document.querySelector('.ResendCodeBtn');

let digitValidate = function (ele) {
    if (ele.value.length > 1) {
        ele.value = ele.value.slice(0, 1);
        ele.value = ele.value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
    }
    otpInpValidate();
}

function otpInpValidate() {
    let optValue = '';
    const checkCodeValidator = document.getElementById("checkCodeValidator");
    var valid = true;
    for (let i = 0; i < otpInputs.length; i++) {
        if (otpInputs[i].value.length < 1) {
            valid = false;
        } 
        optValue += otpInputs[i].value.toUpperCase();
    }
    
    if (valid == true) {
        // Put ajax here
        const OneTimeCodeEmail = document.getElementById("OneTimeCodeEmail");
        console.log(optValue)
        console.log(OneTimeCodeEmail.value)
        $.ajax({
            type: "POST",
            url: "launchpad.aspx/ValidateOTP",
            data: JSON.stringify({
                Otp: optValue,
                Email: OneTimeCodeEmail.value
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                console.log(response.d);
                if (response.d == "ok") {
                    location.reload();
                }
                else {

                }
            },
            failure: function (response) {
                console.log("Failed to validate OTP.");
            }
        });
        document.getElementById("checkingCodePrgrss").style.display = "block";
        setTimeout(() => {
            document.getElementById("checkingCodePrgrss").style.display = "none";
            checkCodeValidator.style.display = "flex";
        }, 3000);
    }
}

let tabChange = function (e, val) {
    if (!otpInputs[val]) return;

    const next = otpInputs[val + 1];
    const prev = otpInputs[val - 1];

    if (otpInputs[val].value != '' && next && e.keyCode != 8) {
        next.select();
        next.focus();
    } else if (otpInputs[val].value == '' && prev) {
        if (e.keyCode == 8 || e.keyCode == 46) {
            prev.select();
            prev.focus();
        }
    }

}

function checkKeys(e){
    if(e.keyCode == 8) return true;

    if(e.key.length === 1 && e.key.match(/[a-zA-Z]/i)) return true
    else if(e.key.length === 1 && e.key.match(/[0-9]/i)) return true

    return false
}

otpInputs.forEach((otpInput, index) => {
    const OtpInputIndex = index;
    otpInput.addEventListener('paste', (e) => {
        const clipboardData = e.clipboardData;
        const pastedData = clipboardData.getData('text/plain');
        let newPastedData = '';
        for (let i = 0; i < pastedData.length; i++) {
            if (pastedData[i] == ' ') {
                continue;
            }
            newPastedData += pastedData[i].replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
        }

        for (let i = 0; i < otpInputs.length; i++) {
            let otpCode = newPastedData.slice(i, i + 1)
            otpInputs[i].value = otpCode.toUpperCase();
            otpInpValidate();
        }
        otpInput.blur();
    })
    otpInput.addEventListener('keyup', (e) => {
        const isChar = checkKeys(e);


        tabChange(e, OtpInputIndex);
    })
    otpInput.addEventListener('input', (e) => {
        tabChange(e, OtpInputIndex);
        otpInpValidate();
    })
});


if(ResendCodeBtn){
    ResendCodeBtn.addEventListener('click', (e) => {
        const Target = e.currentTarget;
    
        if (Target.classList.contains('CodeResent')) return false;
        Target.classList.add('CodeResent');
        Target.innerText = "Code sent!";
        setTimeout(() => {
            Target.classList.remove('CodeResent');
            Target.innerText = "resend code.";
        }, 1500);
    })
}

document.getElementById('CloseNavPopUpBtn').addEventListener('click', (e) => {
    document.getElementById('OneTimeCodeEmail').classList.remove('border-red');
})
