import React, { useEffect, useState } from 'react';
import { initSignInAuthProvider, getSignInAuthProvider, } from './signInAuthProvider';
import { LoadingIndicator } from '../../UI/loading/LoadingIndicator';
import { MsalProvider } from '@azure/msal-react';
import { useHistory } from 'react-router-dom';
import CustomNavigationClient from '../CustomNavigationClient';
import { useLocation } from 'react-use';
import UserProvider from './UserProvider';
import { useRouteRegistry } from '../../routes/routeRegistryStore';
import { matchPath } from 'react-router-dom';
const useIsRoutePublic = () => {
    var _a;
    const location = useLocation();
    const routeRegistry = useRouteRegistry();
    const patterns = Object.keys(routeRegistry.routeMap);
    const matchingPattern = patterns.find(pattern => matchPath(location.pathname, {
        path: pattern,
        exact: true,
        strict: false
    }));
    return matchingPattern
        ? (_a = routeRegistry.routeMap[matchingPattern]) === null || _a === void 0 ? void 0 : _a.isPublic
        : undefined;
};
export const AuthProvider = ({ children, doNotWaitForTenant = true }) => {
    const [msalInstance, setMsalInstance] = useState(null);
    const [isInitialized, setIsInitialized] = useState(false);
    const history = useHistory();
    const isRoutePublic = useIsRoutePublic();
    const resolvedIsPublic = isRoutePublic !== null && isRoutePublic !== void 0 ? isRoutePublic : true;
    useEffect(() => {
        const initialize = async () => {
            try {
                await initSignInAuthProvider();
                const authProvider = getSignInAuthProvider();
                const navigationClient = new CustomNavigationClient(history);
                authProvider.setNavigationClient(navigationClient);
                try {
                    const redirectResult = await authProvider.handleRedirectPromise();
                    if (redirectResult === null || redirectResult === void 0 ? void 0 : redirectResult.account) {
                        authProvider.setActiveAccount(redirectResult.account);
                    }
                }
                catch (error) {
                    console.error('[AuthProvider] Redirect handling failed:', error);
                }
                setMsalInstance(authProvider);
                setIsInitialized(true);
            }
            catch (error) {
                console.error('Failed to initialize AuthProvider:', error);
            }
        };
        initialize();
    }, [history]);
    if (!isInitialized) {
        return React.createElement(LoadingIndicator, null);
    }
    return (React.createElement(MsalProvider, { instance: msalInstance }, React.createElement(UserProvider, { isWhiteListed: resolvedIsPublic, doNotWaitForTenant: doNotWaitForTenant }, children)));
};
//# sourceMappingURL=AuthProvider.js.map