import "jstree/dist/themes/default/style.min.css";
import "./vendor/w2ui/w2ui.css";
import "./styles/base.css";
import { api } from "./services/api";
import { getToken, setCurrentUser, setSession, clearSession } from "./services/authState";
import type { AuthBootstrapResponse, AuthUser } from "./types";
import { renderLogin } from "./pages/login/login";
import { renderApp } from "./pages/app/layout";

async function bootstrap() {
  try {
    const boot = await api<AuthBootstrapResponse>("/api/auth/bootstrap");
    if (boot.mode === "fixed") {
      document.body.dataset.authMode = "fixed";
      setSession(boot.token, boot.user);
      await renderApp();
      return;
    }
    delete document.body.dataset.authMode;
  } catch {
    delete document.body.dataset.authMode;
    clearSession();
  }

  if (!getToken()) {
    renderLogin(renderApp);
    return;
  }
  try {
    const result = await api<{ user: AuthUser }>("/api/auth/me");
    setCurrentUser(result.user);
    await renderApp();
  } catch {
    clearSession();
    renderLogin(renderApp);
  }
}

bootstrap();
