import { localizationKeys } from "../../localization/localizationKeys.js";
import { useUserProfileContext } from "../../contexts/components/UserProfile.js";
import { descriptors } from "../../customizables/elementDescriptors.js";
import { useCardState, withCardStateProvider } from "../../elements/contexts/index.js";
import { Badge, Box, Flex, Text } from "../../customizables/index.js";
import { Card } from "../../elements/Card/index.js";
import { sleep } from "../../utils/sleep.js";
import { ProviderIcon } from "../../common/ProviderIcon.js";
import { handleError } from "../../utils/errorHandler.js";
import { Action } from "../../elements/Action/index.js";
import { ProfileSection } from "../../elements/Section.js";
import { Fragment, useState } from "react";
import { appendModalState } from "@clerk/shared/internal/clerk-js/queryStateParams";
import { __internal_useUserEnterpriseConnections, useReverification, useUser } from "@clerk/shared/react";
import { jsx, jsxs } from "@emotion/react/jsx-runtime";
import { windowNavigate } from "@clerk/shared/internal/clerk-js/windowNavigate";

//#region src/components/UserProfile/EnterpriseAccountsSection.tsx
const EnterpriseConnectMenuButton = (props) => {
	const { connection } = props;
	const card = useCardState();
	const { user } = useUser();
	const { componentName, mode } = useUserProfileContext();
	const isModal = mode === "modal";
	const loadingKey = `enterprise_${connection.id}`;
	const createExternalAccount = useReverification(() => {
		const redirectUrl = isModal ? appendModalState({
			url: window.location.href,
			componentName
		}) : window.location.href;
		return user?.createExternalAccount({
			enterpriseConnectionId: connection.id,
			redirectUrl
		});
	});
	const connect = () => {
		if (!user) return;
		card.setLoading(loadingKey);
		return createExternalAccount().then((res) => {
			if (res?.verification?.externalVerificationRedirectURL) {
				sleep(2e3).then(() => card.setIdle(loadingKey));
				windowNavigate(res.verification.externalVerificationRedirectURL);
			}
		}).catch((err) => {
			handleError(err, [], card.setError);
			card.setIdle(loadingKey);
		});
	};
	const providerIconId = connection.provider.replace(/(oauth_|saml_)/, "").trim();
	const providerIconUrl = connection.logoPublicUrl?.trim() || "";
	return /* @__PURE__ */ jsx(ProfileSection.ActionMenuItem, {
		id: connection.id,
		onClick: connect,
		isDisabled: card.isLoading,
		variant: "ghost",
		isLoading: card.loadingMetadata === loadingKey,
		focusRing: false,
		closeAfterClick: false,
		localizationKey: localizationKeys("userProfile.connectedAccountPage.socialButtonsBlockButton", { provider: connection.name }),
		sx: (t) => ({
			justifyContent: "start",
			gap: t.space.$2
		}),
		leftIcon: /* @__PURE__ */ jsx(ProviderIcon, {
			id: providerIconId,
			iconUrl: providerIconUrl || void 0,
			name: connection.name,
			isLoading: card.loadingMetadata === loadingKey,
			isDisabled: card.isLoading,
			alt: `Connect ${connection.name} account`,
			elementDescriptor: descriptors.providerIcon,
			elementId: descriptors.providerIcon.setId(providerIconId)
		})
	}, connection.id);
};
const AddEnterpriseAccount = ({ onClick, enterpriseConnections }) => {
	if (enterpriseConnections.length === 0) return null;
	return /* @__PURE__ */ jsx(ProfileSection.ActionMenu, {
		triggerLocalizationKey: localizationKeys("userProfile.start.enterpriseAccountsSection.primaryButton"),
		id: "enterpriseAccounts",
		onClick,
		children: enterpriseConnections.map((connection) => /* @__PURE__ */ jsx(EnterpriseConnectMenuButton, { connection }, connection.id))
	});
};
const EnterpriseAccountsSection = withCardStateProvider(() => {
	const { user } = useUser();
	const card = useCardState();
	const [actionValue, setActionValue] = useState(null);
	const activeEnterpriseAccounts = user?.enterpriseAccounts.filter(({ enterpriseConnection }) => enterpriseConnection?.active);
	const { data: userEnterpriseConnections = [] } = __internal_useUserEnterpriseConnections({ withOrganizationAccountLinking: true });
	const linkableEnterpriseConnections = userEnterpriseConnections.filter((c) => c.allowOrganizationAccountLinking && !user?.enterpriseAccounts?.some((a) => a.enterpriseConnectionId === c.id));
	if (!activeEnterpriseAccounts?.length && !linkableEnterpriseConnections.length) return null;
	return /* @__PURE__ */ jsxs(ProfileSection.Root, {
		title: localizationKeys("userProfile.start.enterpriseAccountsSection.title"),
		id: "enterpriseAccounts",
		centered: false,
		children: [/* @__PURE__ */ jsx(Card.Alert, { children: card.error }), /* @__PURE__ */ jsxs(Action.Root, {
			value: actionValue,
			onChange: setActionValue,
			children: [/* @__PURE__ */ jsx(ProfileSection.ItemList, {
				id: "enterpriseAccounts",
				children: activeEnterpriseAccounts?.map((account) => /* @__PURE__ */ jsx(EnterpriseAccount, { account }, account.id))
			}), linkableEnterpriseConnections.length > 0 && /* @__PURE__ */ jsx(AddEnterpriseAccount, {
				enterpriseConnections: linkableEnterpriseConnections,
				onClick: () => setActionValue(null)
			})]
		})]
	});
});
const EnterpriseAccount = ({ account }) => {
	const label = account.emailAddress;
	const connectionName = account?.enterpriseConnection?.name;
	const error = account.verification?.error?.longMessage;
	const accountId = account.id ?? "";
	return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(ProfileSection.Item, {
		id: "enterpriseAccounts",
		children: /* @__PURE__ */ jsxs(Flex, {
			sx: (t) => ({
				overflow: "hidden",
				gap: t.space.$2
			}),
			children: [/* @__PURE__ */ jsx(EnterpriseAccountProviderIcon, { account }), /* @__PURE__ */ jsx(Box, {
				sx: {
					whiteSpace: "nowrap",
					overflow: "hidden"
				},
				children: /* @__PURE__ */ jsxs(Flex, {
					gap: 1,
					center: true,
					children: [
						/* @__PURE__ */ jsx(Text, {
							truncate: true,
							colorScheme: "body",
							children: connectionName
						}),
						/* @__PURE__ */ jsx(Text, {
							truncate: true,
							as: "span",
							colorScheme: "secondary",
							children: label ? `• ${label}` : ""
						}),
						error && /* @__PURE__ */ jsx(Badge, {
							colorScheme: "danger",
							localizationKey: localizationKeys("badge__requiresAction")
						})
					]
				})
			})]
		})
	}) }, accountId);
};
const EnterpriseAccountProviderIcon = ({ account }) => {
	const { provider, enterpriseConnection } = account;
	const providerWithoutPrefix = provider.replace(/(oauth_|saml_)/, "").trim();
	const connectionName = enterpriseConnection?.name ?? providerWithoutPrefix;
	return /* @__PURE__ */ jsx(ProviderIcon, {
		id: providerWithoutPrefix,
		iconUrl: enterpriseConnection?.logoPublicUrl,
		name: connectionName,
		alt: `${connectionName}'s icon`,
		elementDescriptor: [descriptors.providerIcon],
		elementId: descriptors.enterpriseButtonsProviderIcon.setId(account.provider)
	});
};

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