import { useRouter } from "../../router/RouteContext.js";
import { useFetch } from "../../hooks/useFetch.js";
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 { VerificationCodeCard } from "../../elements/VerificationCodeCard.js";
import { clerkInvalidFAPIResponse } from "@clerk/shared/internal/clerk-js/errors";
import { useMemo } from "react";
import { useClerk } from "@clerk/shared/react";
import { jsx } from "@emotion/react/jsx-runtime";
import { isUserLockedError } from "@clerk/shared/error";

//#region src/components/SignIn/SignInFactorOneCodeForm.tsx
const SignInFactorOneCodeForm = (props) => {
	const signIn = useCoreSignIn();
	const card = useCardState();
	const { navigate } = useRouter();
	const { afterSignInUrl, navigateOnSetActive } = useSignInContext();
	const { setActive } = useClerk();
	const supportEmail = useSupportEmail();
	const clerk = useClerk();
	const shouldAvoidPrepare = signIn.firstFactorVerification.status === "verified" && props.factorAlreadyPrepared;
	const cacheKey = useMemo(() => {
		const factor = props.factor;
		let factorKey = factor.strategy;
		if ("emailAddressId" in factor) factorKey += `_${factor.emailAddressId}`;
		if ("phoneNumberId" in factor) factorKey += `_${factor.phoneNumberId}`;
		if ("channel" in factor && factor.channel) factorKey += `_${factor.channel}`;
		return {
			name: "signIn.prepareFirstFactor",
			factorKey
		};
	}, [
		props.factor.strategy,
		"emailAddressId" in props.factor ? props.factor.emailAddressId : void 0,
		"phoneNumberId" in props.factor ? props.factor.phoneNumberId : void 0,
		"channel" in props.factor ? props.factor.channel : void 0
	]);
	const goBack = () => {
		return navigate("../");
	};
	const prepare = () => {
		if (shouldAvoidPrepare) return;
		signIn.prepareFirstFactor(props.factor).then(() => props.onFactorPrepare()).catch((err) => handleError(err, [], card.setError));
	};
	useFetch(shouldAvoidPrepare ? void 0 : () => signIn?.prepareFirstFactor(props.factor), cacheKey, {
		staleTime: 100,
		onSuccess: () => props.onFactorPrepare(),
		onError: (err) => handleError(err, [], card.setError)
	});
	const action = (code, resolve, reject) => {
		signIn.attemptFirstFactor({
			strategy: props.factor.strategy,
			code
		}).then(async (res) => {
			await resolve();
			switch (res.status) {
				case "complete": return setActive({
					session: res.createdSessionId,
					navigate: async ({ session }) => {
						await navigateOnSetActive({
							session,
							redirectUrl: afterSignInUrl
						});
					}
				});
				case "needs_second_factor": return navigate("../factor-two");
				case "needs_new_password": return navigate("../reset-password");
				default: return console.error(clerkInvalidFAPIResponse(res.status, supportEmail));
			}
		}).catch((err) => {
			if (isUserLockedError(err)) return clerk.__internal_navigateWithError("..", err.errors[0]);
			return reject(err);
		});
	};
	return /* @__PURE__ */ jsx(VerificationCodeCard, {
		cardTitle: props.cardTitle,
		cardSubtitle: props.cardSubtitle,
		inputLabel: props.inputLabel,
		resendButton: props.resendButton,
		onCodeEntryFinishedAction: action,
		onResendCodeClicked: prepare,
		safeIdentifier: props.factor.safeIdentifier,
		profileImageUrl: signIn.userData.imageUrl,
		onShowAlternativeMethodsClicked: props.onShowAlternativeMethodsClicked,
		showAlternativeMethods: props.showAlternativeMethods,
		onIdentityPreviewEditClicked: goBack,
		onBackLinkClicked: props.onBackLinkClicked
	});
};

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