import { createRoot } from 'react-dom/client';
import { PublicClientApplication, EventType, EventMessage, AuthenticationResult } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { msalConfig } from './lib/msalConfig';
import App from './App.tsx';
import './index.css';

/**
 * Initialize MSAL instance
 * This must be done before rendering the app
 */
export const msalInstance = new PublicClientApplication(msalConfig);

// Initialize the MSAL instance
msalInstance.initialize().then(() => {
  // Handle redirect promise (for redirect flow)
  msalInstance.handleRedirectPromise().then((response) => {
    if (response) {
      // Set the active account after redirect
      msalInstance.setActiveAccount(response.account);
    }
  }).catch((error) => {
    console.error('Redirect error:', error);
  });

  // Set up event callbacks
  msalInstance.addEventCallback((event: EventMessage) => {
    if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
      const payload = event.payload as AuthenticationResult;
      msalInstance.setActiveAccount(payload.account);
    }
  });

  // Check if there's already an active account
  const accounts = msalInstance.getAllAccounts();
  if (accounts.length > 0 && !msalInstance.getActiveAccount()) {
    // Set the first account as active if none is set
    msalInstance.setActiveAccount(accounts[0]);
  }

  // Render the app wrapped in MsalProvider
  createRoot(document.getElementById("root")!).render(
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  );
});
