/**
 * OTP Input Logic
 */
document.addEventListener('DOMContentLoaded', () => {
  const inputs = document.querySelectorAll('.otp-input');
  
  if (inputs.length === 0) return;

  inputs[0].focus();

  inputs.forEach((input, index) => {
    // Keydown event for backspace and navigation
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Backspace') {
        input.value = '';
        if (index > 0) {
          inputs[index - 1].focus();
        }
      } else if (e.key === 'ArrowLeft' && index > 0) {
        inputs[index - 1].focus();
      } else if (e.key === 'ArrowRight' && index < inputs.length - 1) {
        inputs[index + 1].focus();
      }
    });

    // Input event for typing
    input.addEventListener('input', (e) => {
      const val = e.target.value;
      if (val.length > 1) {
        e.target.value = val.slice(0, 1);
      }
      if (val !== '' && index < inputs.length - 1) {
        inputs[index + 1].focus();
      }
      
      checkAllFilled();
    });

    // Paste event
    input.addEventListener('paste', (e) => {
      e.preventDefault();
      const pastedData = e.clipboardData.getData('text').slice(0, inputs.length).trim();
      if (!/^\d+$/.test(pastedData)) return; // Ensure numbers only

      let i = 0;
      for (const char of pastedData) {
        if (i < inputs.length) {
          inputs[i].value = char;
          i++;
        }
      }
      
      if (i < inputs.length) {
        inputs[i].focus();
      } else {
        inputs[inputs.length - 1].focus();
      }
      checkAllFilled();
    });
  });

  function checkAllFilled() {
    const allFilled = Array.from(inputs).every(input => input.value !== '');
    if (allFilled) {
      // Auto submit or trigger event
      const form = inputs[0].closest('form');
      if (form) {
        // Optional: auto submit
        // form.submit();
        console.log('OTP Filled');
      }
    }
  }
});
