import { apiPost, authFetchStatus } from '../api.js';

const loadingEl = document.getElementById('page-loading');
const panel = document.getElementById('bootstrap-panel');

async function init() {
  let st;
  try {
    st = await authFetchStatus();
  } catch {
    st = { needsBootstrap: false, loggedIn: false };
  }
  if (!st.needsBootstrap) {
    location.href = st.loggedIn ? '/start.html' : '/login.html';
    return;
  }

  loadingEl.hidden = true;
  panel.hidden = false;

  document.getElementById('form-boot').onsubmit = async (e) => {
    e.preventDefault();
    const fd = new FormData(e.target);
    await apiPost('/auth/bootstrap', {
      username: fd.get('username'),
      password: fd.get('password'),
    });
    location.href = '/start.html';
  };
}

init();
