const inputs = document.querySelectorAll('.code-input');
const form = document.querySelector('form');

inputs.forEach((input, index) => {
    input.addEventListener('input', (e) => {
        // Allow only numbers
        let value = e.target.value.replace(/\D/g, ''); // Remove non-digits

        // Only set the cleaned value (in case user pasted multiple)
        e.target.value = value;

        if (value.length === 1) {
            if (index < inputs.length - 1) {
                inputs[index + 1].focus();
            } else {
                form.submit(); // Submit form when last input is filled
            }
        }
    });

    input.addEventListener('keydown', (e) => {
        if (e.key === "Backspace" && !e.target.value && index > 0) {
            inputs[index - 1].focus();
        }
    });

    input.addEventListener('paste', (e) => {
        e.preventDefault();
        const pasteData = (e.clipboardData || window.clipboardData).getData('text');
        const digits = pasteData.replace(/\D/g, '').substring(0, inputs.length);
        digits.split('').forEach((char, i) => {
            inputs[i].value = char;
        });

        if (digits.length === inputs.length) {
            form.submit(); // Submit form if paste fills all inputs
        } else {
            inputs[digits.length].focus();
        }
    });
});