import { getSignInAuthProvider, initSignInAuthProvider } from "./signInAuthProvider.mjs";
import CustomNavigationClient from "../CustomNavigationClient.mjs";
import { useRouteRegistry } from "../../routes/routeRegistryStore.mjs";
import { LoadingIndicator } from "../../UI/loading/LoadingIndicator/LoadingIndicator.mjs";
import UserProvider from "./UserProvider.mjs";
import React, { useEffect, useState } from "react";
import { matchPath, useHistory } from "react-router-dom";
import { useLocation as useLocation$1 } from "react-use";
import { MsalProvider } from "@azure/msal-react";
//#region src/utilities/auth/AuthProvider.jsx
const useIsRoutePublic = () => {
	const location = useLocation$1();
	const routeRegistry = useRouteRegistry();
	const matchingPattern = Object.keys(routeRegistry.routeMap).find((pattern) => matchPath(location.pathname, {
		path: pattern,
		exact: true,
		strict: false
	}));
	return matchingPattern ? routeRegistry.routeMap[matchingPattern]?.isPublic : void 0;
};
const AuthProvider = ({ children, doNotWaitForTenant = true }) => {
	const [msalInstance, setMsalInstance] = useState(null);
	const [isInitialized, setIsInitialized] = useState(false);
	const history = useHistory();
	const resolvedIsPublic = useIsRoutePublic() ?? 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?.account) authProvider.setActiveAccount(redirectResult.account);
				} catch (error_0) {
					console.error("[AuthProvider] Redirect handling failed:", error_0);
				}
				setMsalInstance(authProvider);
				setIsInitialized(true);
			} catch (error) {
				console.error("Failed to initialize AuthProvider:", error);
			}
		};
		initialize();
	}, [history]);
	if (!isInitialized) return /* @__PURE__ */ React.createElement(LoadingIndicator, null);
	return /* @__PURE__ */ React.createElement(MsalProvider, { instance: msalInstance }, /* @__PURE__ */ React.createElement(UserProvider, {
		isWhiteListed: resolvedIsPublic,
		doNotWaitForTenant
	}, children));
};
//#endregion
export { AuthProvider };

//# sourceMappingURL=AuthProvider.mjs.map