let currentStep = 1;
let setupData = null;

function openSetup2FAModal() {
   document.getElementById('setup2FAModal').classList.remove('hidden');
   document.body.style.overflow = 'hidden';
   goToStep(1);
}

function closeSetup2FAModal() {
   document.getElementById('setup2FAModal').classList.add('hidden');
   document.body.style.overflow = 'auto';
   resetSetup();
}

function openDisable2FAModal() {
   document.getElementById('disable2FAModal').classList.remove('hidden');
   document.body.style.overflow = 'hidden';
   document.getElementById('disableCode').focus();
}

function closeDisable2FAModal() {
   document.getElementById('disable2FAModal').classList.add('hidden');
   document.body.style.overflow = 'auto';
   document.getElementById('disableError').classList.add('hidden');
   document.getElementById('disableCode').value = '';
}

async function startSetup() {
   const loadingDiv = document.getElementById('qrcode');
   loadingDiv.innerHTML = '<div class="animate-pulse text-gray-400">Loading...</div>';
   
   try {
       const response = await fetch('setup_2fa_ajax.php', {
           method: 'POST',
           headers: { 
               'Content-Type': 'application/json',
               'X-Requested-With': 'XMLHttpRequest'
           }
       });
       
       setupData = await response.json();
       console.log("Setup response:", setupData);
       
       if (setupData.success) {
           document.getElementById('qrcode').innerHTML = setupData.qrCode;
           document.getElementById('secretKey').textContent = setupData.secret;
           goToStep(2);
       } else {
           showError(setupData.error || 'Setup failed');
       }
   } catch (error) {
       console.error('Setup error:', error);
       showError('Connection error');
   }
}

async function verifySetup() {
   const code = document.getElementById('verificationCode').value.trim();
   
   if (!code || code.length !== 6 || !/^\d+$/.test(code)) {
       showError('Please enter a valid 6-digit code');
       return;
   }

   try {
       const response = await fetch('verify_2fa_setup.php', {
           method: 'POST',
           headers: { 
               'Content-Type': 'application/json',
               'X-Requested-With': 'XMLHttpRequest'
           },
           body: JSON.stringify({ code })
       });
       
       const result = await response.json();
       console.log("Verify response:", result);

       if (result.success) {
           displayBackupCodes(result.backupCodes);
           goToStep(4);
       } else {
           showError(result.error || 'Invalid verification code');
           document.getElementById('verificationCode').select();
       }
   } catch (error) {
       console.error('Verification error:', error);
       showError('Verification failed');
   }
}

async function disableTwoFactor() {
   const code = document.getElementById('disableCode').value.trim();
   
   if (!code || code.length !== 6 || !/^\d+$/.test(code)) {
       showDisableError('Please enter a valid 6-digit code');
       return;
   }

   try {
       const response = await fetch('disable_2fa.php', {
           method: 'POST',
           headers: { 
               'Content-Type': 'application/json',
               'X-Requested-With': 'XMLHttpRequest'
           },
           body: JSON.stringify({ code })
       });
       
       const result = await response.json();
       console.log("Disable response:", result);

       if (result.success) {
           window.location.reload();
       } else {
           showDisableError(result.error || 'Invalid code');
           document.getElementById('disableCode').select();
       }
   } catch (error) {
       console.error('Disable error:', error);
       showDisableError('Disable failed');
   }
}

function goToStep(step) {
   document.querySelectorAll('.step').forEach(el => {
       el.classList.add('hidden');
   });
   document.getElementById(`step${step}`).classList.remove('hidden');
   currentStep = step;
   
   if (step === 3) {
       document.getElementById('verificationCode').focus();
   }
}

function showError(message) {
   const errorDiv = document.getElementById('verificationError');
   errorDiv.textContent = message;
   errorDiv.classList.remove('hidden');
}

function showDisableError(message) {
   const errorDiv = document.getElementById('disableError');
   errorDiv.textContent = message;
   errorDiv.classList.remove('hidden');
}

function displayBackupCodes(codes) {
   const container = document.getElementById('backupCodes');
   container.innerHTML = codes.map(code => 
       `<div class="px-3 py-2 bg-black/20 rounded text-yellow-400 font-mono text-center">${code}</div>`
   ).join('');
}

function downloadCodes() {
   const codes = Array.from(document.querySelectorAll('#backupCodes div'))
       .map(div => div.textContent)
       .join('\n');
   
   const blob = new Blob([`Your 2FA Backup Codes:\n\n${codes}`], { type: 'text/plain' });
   const url = window.URL.createObjectURL(blob);
   const a = document.createElement('a');
   a.href = url;
   a.download = '2fa-backup-codes.txt';
   document.body.appendChild(a);
   a.click();
   window.URL.revokeObjectURL(url);
   document.body.removeChild(a);
}

function resetSetup() {
   currentStep = 1;
   setupData = null;
   document.querySelectorAll('.step').forEach(el => el.classList.add('hidden'));
   document.getElementById('step1').classList.remove('hidden');
   document.getElementById('verificationCode').value = '';
   document.getElementById('verificationError')?.classList.add('hidden');
}

function finishSetup() {
   window.location.reload();
}

// Event Listeners
document.addEventListener('DOMContentLoaded', function() {
   // Input handlers
   const numericInputs = document.querySelectorAll('input[type="text"]');
   numericInputs.forEach(input => {
       input.addEventListener('input', function(e) {
           this.value = this.value.replace(/[^0-9]/g, '');
           if (this.value.length === this.maxLength && this.id === 'verificationCode') {
               verifySetup();
           }
       });
   });

   // Enter key handlers
   document.getElementById('verificationCode')?.addEventListener('keypress', function(e) {
       if (e.key === 'Enter' && this.value.length === 6) {
           verifySetup();
       }
   });

   document.getElementById('disableCode')?.addEventListener('keypress', function(e) {
       if (e.key === 'Enter' && this.value.length === 6) {
           disableTwoFactor();
       }
   });

   // Escape key handler
   document.addEventListener('keydown', function(e) {
       if (e.key === 'Escape') {
           if (!document.getElementById('setup2FAModal').classList.contains('hidden')) {
               closeSetup2FAModal();
           }
           if (!document.getElementById('disable2FAModal').classList.contains('hidden')) {
               closeDisable2FAModal();
           }
       }
   });
});