import { useRouter } from "../../router/RouteContext.js";
import { useEnabledThirdPartyProviders } from "../../hooks/useEnabledThirdPartyProviders.js";
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 { Box, Button, Flex, Text } from "../../customizables/index.js";
import { Card } from "../../elements/Card/index.js";
import { ProviderIcon } from "../../common/ProviderIcon.js";
import { handleError } from "../../utils/errorHandler.js";
import { useActionContext } from "../../elements/Action/ActionRoot.js";
import { Action } from "../../elements/Action/index.js";
import { ThreeDotsMenu } from "../../elements/ThreeDotsMenu.js";
import { ProfileSection } from "../../elements/Section.js";
import { AddConnectedAccount } from "./ConnectedAccountsMenu.js";
import { RemoveConnectedAccountForm } from "./RemoveResourceForm.js";
import { Fragment, useState } from "react";
import { appendModalState } from "@clerk/shared/internal/clerk-js/queryStateParams";
import { useReverification, useUser } from "@clerk/shared/react";
import { jsx, jsxs } from "@emotion/react/jsx-runtime";

//#region src/components/UserProfile/ConnectedAccountsSection.tsx
const RemoveConnectedAccountScreen = (props) => {
	const { close } = useActionContext();
	return /* @__PURE__ */ jsx(RemoveConnectedAccountForm, {
		onSuccess: close,
		onReset: close,
		...props
	});
};
const errorCodesForReconnect = [
	"external_account_missing_refresh_token",
	"oauth_fetch_user_error",
	"oauth_token_exchange_error",
	"external_account_email_address_verification_required"
];
const ConnectedAccountsSection = withCardStateProvider(({ shouldAllowCreation = true }) => {
	const { user } = useUser();
	const card = useCardState();
	const hasExternalAccounts = Boolean(user?.externalAccounts?.length);
	const [actionValue, setActionValue] = useState(null);
	if (!user || !shouldAllowCreation && !hasExternalAccounts) return null;
	const accounts = [...user.verifiedExternalAccounts, ...user.unverifiedExternalAccounts.filter((a) => a.verification?.error)];
	return /* @__PURE__ */ jsxs(ProfileSection.Root, {
		title: localizationKeys("userProfile.start.connectedAccountsSection.title"),
		centered: false,
		id: "connectedAccounts",
		children: [/* @__PURE__ */ jsx(Card.Alert, { children: card.error }), /* @__PURE__ */ jsxs(Action.Root, {
			value: actionValue,
			onChange: setActionValue,
			children: [/* @__PURE__ */ jsx(ProfileSection.ItemList, {
				id: "connectedAccounts",
				children: accounts.map((account) => /* @__PURE__ */ jsx(ConnectedAccount, { account }, account.id))
			}), shouldAllowCreation && /* @__PURE__ */ jsx(AddConnectedAccount, { onClick: () => setActionValue(null) })]
		})]
	});
});
const ConnectedAccount = ({ account }) => {
	const { additionalOAuthScopes, componentName, mode } = useUserProfileContext();
	const { navigate } = useRouter();
	const { user } = useUser();
	const card = useCardState();
	const accountId = account.id;
	const isModal = mode === "modal";
	const redirectUrl = isModal ? appendModalState({
		url: window.location.href,
		componentName
	}) : window.location.href;
	const createExternalAccount = useReverification(() => user?.createExternalAccount({
		strategy: account.verification.strategy,
		redirectUrl,
		additionalScopes
	}));
	const { providerToDisplayData } = useEnabledThirdPartyProviders();
	if (!user) return null;
	const label = account.username || account.emailAddress;
	const fallbackErrorMessage = account.verification?.error?.longMessage;
	const additionalScopes = findAdditionalScopes(account, additionalOAuthScopes);
	const reauthorizationRequired = additionalScopes.length > 0 && account.approvedScopes != "";
	const shouldDisplayReconnect = errorCodesForReconnect.includes(account.verification?.error?.code || "") || reauthorizationRequired;
	const connectedAccountErrorMessage = shouldDisplayReconnect ? localizationKeys(`userProfile.start.connectedAccountsSection.subtitle__disconnected`) : fallbackErrorMessage;
	const reconnect = async () => {
		const redirectUrl$1 = isModal ? appendModalState({
			url: window.location.href,
			componentName
		}) : window.location.href;
		try {
			let response;
			if (reauthorizationRequired) response = await account.reauthorize({
				additionalScopes,
				redirectUrl: redirectUrl$1
			});
			else response = await createExternalAccount();
			if (response) await navigate(response.verification.externalVerificationRedirectURL?.href || "");
		} catch (err) {
			handleError(err, [], card.setError);
		}
	};
	const providerData = providerToDisplayData[account.provider];
	return /* @__PURE__ */ jsxs(Fragment, { children: [
		/* @__PURE__ */ jsxs(ProfileSection.Item, {
			id: "connectedAccounts",
			children: [/* @__PURE__ */ jsxs(Flex, {
				sx: (t) => ({
					overflow: "hidden",
					gap: t.space.$2
				}),
				children: [/* @__PURE__ */ jsx(ProviderIcon, {
					id: account.provider,
					iconUrl: providerData?.iconUrl,
					name: providerData?.name || account.provider,
					alt: providerData?.name || account.provider,
					elementDescriptor: descriptors.providerIcon,
					elementId: descriptors.socialButtonsProviderIcon.setId(account.provider),
					sx: { flexShrink: 0 }
				}), /* @__PURE__ */ jsx(Box, {
					sx: {
						whiteSpace: "nowrap",
						overflow: "hidden"
					},
					children: /* @__PURE__ */ jsxs(Flex, {
						gap: 1,
						center: true,
						children: [/* @__PURE__ */ jsx(Text, {
							sx: (t) => ({ color: t.colors.$colorForeground }),
							children: `${providerData?.name || account.provider}`
						}), /* @__PURE__ */ jsx(Text, {
							truncate: true,
							as: "span",
							colorScheme: "secondary",
							children: label ? `• ${label}` : ""
						})]
					})
				})]
			}), /* @__PURE__ */ jsx(ConnectedAccountMenu, { account })]
		}),
		shouldDisplayReconnect && /* @__PURE__ */ jsxs(Box, {
			sx: (t) => ({ padding: `${t.sizes.$none} ${t.sizes.$none} ${t.sizes.$1x5} ${t.sizes.$8x5}` }),
			children: [/* @__PURE__ */ jsx(Text, {
				colorScheme: "secondary",
				sx: (t) => ({
					paddingRight: t.sizes.$1x5,
					display: "inline-block"
				}),
				localizationKey: connectedAccountErrorMessage
			}), /* @__PURE__ */ jsx(Button, {
				sx: { display: "inline-block" },
				onClick: reconnect,
				variant: "link",
				localizationKey: localizationKeys("userProfile.start.connectedAccountsSection.actionLabel__connectionFailed")
			})]
		}),
		account.verification?.error?.code && !shouldDisplayReconnect && /* @__PURE__ */ jsx(Text, {
			colorScheme: "danger",
			sx: (t) => ({ padding: `${t.sizes.$none} ${t.sizes.$1x5} ${t.sizes.$1x5} ${t.sizes.$8x5}` }),
			children: fallbackErrorMessage
		}),
		/* @__PURE__ */ jsx(Action.Open, {
			value: `remove-${accountId}`,
			children: /* @__PURE__ */ jsx(Action.Card, {
				variant: "destructive",
				children: /* @__PURE__ */ jsx(RemoveConnectedAccountScreen, { accountId: account.id })
			})
		})
	] }, account.id);
};
const ConnectedAccountMenu = ({ account }) => {
	const { open } = useActionContext();
	const accountId = account.id;
	return /* @__PURE__ */ jsx(ThreeDotsMenu, { actions: [{
		label: localizationKeys("userProfile.start.connectedAccountsSection.destructiveActionTitle"),
		isDestructive: true,
		onClick: () => open(`remove-${accountId}`)
	}].filter((a) => a !== null) });
};
function findAdditionalScopes(account, scopes) {
	if (!scopes) return [];
	const additionalScopes = scopes[account.provider] || [];
	const currentScopes = account.approvedScopes.split(" ");
	if (additionalScopes.filter((scope) => !currentScopes.includes(scope)).length === 0) return [];
	return additionalScopes;
}

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