import { withCoreUserGuard } from "../../contexts/CoreUserContext.js";
import { useEnvironment } from "../../contexts/EnvironmentContext.js";
import { localizationKeys } from "../../localization/localizationKeys.js";
import { Route } from "../../router/Route.js";
import { Switch } from "../../router/Switch.js";
import { useOAuthConsentContext } from "../../contexts/components/OAuthConsent.js";
import { useLocalizations } from "../../localization/makeLocalizable.js";
import { Alert } from "../../primitives/Alert.js";
import { Textarea } from "../../primitives/Input.js";
import { withCardStateProvider } from "../../elements/contexts/index.js";
import { Flow } from "../../customizables/Flow.js";
import { Box, Button, Grid, Text } from "../../customizables/index.js";
import { Modal } from "../../elements/Modal.js";
import { ApplicationLogo } from "../../elements/ApplicationLogo.js";
import { Card } from "../../elements/Card/index.js";
import { Header } from "../../elements/Header.js";
import { LoadingCardContainer } from "../../elements/LoadingCard.js";
import { InlineAction } from "./InlineAction.js";
import { ListGroup, ListGroupContent, ListGroupHeader, ListGroupHeaderTitle, ListGroupItem, ListGroupItemLabel } from "./ListGroup.js";
import { LogoGroup, LogoGroupIcon, LogoGroupItem, LogoGroupSeparator } from "./LogoGroup.js";
import { OrgSelect } from "./OrgSelect.js";
import { getForwardedParams, getOAuthConsentFromSearch, getRedirectDisplay, getRedirectUriFromSearch } from "./utils.js";
import { useState } from "react";
import { useClerk, useOAuthConsent, useUser } from "@clerk/shared/react";
import { Fragment as Fragment$1, jsx, jsxs } from "@emotion/react/jsx-runtime";

