import React from 'react';
import ReactDOM from 'react-dom/client';
import { HashRouter } from 'react-router-dom';
import App from './App';
import './styles.css';
import './portfolio.css';

/**
 * After signing in, Microsoft sends the browser back with the result in the address
 * (#code=…&state=…). The app uses #/… for its pages, so that result goes to the sign-in
 * library first; then the app opens on the page you signed in from.
 */
function isAuthResponse(): boolean {
  const h = location.hash;
  const hashAuth = h.length > 1 && !h.startsWith('#/') && /(^#|&)(code|error|state)=/.test(h);
  const queryAuth = /[?&](code|error)=/.test(location.search) && /[?&]state=/.test(location.search);
  return hashAuth || queryAuth;
}

async function boot() {
  if (isAuthResponse()) {
    try {
      const { getMsal } = await import('./lib/sync/graph');
      await getMsal();
    } catch (e) {
      console.error('Sign-in could not be completed', e);
      sessionStorage.setItem('pm.signinError', String((e as Error)?.message ?? e));
    }
    let back = '#/settings';
    try {
      back = sessionStorage.getItem('pm.returnTo') || back;
      sessionStorage.removeItem('pm.returnTo');
    } catch {}
    history.replaceState(null, '', location.pathname + back);
  }
  ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
      <HashRouter>
        <App />
      </HashRouter>
    </React.StrictMode>
  );
}
boot();
