<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Login – Alpine 5G Router</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
  <div class="login-wrap">
    <div class="login-card">
      <h1>Alpine 5G Router</h1>
      <p class="sub">Sign in to manage modem and network</p>
      <form id="loginForm">
        <div class="form-group">
          <label for="username">Username</label>
          <input type="text" id="username" name="username" autocomplete="username" required autofocus>
        </div>
        <div class="form-group">
          <label for="password">Password</label>
          <input type="password" id="password" name="password" autocomplete="current-password" required>
        </div>
        <div id="loginError" class="login-error"></div>
        <button type="submit" class="btn btn-primary" id="submitBtn">Sign in</button>
      </form>
    </div>
  </div>
  <script>
    const form = document.getElementById('loginForm');
    const errorEl = document.getElementById('loginError');
    const submitBtn = document.getElementById('submitBtn');

    function showError(msg) {
      errorEl.textContent = msg || 'Login failed';
      errorEl.classList.add('visible');
    }
    function hideError() {
      errorEl.textContent = '';
      errorEl.classList.remove('visible');
    }

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      hideError();
      submitBtn.disabled = true;
      const username = document.getElementById('username').value.trim();
      const password = document.getElementById('password').value;
      try {
        const res = await fetch('/api/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ username, password }),
        });
        const data = await res.json().catch(() => ({}));
        if (res.ok) {
          window.location.href = '{{ url_for("status_page") }}';
          return;
        }
        showError(data.error || 'Invalid username or password');
      } catch (err) {
        showError('Network error');
      } finally {
        submitBtn.disabled = false;
      }
    });
  </script>
</body>
</html>
