import { useRouter } from "../../router/RouteContext.js";
import { useEnvironment } from "../../contexts/EnvironmentContext.js";
import { localizationKeys } from "../../localization/localizationKeys.js";
import { useCoreSignIn } from "../../contexts/CoreClientContext.js";
import { useCardState, withCardStateProvider } from "../../elements/contexts/index.js";
import { LoadingCard } from "../../elements/LoadingCard.js";
import { withRedirectToAfterSignIn, withRedirectToSignInTask } from "../../common/withRedirect.js";
import { ErrorCard } from "../../elements/ErrorCard.js";
import { determineStartingSignInFactor, factorHasLocalStrategy } from "./utils.js";
import { useAlternativeStrategies } from "../../hooks/useAlternativeStrategies.js";
import { useResetPasswordFactor } from "./useResetPasswordFactor.js";
import { AlternativeMethods } from "./AlternativeMethods.js";
import { hasMultipleEnterpriseConnections } from "./shared.js";
import { SignInFactorOneAlternativePhoneCodeCard } from "./SignInFactorOneAlternativePhoneCodeCard.js";
import { SignInFactorOneEmailCodeCard } from "./SignInFactorOneEmailCodeCard.js";
import { SignInFactorOneEmailLinkCard } from "./SignInFactorOneEmailLinkCard.js";
import { SignInFactorOneEnterpriseConnections } from "./SignInFactorOneEnterpriseConnections.js";
import { SignInFactorOneForgotPasswordCard } from "./SignInFactorOneForgotPasswordCard.js";
import { SignInFactorOnePasskey } from "./SignInFactorOnePasskey.js";
import { SignInFactorOnePasswordCard } from "./SignInFactorOnePasswordCard.js";
import { SignInFactorOnePhoneCodeCard } from "./SignInFactorOnePhoneCodeCard.js";
import React from "react";
import { useClerk } from "@clerk/shared/react";
import { jsx } from "@emotion/react/jsx-runtime";

