Загрузка данных


const users = [
  { login: 'demo', password: '1234' },
  { login: 'alex', password: '1234' },
];

let authMode = 'register';

function setAuthMode(mode) {
  authMode = mode;
  const title = document.getElementById('authTitle');
  const sub = document.getElementById('authSub');
  const btn = document.getElementById('authActionBtn');
  const switchBtn = document.getElementById('switchAuthMode');
  
  if (mode === 'register') {
    title.textContent = 'Регистрация';
    sub.textContent = 'Создайте аккаунт';
    btn.textContent = 'Зарегистрироваться';
    switchBtn.textContent = 'Уже есть аккаунт? Войти';
  } else {
    title.textContent = 'Вход';
    sub.textContent = 'Войдите в свой аккаунт';
    btn.textContent = 'Войти';
    switchBtn.textContent = 'Нет аккаунта? Регистрация';
  }
  document.getElementById('authError').style.display = 'none';
}

function showAuthError(msg) {
  const el = document.getElementById('authError');
  el.textContent = msg;
  el.style.display = 'block';
}

function handleAuth() {
  const login = document.getElementById('authLogin').value.trim();
  const password = document.getElementById('authPassword').value.trim();
  
  if (login.length < 3) return showAuthError('Логин минимум 3 символа');
  if (password.length < 4) return showAuthError('Пароль минимум 4 символа');

  if (authMode === 'register') {
    if (users.some(u => u.login === login)) return showAuthError('Логин уже занят');
    users.push({ login, password });
    loginUser(login);
  } else {
    const found = users.find(u => u.login === login && u.password === password);
    if (!found) return showAuthError('Неверный логин или пароль');
    loginUser(login);
  }
}

function loginUser(login) {
  localStorage.setItem('currentUser', login);
  window.location.href = 'index.html';
}

function checkAuth() {
  const user = localStorage.getItem('currentUser');
  if (user && window.location.pathname.includes('auth.html')) {
    window.location.href = 'index.html';
  }
  if (!user && !window.location.pathname.includes('auth.html')) {
    window.location.href = 'auth.html';
  }
  return user;
}

document.addEventListener('DOMContentLoaded', function() {
  if (document.getElementById('authTitle')) {
    setAuthMode('register');
    
    document.getElementById('authActionBtn').addEventListener('click', handleAuth);
    document.getElementById('switchAuthMode').addEventListener('click', function() {
      setAuthMode(authMode === 'register' ? 'login' : 'register');
    });
    
    document.getElementById('authLogin').addEventListener('keydown', function(e) {
      if (e.key === 'Enter') handleAuth();
    });
    document.getElementById('authPassword').addEventListener('keydown', function(e) {
      if (e.key === 'Enter') handleAuth();
    });
  }
});