/**
 * Auth UI handlers module
 * Following the pattern from static/js/watchlist.js (global exports)
 */

async function handleLogin(event) {
  event.preventDefault();
  
  const username = document.getElementById('loginUsername').value;
  const password = document.getElementById('loginPassword').value;
  const button = document.getElementById('loginSubmit');
  
  if (!button) {
    console.error('Login button not found');
    return;
  }
  
  const originalText = button.textContent;
  setLoading('loginSubmit', true, { loadingText: 'Connexion...', originalText });
  
  try {
    const data = await window.authApi.login(username, password);
    
    if (data.access_token) {
      window.setToken(data.access_token);
      localStorage.setItem('user', JSON.stringify(data.user));
      window.displaySuccess('authSuccess', 'Connexion réussie! Redirection...');
      setTimeout(() => {
        window.location.href = '/web';
      }, 1000);
    }
  } catch (error) {
    window.displayError('authError', error.message || 'Erreur lors de la connexion');
  } finally {
    setLoading('loginSubmit', false, { originalText });
  }
}

async function handleRegister(event) {
  event.preventDefault();
  
  const username = document.getElementById('registerUsername').value;
  const password = document.getElementById('registerPassword').value;
  const passwordConfirm = document.getElementById('registerPasswordConfirm').value;
  const email = document.getElementById('registerEmail').value || null;
  const full_name = document.getElementById('registerFullName').value || null;
  
  if (password !== passwordConfirm) {
    window.displayError('authError', 'Les mots de passe ne correspondent pas');
    return;
  }
  
  const button = document.getElementById('registerSubmit');
  if (!button) {
    console.error('Register button not found');
    return;
  }
  
  const originalText = button.textContent;
  setLoading('registerSubmit', true, { loadingText: 'Inscription...', originalText });
  
  try {
    const data = await window.authApi.register(username, password, email, full_name);
    
    window.displaySuccess('authSuccess', 'Inscription réussie! Vous pouvez maintenant vous connecter.');
    
    setTimeout(() => {
      window.authUi.switchTab('login');
      document.getElementById('loginUsername').value = username;
    }, 1500);
  } catch (error) {
    window.displayError('authError', error.message || 'Erreur lors de l\'inscription');
  } finally {
    setLoading('registerSubmit', false, { originalText });
  }
}

function setLoading(buttonId, isLoading, options = {}) {
  const button = document.getElementById(buttonId);
  if (!button) {
    return;
  }

  const defaultLoadingText = '...';
  const loadingText = options.loadingText || defaultLoadingText;

  if (isLoading) {
    const origText = options.originalText || button.textContent;
    button.dataset.originalText = origText;
    button.textContent = loadingText;
    button.disabled = true;
  } else {
    const origText = button.dataset.originalText || options.originalText || 'Se connecter';
    button.textContent = origText;
    button.disabled = false;
  }
}

function resetLoading(buttonId, originalText) {
  setLoading(buttonId, false, { originalText });
}

function switchTab(tab) {
  const tabs = document.querySelectorAll('.auth-tab');
  const forms = document.querySelectorAll('.auth-form');

  tabs.forEach(t => t.classList.remove('active'));
  forms.forEach(f => f.classList.remove('active'));

  if (tab === 'login') {
    tabs[0].classList.add('active');
    document.getElementById('loginForm').classList.add('active');
  } else {
    tabs[1].classList.add('active');
    document.getElementById('registerForm').classList.add('active');
  }

  document.getElementById('authError').classList.remove('show');
  document.getElementById('authSuccess').classList.remove('show');
}

window.authUi = {
  handleLogin,
  handleRegister,
  setLoading,
  resetLoading,
  switchTab,
};