//#region src/components/SignIn/SignInFactorOne.tsx
const factorKey = (factor) => {
	if (!factor) return "";
	let key = factor.strategy;
	if ("emailAddressId" in factor) key += factor.emailAddressId;
	if ("phoneNumberId" in factor) key += factor.phoneNumberId;
	if ("channel" in factor) key += factor.channel;
	return key;
};
function determineAlternativeMethodsMode(showForgotPasswordStrategies, passwordErrorCode) {
	if (!showForgotPasswordStrategies) return "default";
	if (passwordErrorCode === "pwned") return "pwned";
	if (passwordErrorCode === "compromised") return "passwordCompromised";
	return "forgot";
}
function SignInFactorOneInternal() {
	const { __internal_setActiveInProgress } = useClerk();
	const signIn = useCoreSignIn();
	const { preferredSignInStrategy } = useEnvironment().displayConfig;
	const availableFactors = signIn.supportedFirstFactors;
	const router = useRouter();
	const card = useCardState();
	const { supportedFirstFactors, firstFactorVerification } = useCoreSignIn();
	const lastPreparedFactorKeyRef = React.useRef("");
	const [{ currentFactor }, setFactor] = React.useState(() => {
		const factor = determineStartingSignInFactor(availableFactors, signIn.identifier, preferredSignInStrategy);
		if (factor?.strategy === "phone_code" && !!firstFactorVerification.channel && firstFactorVerification.channel !== "sms") factor.channel = firstFactorVerification.channel;
		return {
			currentFactor: factor,
			prevCurrentFactor: void 0
		};
	});
	const { hasAnyStrategy } = useAlternativeStrategies({
		filterOutFactor: currentFactor,
		supportedFirstFactors
	});
	const [showAllStrategies, setShowAllStrategies] = React.useState(() => !currentFactor || !factorHasLocalStrategy(currentFactor));
	const resetPasswordFactor = useResetPasswordFactor();
	const [showForgotPasswordStrategies, setShowForgotPasswordStrategies] = React.useState(false);
	const [passwordErrorCode, setPasswordErrorCode] = React.useState(null);
	React.useEffect(() => {
		if (__internal_setActiveInProgress) return;
		if (signIn.status === "needs_identifier" || signIn.status === null) router.navigate("../");
	}, [__internal_setActiveInProgress]);
	if (!currentFactor) return signIn.status ? /* @__PURE__ */ jsx(ErrorCard, {
		cardTitle: localizationKeys("signIn.noAvailableMethods.title"),
		cardSubtitle: localizationKeys("signIn.noAvailableMethods.subtitle"),
		message: localizationKeys("signIn.noAvailableMethods.message")
	}) : /* @__PURE__ */ jsx(LoadingCard, {});
	const toggleAllStrategies = hasAnyStrategy ? () => setShowAllStrategies((s) => !s) : void 0;
	const toggleForgotPasswordStrategies = () => setShowForgotPasswordStrategies((s) => !s);
	const handleFactorPrepare = () => {
		lastPreparedFactorKeyRef.current = factorKey(currentFactor);
	};
	const selectFactor = (factor) => {
		setFactor((prev) => ({
			currentFactor: factor,
			prevCurrentFactor: prev.currentFactor
		}));
	};
	/**
	* Prompt to choose between a list of enterprise connections as supported first factors
	* @experimental
	*/
	if (hasMultipleEnterpriseConnections(signIn.supportedFirstFactors)) return /* @__PURE__ */ jsx(SignInFactorOneEnterpriseConnections, {});
	if (showAllStrategies || showForgotPasswordStrategies) {
		const canGoBack = factorHasLocalStrategy(currentFactor) && !passwordErrorCode;
		const toggle = showAllStrategies ? toggleAllStrategies : toggleForgotPasswordStrategies;
		const backHandler = () => {
			card.setError(void 0);
			setPasswordErrorCode(null);
			toggle?.();
		};
		return /* @__PURE__ */ jsx(AlternativeMethods, {
			mode: determineAlternativeMethodsMode(showForgotPasswordStrategies, passwordErrorCode),
			onBackLinkClick: canGoBack ? backHandler : void 0,
			onFactorSelected: (f) => {
				selectFactor(f);
				toggle?.();
			},
			currentFactor
		});
	}
	if (!currentFactor) return /* @__PURE__ */ jsx(LoadingCard, {});
	switch (currentFactor?.strategy) {
		case "passkey": return /* @__PURE__ */ jsx(SignInFactorOnePasskey, {
			onFactorPrepare: handleFactorPrepare,
			onShowAlternativeMethodsClick: toggleAllStrategies
		});
		case "password": return /* @__PURE__ */ jsx(SignInFactorOnePasswordCard, {
			onForgotPasswordMethodClick: resetPasswordFactor ? toggleForgotPasswordStrategies : toggleAllStrategies,
			onShowAlternativeMethodsClick: toggleAllStrategies,
			onPasswordError: (errorCode) => {
				setPasswordErrorCode(errorCode);
				toggleForgotPasswordStrategies();
			}
		});
		case "email_code": return /* @__PURE__ */ jsx(SignInFactorOneEmailCodeCard, {
			factorAlreadyPrepared: lastPreparedFactorKeyRef.current === factorKey(currentFactor),
			onFactorPrepare: handleFactorPrepare,
			factor: currentFactor,
			onShowAlternativeMethodsClicked: toggleAllStrategies
		});
		case "phone_code": if (currentFactor.channel && currentFactor.channel !== "sms") return /* @__PURE__ */ jsx(SignInFactorOneAlternativePhoneCodeCard, {
			factorAlreadyPrepared: lastPreparedFactorKeyRef.current === factorKey(currentFactor),
			onFactorPrepare: handleFactorPrepare,
			factor: currentFactor,
			onChangePhoneCodeChannel: selectFactor
		});
		else return /* @__PURE__ */ jsx(SignInFactorOnePhoneCodeCard, {
			factorAlreadyPrepared: lastPreparedFactorKeyRef.current === factorKey(currentFactor),
			onFactorPrepare: handleFactorPrepare,
			factor: currentFactor,
			onShowAlternativeMethodsClicked: toggleAllStrategies
		});
		case "email_link": return /* @__PURE__ */ jsx(SignInFactorOneEmailLinkCard, {
			factorAlreadyPrepared: lastPreparedFactorKeyRef.current === factorKey(currentFactor),
			onFactorPrepare: handleFactorPrepare,
			factor: currentFactor,
			onShowAlternativeMethodsClicked: toggleAllStrategies
		});
		case "reset_password_phone_code": return /* @__PURE__ */ jsx(SignInFactorOneForgotPasswordCard, {
			factorAlreadyPrepared: lastPreparedFactorKeyRef.current === factorKey(currentFactor),
			onFactorPrepare: handleFactorPrepare,
			factor: currentFactor,
			onShowAlternativeMethodsClicked: toggleAllStrategies,
			onBackLinkClicked: () => {
				setFactor((prev) => ({
					currentFactor: prev.prevCurrentFactor,
					prevCurrentFactor: prev.currentFactor
				}));
				toggleForgotPasswordStrategies();
			},
			cardSubtitle: localizationKeys("signIn.forgotPassword.subtitle_phone")
		});
		case "reset_password_email_code": return /* @__PURE__ */ jsx(SignInFactorOneForgotPasswordCard, {
			factorAlreadyPrepared: lastPreparedFactorKeyRef.current === factorKey(currentFactor),
			onFactorPrepare: handleFactorPrepare,
			factor: currentFactor,
			onShowAlternativeMethodsClicked: toggleAllStrategies,
			onBackLinkClicked: () => {
				setFactor((prev) => ({
					currentFactor: prev.prevCurrentFactor,
					prevCurrentFactor: prev.currentFactor
				}));
				toggleForgotPasswordStrategies();
			},
			cardSubtitle: localizationKeys("signIn.forgotPassword.subtitle_email")
		});
		default: return /* @__PURE__ */ jsx(LoadingCard, {});
	}
}
const SignInFactorOne = withRedirectToSignInTask(withRedirectToAfterSignIn(withCardStateProvider(SignInFactorOneInternal)));

//#endregion
export { SignInFactorOne };
//# sourceMappingURL=SignInFactorOne.js.map