import { useSignInContext } from "../../contexts/components/SignIn.js";
import { useCoreSignIn } from "../../contexts/CoreClientContext.js";
import { useCardState } from "../../elements/contexts/index.js";
import { handleError } from "../../utils/errorHandler.js";
import { useSupportEmail } from "../../hooks/useSupportEmail.js";
import { clerkInvalidFAPIResponse } from "@clerk/shared/internal/clerk-js/errors";
import { useCallback, useEffect } from "react";
import { useClerk } from "@clerk/shared/react";
import { isClerkRuntimeError, isUserLockedError } from "@clerk/shared/error";
import { __internal_WebAuthnAbortService } from "@clerk/shared/internal/clerk-js/passkeys";

//#region src/components/SignIn/shared.ts
function useHandleAuthenticateWithPasskey(onSecondFactor) {
	const card = useCardState();
	const { setActive, __internal_navigateWithError } = useClerk();
	const supportEmail = useSupportEmail();
	const { afterSignInUrl, navigateOnSetActive } = useSignInContext();
	const { authenticateWithPasskey } = useCoreSignIn();
	useEffect(() => {
		return () => {
			__internal_WebAuthnAbortService.abort();
		};
	}, []);
	return useCallback(async (...args) => {
		try {
			const res = await authenticateWithPasskey(...args);
			switch (res.status) {
				case "complete": return setActive({
					session: res.createdSessionId,
					navigate: async ({ session }) => {
						await navigateOnSetActive({
							session,
							redirectUrl: afterSignInUrl
						});
					}
				});
				case "needs_second_factor": return onSecondFactor();
				default: return console.error(clerkInvalidFAPIResponse(res.status, supportEmail));
			}
		} catch (err) {
			const { flow } = args[0] || {};
			if (isClerkRuntimeError(err)) {
				if (err.code === "passkey_operation_aborted") return;
				if (flow === "autofill" && err.code === "passkey_retrieval_cancelled") return;
			}
			if (isUserLockedError(err)) return __internal_navigateWithError("..", err.errors[0]);
			handleError(err, [], card.setError);
		}
	}, []);
}
/**
* Type guard that checks if all factors in the array are enterprise SSO factors
* with both `enterpriseConnectionId` and `enterpriseConnectionName` properties.
* This is used to determine if the user should be presented with a choice
* between multiple enterprise connections.
* @experimental
*/
function hasMultipleEnterpriseConnections(factors) {
	if (!factors?.length) return false;
	return factors.filter((factor) => factor.strategy === "enterprise_sso" && "enterpriseConnectionId" in factor && "enterpriseConnectionName" in factor).length > 1;
}

//#endregion
export { hasMultipleEnterpriseConnections, useHandleAuthenticateWithPasskey };
//# sourceMappingURL=shared.js.map