import { localizationKeys } from "../../../localization/localizationKeys.js";
import duotone_at_symbol_default from "../../../icons/duotone-at-symbol.js";
import exclamation_triangle_default from "../../../icons/exclamation-triangle.js";
import { useLocalizations } from "../../../localization/makeLocalizable.js";
import { descriptors } from "../../../customizables/elementDescriptors.js";
import { useCardState } from "../../../elements/contexts/index.js";
import { Flow } from "../../../customizables/Flow.js";
import { Col, Heading, Icon, Input, Text } from "../../../customizables/index.js";
import { handleError } from "../../../utils/errorHandler.js";
import { useFieldOTP } from "../../../elements/CodeControl.js";
import { Form } from "../../../elements/Form.js";
import { useConfigureSSO } from "../ConfigureSSOContext.js";
import { useWizard } from "../elements/Wizard/WizardContext.js";
import { Wizard } from "../elements/Wizard/Wizard.js";
import { Step } from "../elements/Step.js";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useReverification, useSession, useUser } from "@clerk/shared/react";
import { Fragment as Fragment$1, jsx, jsxs } from "@emotion/react/jsx-runtime";

//#region src/components/ConfigureSSO/steps/VerifyDomainStep.tsx
const VerifyDomainStep = () => {
	const { user } = useUser();
	const { session } = useSession();
	const { enterpriseConnection } = useConfigureSSO();
	const { t } = useLocalizations();
	const { goNext: outerGoNext } = useWizard();
	const emailToVerify = user?.primaryEmailAddress ?? user?.emailAddresses?.find((e) => e.verification.status !== "verified");
	const isVerified = emailToVerify?.verification.status === "verified";
	const activeOrganizationId = session?.lastActiveOrganizationId ?? null;
	const isDomainTakenByOtherOrg = Boolean(isVerified && enterpriseConnection && enterpriseConnection.organizationId !== activeOrganizationId);
	const wasVerifiedOnMountRef = useRef(isVerified);
	const emailAddressRef = useRef(emailToVerify);
	const preExistingEmailIdRef = useRef(emailToVerify?.id);
	const initialInnerStepIdRef = useRef(emailToVerify ? "verify-email-address" : "provide-email");
	if (isDomainTakenByOtherOrg) {
		const conflictingDomain = enterpriseConnection?.domains[0];
		return /* @__PURE__ */ jsx(Flow.Part, {
			part: "verifyDomain",
			children: /* @__PURE__ */ jsx(Step, { children: /* @__PURE__ */ jsxs(Col, {
				justify: "center",
				align: "center",
				sx: (t$1) => ({
					gap: t$1.space.$3,
					alignItems: "center",
					flex: 1
				}),
				children: [/* @__PURE__ */ jsx(Icon, {
					icon: exclamation_triangle_default,
					sx: (t$1) => ({
						width: t$1.sizes.$8,
						height: t$1.sizes.$8,
						color: t$1.colors.$neutralAlpha600
					})
				}), /* @__PURE__ */ jsxs(Col, {
					gap: 1,
					sx: (t$1) => ({
						textAlign: "center",
						maxWidth: t$1.sizes.$94
					}),
					children: [/* @__PURE__ */ jsx(Heading, {
						textVariant: "h1",
						sx: (t$1) => ({
							fontSize: t$1.fontSizes.$lg,
							textWrap: "balance"
						}),
						localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.domainTaken.title", { domain: conflictingDomain })
					}), /* @__PURE__ */ jsx(Text, {
						as: "p",
						variant: "body",
						colorScheme: "secondary",
						localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.domainTaken.subtitle")
					})]
				})]
			}) })
		});
	}
	if (wasVerifiedOnMountRef.current && emailToVerify?.emailAddress) return /* @__PURE__ */ jsx(Flow.Part, {
		part: "verifyDomain",
		children: /* @__PURE__ */ jsxs(Step, {
			elementDescriptor: descriptors.configureSSOStep,
			elementId: descriptors.configureSSOStep.setId("verify-domain"),
			children: [
				/* @__PURE__ */ jsx(Step.Header, {
					title: t(localizationKeys("configureSSO.verifyEmailDomainStep.title")),
					description: t(localizationKeys("configureSSO.verifyEmailDomainStep.subtitle"))
				}),
				/* @__PURE__ */ jsx(Step.Body, { children: /* @__PURE__ */ jsx(Step.Section, {
					sx: { flex: 1 },
					align: "center",
					justify: "center",
					children: /* @__PURE__ */ jsx(EmailAlreadyVerified, { emailAddress: emailToVerify.emailAddress })
				}) }),
				/* @__PURE__ */ jsx(Step.Footer, { children: /* @__PURE__ */ jsx(Step.Footer.Continue, { onClick: () => outerGoNext() }) })
			]
		})
	});
	return /* @__PURE__ */ jsx(Flow.Part, {
		part: "verifyDomain",
		children: /* @__PURE__ */ jsx(Step, {
			elementDescriptor: descriptors.configureSSOStep,
			elementId: descriptors.configureSSOStep.setId("verify-domain"),
			children: /* @__PURE__ */ jsxs(Wizard, {
				initialStepId: initialInnerStepIdRef.current,
				children: [/* @__PURE__ */ jsx(Step.Header, {
					title: t(localizationKeys("configureSSO.verifyEmailDomainStep.title")),
					description: t(localizationKeys("configureSSO.verifyEmailDomainStep.subtitle")),
					children: /* @__PURE__ */ jsx(InnerStepCounter, {})
				}), /* @__PURE__ */ jsxs(Step.Body, { children: [/* @__PURE__ */ jsx(Wizard.Step, {
					id: "provide-email",
					children: /* @__PURE__ */ jsx(ProvideEmailStep, {
						emailAddressRef,
						preExistingEmailIdRef
					})
				}), /* @__PURE__ */ jsx(Wizard.Step, {
					id: "verify-email-address",
					children: /* @__PURE__ */ jsx(EnterVerificationCodeStep, { emailAddressRef })
				})] })]
			})
		})
	});
};
const InnerStepCounter = () => {
	const { currentIndex, totalSteps } = useWizard();
	return /* @__PURE__ */ jsx(Step.Counter, {
		total: totalSteps,
		current: currentIndex + 1
	});
};
const isEmail = (str) => /^\S+@\S+\.\S+$/.test(str);
const normalizeEmail = (value) => value.trim().toLowerCase();
const ProvideEmailStep = ({ emailAddressRef, preExistingEmailIdRef }) => {
	const { goNext, goPrev } = useWizard();
	const { user } = useUser();
	const card = useCardState();
	const { t } = useLocalizations();
	const [email, setEmail] = useState(() => emailAddressRef.current?.emailAddress ?? "");
	const createEmailAddress = useReverification((value) => user?.createEmailAddress({ email: value }));
	const canSubmit = isEmail(email) && !card.isLoading;
	const handleSubmit = useCallback(async () => {
		if (!canSubmit) return;
		const current = emailAddressRef.current;
		const submittedEmail = email.trim();
		if (current && normalizeEmail(current.emailAddress) === normalizeEmail(submittedEmail)) {
			await goNext();
			return;
		}
		card.setError(void 0);
		card.setLoading();
		try {
			const created = await createEmailAddress(submittedEmail);
			const previous = current;
			emailAddressRef.current = created ?? void 0;
			if (previous && previous.id !== preExistingEmailIdRef.current && previous.id !== created?.id) try {
				await previous.destroy();
			} catch {}
			await goNext();
		} catch (err) {
			handleError(err, [], card.setError);
		} finally {
			card.setIdle();
		}
	}, [
		canSubmit,
		email,
		createEmailAddress,
		card,
		goNext,
		emailAddressRef,
		preExistingEmailIdRef
	]);
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Step.Section, {
		sx: { flex: 1 },
		align: "center",
		justify: "center",
		children: /* @__PURE__ */ jsxs(Form.Root, {
			onSubmit: handleSubmit,
			gap: 3,
			sx: (t$1) => ({
				display: "flex",
				maxWidth: t$1.sizes.$66,
				textAlign: "center",
				flexDirection: "column",
				alignItems: "center"
			}),
			children: [
				/* @__PURE__ */ jsx(Icon, {
					icon: duotone_at_symbol_default,
					sx: (t$1) => ({
						width: t$1.sizes.$8,
						height: t$1.sizes.$8,
						color: t$1.colors.$neutralAlpha600
					})
				}),
				/* @__PURE__ */ jsx(Col, {
					gap: 1,
					children: /* @__PURE__ */ jsx(Heading, {
						textVariant: "h1",
						sx: (t$1) => ({
							fontSize: t$1.fontSizes.$lg,
							fontWeight: t$1.fontWeights.$bold
						}),
						localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.addEmailAddress.formTitle")
					})
				}),
				/* @__PURE__ */ jsxs(Col, {
					gap: 1,
					sx: { width: "100%" },
					children: [
						/* @__PURE__ */ jsx(Text, {
							as: "p",
							variant: "body",
							colorScheme: "secondary",
							localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.addEmailAddress.formSubtitle")
						}),
						/* @__PURE__ */ jsx(Input, {
							type: "email",
							placeholder: t(localizationKeys("configureSSO.verifyEmailDomainStep.addEmailAddress.inputPlaceholder")),
							"aria-label": t(localizationKeys("configureSSO.verifyEmailDomainStep.addEmailAddress.inputLabel")),
							value: email,
							onChange: (e) => setEmail(e.currentTarget.value),
							hasError: Boolean(card.error),
							isDisabled: card.isLoading,
							autoFocus: true
						}),
						card.error ? /* @__PURE__ */ jsx(Text, {
							as: "p",
							variant: "body",
							sx: (t$1) => ({
								color: t$1.colors.$danger500,
								fontSize: t$1.fontSizes.$sm,
								textAlign: "start"
							}),
							children: card.error
						}) : null
					]
				})
			]
		})
	}), /* @__PURE__ */ jsxs(Step.Footer, { children: [/* @__PURE__ */ jsx(Step.Footer.Previous, {
		onClick: () => goPrev(),
		isDisabled: true
	}), /* @__PURE__ */ jsx(Step.Footer.Continue, {
		onClick: handleSubmit,
		isLoading: card.isLoading,
		isDisabled: !canSubmit || card.isLoading
	})] })] });
};
const EnterVerificationCodeStep = ({ emailAddressRef }) => {
	const { user } = useUser();
	const { provider, createEnterpriseConnection } = useConfigureSSO();
	const card = useCardState();
	const { goNext, goPrev } = useWizard();
	const primaryEmailAddress = user?.primaryEmailAddress;
	const emailToVerify = emailAddressRef.current;
	const isVerified = emailToVerify?.verification.status === "verified";
	const isPrimary = emailToVerify?.id === user?.primaryEmailAddressId;
	const prepareEmailVerification = useReverification(() => emailAddressRef.current?.prepareVerification({ strategy: "email_code" }));
	const attemptEmailVerification = useReverification((code) => emailAddressRef.current?.attemptVerification({ code }));
	const setPrimaryEmailAddress = useReverification((emailAddressId) => user?.update({ primaryEmailAddressId: emailAddressId }));
	const prepare = useCallback(() => prepareEmailVerification()?.catch((err) => handleError(err, [], card.setError)), [prepareEmailVerification, card]);
	const otp = useFieldOTP({
		onCodeEntryFinished: (code, resolve, reject) => {
			attemptEmailVerification(code).then(() => resolve()).catch(reject);
		},
		onResendCodeClicked: () => {
			prepare();
		},
		onResolve: async () => {
			const target = emailAddressRef.current;
			if (target && !isPrimary) try {
				await setPrimaryEmailAddress(target.id);
			} catch (err) {
				handleError(err, [], card.setError);
				return;
			}
			if (!provider) {
				goNext();
				return;
			}
			try {
				await createEnterpriseConnection(provider, emailToVerify);
			} catch (err) {
				handleError(err, [], card.setError);
				return;
			}
			goNext();
		}
	});
	useEffect(() => {
		if (emailToVerify && !isVerified) prepare();
	}, []);
	if (!emailToVerify) return null;
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Step.Section, {
		sx: { flex: 1 },
		align: "center",
		justify: "center",
		children: /* @__PURE__ */ jsxs(Col, {
			gap: 4,
			sx: { textAlign: "center" },
			children: [/* @__PURE__ */ jsxs(Col, {
				gap: 1,
				children: [/* @__PURE__ */ jsx(Heading, {
					textVariant: "h1",
					sx: (t) => ({ fontSize: t.fontSizes.$sm }),
					localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.emailCode.formTitle")
				}), /* @__PURE__ */ jsx(Text, {
					as: "p",
					variant: "body",
					colorScheme: "secondary",
					localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.emailCode.formSubtitle", { identifier: emailToVerify.emailAddress })
				})]
			}), /* @__PURE__ */ jsx(Form.OTPInput, {
				...otp,
				resendButton: localizationKeys("configureSSO.verifyEmailDomainStep.emailCode.resendButton")
			})]
		})
	}), /* @__PURE__ */ jsxs(Step.Footer, { children: [/* @__PURE__ */ jsx(Step.Footer.Previous, {
		onClick: () => goPrev(),
		isDisabled: !!primaryEmailAddress
	}), /* @__PURE__ */ jsx(Step.Footer.Continue, {
		onClick: () => goNext(),
		isLoading: otp.isLoading || card.isLoading,
		isDisabled: !isVerified
	})] })] });
};
const EmailAlreadyVerified = ({ emailAddress }) => {
	const { t } = useLocalizations();
	return /* @__PURE__ */ jsxs(Col, {
		gap: 3,
		sx: { alignItems: "center" },
		children: [/* @__PURE__ */ jsx(Icon, {
			icon: duotone_at_symbol_default,
			sx: (t$1) => ({
				width: t$1.sizes.$8,
				height: t$1.sizes.$8,
				color: t$1.colors.$neutralAlpha600
			})
		}), /* @__PURE__ */ jsxs(Col, {
			gap: 2,
			sx: (t$1) => ({
				textAlign: "center",
				maxWidth: t$1.sizes.$66
			}),
			children: [
				/* @__PURE__ */ jsx(Heading, {
					textVariant: "h1",
					sx: (t$1) => ({
						fontSize: t$1.fontSizes.$lg,
						fontWeight: t$1.fontWeights.$bold
					}),
					localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.emailCode.verified.title")
				}),
				/* @__PURE__ */ jsx(Col, {
					gap: 3,
					sx: { flex: 1 },
					children: /* @__PURE__ */ jsx(Text, {
						as: "p",
						variant: "body",
						colorScheme: "secondary",
						localizationKey: localizationKeys("configureSSO.verifyEmailDomainStep.emailCode.verified.subtitle")
					})
				}),
				/* @__PURE__ */ jsx(Input, {
					type: "email",
					value: emailAddress,
					readOnly: true,
					"aria-label": t(localizationKeys("configureSSO.verifyEmailDomainStep.emailCode.verified.inputLabel")),
					sx: (t$1) => ({ backgroundColor: t$1.colors.$neutralAlpha50 })
				})
			]
		})]
	});
};

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