//#region src/components/OAuthConsent/OAuthConsent.tsx
const OFFLINE_ACCESS_SCOPE = "offline_access";
function _OAuthConsent() {
	const ctx = useOAuthConsentContext();
	const clerk = useClerk();
	const { user } = useUser();
	const { displayConfig: { applicationName, logoImageUrl }, organizationSettings } = useEnvironment();
	const [isUriModalOpen, setIsUriModalOpen] = useState(false);
	const orgSelectionEnabled = !!(ctx.enableOrgSelection && organizationSettings.enabled);
	const orgOptions = orgSelectionEnabled ? (user?.organizationMemberships ?? []).map((m) => ({
		value: m.organization.id,
		label: m.organization.name,
		logoUrl: m.organization.imageUrl
	})) : [];
	const [selectedOrg, setSelectedOrg] = useState(null);
	const effectiveOrg = selectedOrg ?? orgOptions[0]?.value ?? null;
	const hasContextCallbacks = Boolean(ctx.onAllow || ctx.onDeny);
	const fromUrl = getOAuthConsentFromSearch();
	const oauthClientId = ctx.oauthClientId ?? fromUrl.oauthClientId;
	const { data, isLoading, error } = useOAuthConsent({
		oauthClientId,
		scope: ctx.scope ?? fromUrl.scope,
		enabled: !hasContextCallbacks
	});
	const mappedHookScopes = data?.scopes?.map((s) => ({
		scope: s.scope,
		description: s.description,
		requires_consent: s.requiresConsent
	}));
	const scopes = ctx.scopes ?? mappedHookScopes ?? [];
	const oauthApplicationName = ctx.oauthApplicationName ?? data?.oauthApplicationName ?? "";
	const oauthApplicationLogoUrl = ctx.oauthApplicationLogoUrl ?? data?.oauthApplicationLogoUrl;
	const oauthApplicationUrl = ctx.oauthApplicationUrl ?? data?.oauthApplicationUrl;
	const redirectUrl = ctx.redirectUrl ?? getRedirectUriFromSearch();
	const { t } = useLocalizations();
	const domainAction = getRedirectDisplay(redirectUrl);
	const viewFullUrlText = t(localizationKeys("oauthConsent.viewFullUrl"));
	if (!hasContextCallbacks) {
		const errorMessage = !oauthClientId ? "The client ID is missing." : !redirectUrl ? "The redirect URI is missing." : error ? error.message ?? "Failed to load consent information." : void 0;
		if (errorMessage) return /* @__PURE__ */ jsxs(Card.Root, { children: [/* @__PURE__ */ jsx(Card.Content, { children: /* @__PURE__ */ jsx(Card.Alert, { children: errorMessage }) }), /* @__PURE__ */ jsx(Card.Footer, {})] });
		if (isLoading) return /* @__PURE__ */ jsxs(Card.Root, { children: [/* @__PURE__ */ jsx(Card.Content, { children: /* @__PURE__ */ jsx(LoadingCardContainer, {}) }), /* @__PURE__ */ jsx(Card.Footer, {})] });
	}
	const actionUrl = clerk.oauthApplication.buildConsentActionUrl({ clientId: oauthClientId });
	const forwardedParams = getForwardedParams();
	const handleSubmit = (e) => {
		if (!hasContextCallbacks) return;
		e.preventDefault();
		if (e.nativeEvent.submitter?.value === "true") ctx.onAllow?.();
		else ctx.onDeny?.();
	};
	const primaryIdentifier = user?.primaryEmailAddress?.emailAddress || user?.primaryPhoneNumber?.phoneNumber;
	const displayedScopes = scopes.filter((item) => item.scope !== OFFLINE_ACCESS_SCOPE);
	const hasOfflineAccess = scopes.some((item) => item.scope === OFFLINE_ACCESS_SCOPE);
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs("form", {
		method: "POST",
		action: actionUrl,
		onSubmit: handleSubmit,
		children: [
			/* @__PURE__ */ jsxs(Card.Root, { children: [/* @__PURE__ */ jsxs(Card.Content, { children: [
				/* @__PURE__ */ jsxs(Header.Root, { children: [
					oauthApplicationLogoUrl && logoImageUrl && /* @__PURE__ */ jsxs(LogoGroup, { children: [
						/* @__PURE__ */ jsx(LogoGroupItem, {
							justify: "end",
							children: /* @__PURE__ */ jsx(ApplicationLogo, {
								src: oauthApplicationLogoUrl,
								alt: oauthApplicationName,
								href: oauthApplicationUrl,
								isExternal: true
							})
						}),
						/* @__PURE__ */ jsx(LogoGroupSeparator, {}),
						/* @__PURE__ */ jsx(LogoGroupItem, {
							justify: "start",
							children: /* @__PURE__ */ jsx(ApplicationLogo, {})
						})
					] }),
					oauthApplicationLogoUrl && !logoImageUrl && /* @__PURE__ */ jsx(LogoGroup, { children: /* @__PURE__ */ jsxs(Box, {
						sx: { position: "relative" },
						children: [/* @__PURE__ */ jsx(ApplicationLogo, {
							src: oauthApplicationLogoUrl,
							alt: oauthApplicationName,
							href: oauthApplicationUrl,
							isExternal: true
						}), /* @__PURE__ */ jsx(LogoGroupIcon, {
							size: "sm",
							sx: (t$1) => ({
								position: "absolute",
								bottom: `calc(${t$1.space.$3} * -1)`,
								insetInlineEnd: `calc(${t$1.space.$3} * -1)`
							})
						})]
					}) }),
					!oauthApplicationLogoUrl && logoImageUrl && /* @__PURE__ */ jsxs(LogoGroup, { children: [
						/* @__PURE__ */ jsx(LogoGroupItem, {
							justify: "end",
							children: /* @__PURE__ */ jsx(LogoGroupIcon, {})
						}),
						/* @__PURE__ */ jsx(LogoGroupSeparator, {}),
						/* @__PURE__ */ jsx(LogoGroupItem, {
							justify: "start",
							children: /* @__PURE__ */ jsx(ApplicationLogo, {})
						})
					] }),
					!oauthApplicationLogoUrl && !logoImageUrl && /* @__PURE__ */ jsx(LogoGroup, { children: /* @__PURE__ */ jsx(LogoGroupIcon, {}) }),
					/* @__PURE__ */ jsx(Header.Title, { localizationKey: oauthApplicationName }),
					/* @__PURE__ */ jsx(Header.Subtitle, { localizationKey: localizationKeys("oauthConsent.subtitle", {
						applicationName,
						identifier: primaryIdentifier || ""
					}) })
				] }),
				orgSelectionEnabled && orgOptions.length > 0 && effectiveOrg && /* @__PURE__ */ jsx(OrgSelect, {
					options: orgOptions,
					value: effectiveOrg,
					onChange: setSelectedOrg
				}),
				/* @__PURE__ */ jsxs(ListGroup, { children: [/* @__PURE__ */ jsx(ListGroupHeader, { children: /* @__PURE__ */ jsx(ListGroupHeaderTitle, { localizationKey: localizationKeys("oauthConsent.scopeList.title", { applicationName: oauthApplicationName }) }) }), /* @__PURE__ */ jsx(ListGroupContent, { children: displayedScopes.map((item) => /* @__PURE__ */ jsx(ListGroupItem, { children: /* @__PURE__ */ jsx(ListGroupItemLabel, { children: item.description || item.scope || "" }) }, item.scope)) })] }),
				/* @__PURE__ */ jsx(Alert, {
					colorScheme: "warning",
					children: /* @__PURE__ */ jsx(Text, {
						colorScheme: "warning",
						variant: "caption",
						children: /* @__PURE__ */ jsx(InlineAction, {
							text: t(localizationKeys("oauthConsent.warning", {
								applicationName: oauthApplicationName || applicationName,
								domainAction
							})),
							actionText: domainAction,
							onClick: () => setIsUriModalOpen(true),
							tooltipText: viewFullUrlText
						})
					})
				}),
				/* @__PURE__ */ jsxs(Grid, {
					columns: 2,
					gap: 3,
					children: [
						/* @__PURE__ */ jsx(Button, {
							type: "submit",
							name: "consented",
							value: "false",
							colorScheme: "secondary",
							variant: "outline",
							localizationKey: localizationKeys("oauthConsent.action__deny")
						}),
						/* @__PURE__ */ jsx(Button, {
							type: "submit",
							name: "consented",
							value: "true",
							localizationKey: localizationKeys("oauthConsent.action__allow")
						}),
						/* @__PURE__ */ jsxs(Text, {
							sx: { gridColumn: "span 2" },
							colorScheme: "secondary",
							variant: "caption",
							children: [/* @__PURE__ */ jsx(InlineAction, {
								text: t(localizationKeys("oauthConsent.redirectNotice", { domainAction })),
								actionText: domainAction,
								onClick: () => setIsUriModalOpen(true),
								tooltipText: viewFullUrlText
							}), hasOfflineAccess && t(localizationKeys("oauthConsent.offlineAccessNotice"))]
						})
					]
				})
			] }), /* @__PURE__ */ jsx(Card.Footer, {})] }),
			!hasContextCallbacks && forwardedParams.map(([key, value]) => /* @__PURE__ */ jsx("input", {
				type: "hidden",
				name: key,
				value
			}, key)),
			!hasContextCallbacks && orgSelectionEnabled && effectiveOrg && /* @__PURE__ */ jsx("input", {
				type: "hidden",
				name: "organization_id",
				value: effectiveOrg
			})
		]
	}), /* @__PURE__ */ jsx(RedirectUriModal, {
		isOpen: isUriModalOpen,
		onOpen: () => setIsUriModalOpen(true),
		onClose: () => setIsUriModalOpen(false),
		redirectUri: redirectUrl,
		oauthApplicationName
	})] });
}
function RedirectUriModal({ onOpen, onClose, isOpen, redirectUri, oauthApplicationName }) {
	if (!isOpen) return null;
	return /* @__PURE__ */ jsx(Modal, {
		handleOpen: onOpen,
		handleClose: onClose,
		children: /* @__PURE__ */ jsx(Card.Root, { children: /* @__PURE__ */ jsxs(Card.Content, { children: [/* @__PURE__ */ jsxs(Header.Root, { children: [/* @__PURE__ */ jsx(Header.Title, { localizationKey: localizationKeys("oauthConsent.redirectUriModal.title") }), /* @__PURE__ */ jsx(Header.Subtitle, { localizationKey: localizationKeys("oauthConsent.redirectUriModal.subtitle", { applicationName: oauthApplicationName }) })] }), /* @__PURE__ */ jsx(Textarea, {
			style: { maxHeight: "none" },
			cols: 50,
			rows: 6,
			defaultValue: redirectUri,
			readOnly: true
		})] }) })
	});
}
const AuthenticatedRoutes = withCoreUserGuard(withCardStateProvider(_OAuthConsent));
const OAuthConsentInternal = () => {
	return /* @__PURE__ */ jsx(Flow.Root, {
		flow: "oauthConsent",
		children: /* @__PURE__ */ jsx(Flow.Part, { children: /* @__PURE__ */ jsx(Switch, { children: /* @__PURE__ */ jsx(Route, { children: /* @__PURE__ */ jsx(AuthenticatedRoutes, {}) }) }) })
	});
};
const OAuthConsent = OAuthConsentInternal;

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