// Login page handler
(function () {
  const form = document.getElementById('login-form');
  const passwordInput = document.getElementById('password');
  const errorEl = document.getElementById('error');

  // If already authenticated, redirect
  const token = localStorage.getItem('cmux-remote-token');
  if (token) {
    fetch('/api/auth/verify', {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.valid) window.location.href = '/';
      })
      .catch(() => {});
  }

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    errorEl.classList.remove('visible');

    const password = passwordInput.value.trim();
    if (!password) return;

    const submitBtn = form.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.textContent = 'Connecting...';

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password }),
      });

      const data = await res.json();

      if (res.ok && data.token) {
        localStorage.setItem('cmux-remote-token', data.token);
        window.location.href = '/';
      } else {
        errorEl.textContent = data.error || 'Login failed';
        errorEl.classList.add('visible');
        passwordInput.value = '';
        passwordInput.focus();
        submitBtn.disabled = false;
        submitBtn.textContent = 'Connect';
      }
    } catch (err) {
      errorEl.textContent = 'Connection failed';
      errorEl.classList.add('visible');
      submitBtn.disabled = false;
      submitBtn.textContent = 'Connect';
    }
  });
})();
