/**
 * Shared 6-digit TOTP input handler.
 * Auto-initializes on pages containing #tfaForm + .tfa-digit + #totp_code.
 */
document.addEventListener('DOMContentLoaded', function () {
    const digits = document.querySelectorAll('.tfa-digit');
    const hidden = document.getElementById('totp_code');
    const form = document.getElementById('tfaForm');
    if (!form || !hidden || digits.length === 0) return;
    let submitting = false;

    function collectCode() {
        let code = '';
        digits.forEach(function (d) { code += d.value; });
        hidden.value = code;
        return code;
    }

    digits.forEach(function (digit, i) {
        digit.addEventListener('input', function () {
            const val = this.value.replace(/\D/g, '');
            this.value = val.charAt(0) || '';
            this.classList.toggle('has-value', this.value !== '');

            if (this.value && i < digits.length - 1) {
                digits[i + 1].focus();
            }

            const code = collectCode();
            if (code.length === 6 && !submitting) {
                submitting = true;
                document.querySelector('.tfa-card').classList.add('tfa-verifying');
                setTimeout(function () { form.submit(); }, 200);
            }
        });

        digit.addEventListener('keydown', function (e) {
            if (e.key === 'Backspace' && !this.value && i > 0) {
                digits[i - 1].focus();
                digits[i - 1].value = '';
                digits[i - 1].classList.remove('has-value');
            }
        });

        digit.addEventListener('focus', function () {
            this.select();
        });

        digit.addEventListener('paste', function (e) {
            e.preventDefault();
            const pasted = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '').slice(0, 6);
            for (let j = 0; j < pasted.length && j < digits.length; j++) {
                digits[j].value = pasted[j];
                digits[j].classList.add('has-value');
            }
            if (pasted.length > 0 && pasted.length <= digits.length) {
                digits[Math.min(pasted.length, digits.length - 1)].focus();
            }

            const code = collectCode();
            if (code.length === 6 && !submitting) {
                submitting = true;
                document.querySelector('.tfa-card').classList.add('tfa-verifying');
                setTimeout(function () { form.submit(); }, 200);
            }
        });
    });
});
