import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import { BrowserRouter } from 'react-router-dom';
import { msalConfig } from './auth/AuthConfig.ts';
import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { AuthProvider } from './auth/AuthProvider.tsx';

// Initialize MSAL instance
const msalInstance = new PublicClientApplication(msalConfig);

// Handle initial setup for auth
async function initializeAuth() {
  try {
    // .initialize() must be called first
    await msalInstance.initialize();

    // Handle redirect response if coming back from login
    await msalInstance.handleRedirectPromise();

    // Default to user's first registered Microsoft account
    const accounts = msalInstance.getAllAccounts();
    if (accounts.length) {
      msalInstance.setActiveAccount(accounts[0]);
    }
  } catch (error) {
    console.error('MSAL initialization failed:', error);
  }
}

// Initialize auth and render app
initializeAuth().then(() => {
  createRoot(document.getElementById('root')!).render(
    <MsalProvider instance={msalInstance}>
      <BrowserRouter>
        <AuthProvider>
          <App instance={msalInstance} />
        </AuthProvider>
      </BrowserRouter>
    </MsalProvider>
  );
});
