'use strict';

(async () => {
  const form = document.getElementById('loginForm');
  const message = document.getElementById('loginMessage');
  const button = document.getElementById('loginButton');

  const existing = VegApi.getToken();
  if (existing) {
    try {
      await VegApi.request('/api/auth/me', { redirectOnUnauthorized: false });
      window.location.replace('/app/');
      return;
    } catch (_) {
      VegApi.clearToken();
    }
  }

  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    message.hidden = true;
    VegApi.setButtonLoading(button, true, 'جاري الدخول...');
    try {
      const result = await VegApi.request('/api/auth/login', {
        method: 'POST',
        redirectOnUnauthorized: false,
        body: {
          username: document.getElementById('username').value,
          password: document.getElementById('password').value,
        },
      });
      VegApi.setToken(result.token);
      window.location.replace('/app/');
    } catch (error) {
      message.textContent = error.message;
      message.hidden = false;
    } finally {
      VegApi.setButtonLoading(button, false);
    }
  });
})();
