'use strict';

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

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