import React from 'react';
import ReactDOM from 'react-dom/client';
import { PublicClientApplication, EventType } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import App from './App.js';
import { msalConfig } from './authConfig.js';
import { UserProvider } from "./context/UserContext.js";

const msalInstance = new PublicClientApplication(msalConfig);

try {
  await msalInstance.initialize();
  try {
    const response = await msalInstance.handleRedirectPromise();
    if (response) {
      msalInstance.setActiveAccount(response.account);
    }
  } catch (error) {
    console.error("Redirect error: ", error);
  }

  if (!msalInstance.getActiveAccount() && msalInstance?.getAllAccounts().length > 0) {
    msalInstance.setActiveAccount(msalInstance?.getAllAccounts()[0]);
  }

  msalInstance.enableAccountStorageEvents();
  msalInstance.addEventCallback((event) => {
    if (event.eventType === EventType.LOGIN_SUCCESS && event.payload.account) {
      const {account} = event.payload;
      msalInstance.setActiveAccount(account);
    }
  });

  ReactDOM.createRoot(document.getElementById('root')).render(
    <MsalProvider instance={msalInstance}>
      <UserProvider>
        <App />
      </UserProvider>
    </MsalProvider>
  );
} catch (error) {
  console.error("Initialization error: ", error);
}
