import { withCoreUserGuard } from "../../contexts/CoreUserContext.js";
import { localizationKeys } from "../../localization/localizationKeys.js";
import { Route } from "../../router/Route.js";
import { Switch } from "../../router/Switch.js";
import exclamation_triangle_default from "../../icons/exclamation-triangle.js";
import { useProtect } from "../../common/Gate.js";
import { descriptors } from "../../customizables/elementDescriptors.js";
import { useCardState, withCardStateProvider } from "../../elements/contexts/index.js";
import { Flow } from "../../customizables/Flow.js";
import { Col, Flex, Heading, Icon, Text } from "../../customizables/index.js";
import { ProfileCard } from "../../elements/ProfileCard/index.js";
import { ConfigureSSOProvider, useConfigureSSO } from "./ConfigureSSOContext.js";
import { ProfileCardFooter, ProfileCardHeader } from "./elements/ProfileCard.js";
import { useWizard } from "./elements/Wizard/WizardContext.js";
import { Wizard } from "./elements/Wizard/Wizard.js";
import { ConfigureSSOHeader } from "./ConfigureSSOHeader.js";
import { ConfigureSSONavbar } from "./ConfigureSSONavbar.js";
import { Step } from "./elements/Step.js";
import { ConfigureSSOSkeleton } from "./ConfigureSSOSkeleton.js";
import { ConfigureStep } from "./steps/ConfigureStep.js";
import { ConfirmationStep } from "./steps/ConfirmationStep.js";
import { SelectProviderStep } from "./steps/SelectProviderStep.js";
import { TestConfigurationStep } from "./steps/TestConfigurationStep.js";
import { VerifyDomainStep } from "./steps/VerifyDomainStep.js";
import React from "react";
import { __internal_useEnterpriseConnectionTestRuns, __internal_useUserEnterpriseConnections, useSession } from "@clerk/shared/react";
import { Fragment as Fragment$1, jsx, jsxs } from "@emotion/react/jsx-runtime";

//#region src/components/ConfigureSSO/ConfigureSSO.tsx
const ConfigureSSOInternal = () => {
	return /* @__PURE__ */ jsx(Flow.Root, {
		flow: "configureSSO",
		children: /* @__PURE__ */ jsx(Switch, { children: /* @__PURE__ */ jsx(Route, { children: /* @__PURE__ */ jsx(AuthenticatedContent, {}) }) })
	});
};
const AuthenticatedContent = withCoreUserGuard(() => {
	const contentRef = React.useRef(null);
	return /* @__PURE__ */ jsx(ProfileCard.Root, {
		sx: (t) => ({
			display: "grid",
			gridTemplateColumns: "1fr 3fr",
			height: t.sizes.$176,
			overflow: "hidden"
		}),
		children: /* @__PURE__ */ jsx(ConfigureSSONavbar, {
			contentRef,
			children: /* @__PURE__ */ jsx(Col, {
				ref: contentRef,
				elementDescriptor: descriptors.scrollBox,
				sx: (t) => ({
					backgroundColor: t.colors.$colorBackground,
					position: "relative",
					borderRadius: t.radii.$lg,
					width: "100%",
					overflow: "hidden",
					borderWidth: t.borderWidths.$normal,
					borderStyle: t.borderStyles.$solid,
					borderColor: t.colors.$borderAlpha150,
					flex: 1
				}),
				children: /* @__PURE__ */ jsx(ConfigureSSOCardProtect, { children: /* @__PURE__ */ jsx(ConfigureSSOCardContent, { contentRef }) })
			})
		})
	});
});
const ConfigureSSOCardContent = ({ contentRef }) => {
	const { data: enterpriseConnections, isLoading: isLoadingEnterpriseConnections, createEnterpriseConnection, updateEnterpriseConnection, deleteEnterpriseConnection } = __internal_useUserEnterpriseConnections({ enabled: true });
	const enterpriseConnection = enterpriseConnections?.[0];
	const { hasSuccessfulTestRun, isLoading: isLoadingTestRuns } = useHasSuccessfulTestRun(enterpriseConnection);
	if (isLoadingEnterpriseConnections || isLoadingTestRuns) return /* @__PURE__ */ jsx(ConfigureSSOSkeleton, {});
	return /* @__PURE__ */ jsx(ConfigureSSOProvider, {
		hasSuccessfulTestRun,
		enterpriseConnection,
		contentRef,
		createEnterpriseConnection,
		updateEnterpriseConnection,
		deleteEnterpriseConnection,
		children: /* @__PURE__ */ jsx(ConfigureSSOSteps, {})
	});
};
const ConfigureSSOSteps = () => {
	const { initialStepId } = useConfigureSSO();
	return /* @__PURE__ */ jsxs(Wizard, {
		initialStepId,
		children: [
			/* @__PURE__ */ jsx(ResetCardErrorOnStepChange, {}),
			/* @__PURE__ */ jsx(ConfigureSSOHeader, {}),
			/* @__PURE__ */ jsx(Wizard.Step, {
				id: "select-provider",
				children: /* @__PURE__ */ jsx(SelectProviderStep, {})
			}),
			/* @__PURE__ */ jsx(Wizard.Step, {
				id: "verify-domain",
				label: "Verify domain",
				children: /* @__PURE__ */ jsx(VerifyDomainStep, {})
			}),
			/* @__PURE__ */ jsx(Wizard.Step, {
				id: "configure",
				label: "Configure",
				children: /* @__PURE__ */ jsx(ConfigureStep, {})
			}),
			/* @__PURE__ */ jsx(Wizard.Step, {
				id: "test",
				label: "Test",
				children: /* @__PURE__ */ jsx(TestConfigurationStep, {})
			}),
			/* @__PURE__ */ jsx(Wizard.Step, {
				id: "confirmation",
				label: "Confirmation",
				children: /* @__PURE__ */ jsx(ConfirmationStep, {})
			})
		]
	});
};
const ConfigureSSOCardProtect = ({ children }) => {
	const { session } = useSession();
	const isPersonalWorkspace = !session?.lastActiveOrganizationId;
	if (!useProtect((has) => isPersonalWorkspace || has({ permission: "org:sys_enterprise_connections:manage" }))) return /* @__PURE__ */ jsx(MissingManageEnterpriseConnectionsPermission, {});
	return children;
};
const MissingManageEnterpriseConnectionsPermission = () => /* @__PURE__ */ jsxs(Fragment$1, { children: [
	/* @__PURE__ */ jsx(ProfileCardHeader, {}),
	/* @__PURE__ */ jsx(Step.Body, { children: /* @__PURE__ */ jsx(Step.Section, {
		sx: { flex: 1 },
		align: "center",
		justify: "center",
		children: /* @__PURE__ */ jsx(Flex, {
			align: "center",
			justify: "center",
			sx: (t) => ({
				flex: 1,
				padding: t.space.$8
			}),
			children: /* @__PURE__ */ jsxs(Col, {
				align: "center",
				sx: (t) => ({
					gap: t.space.$2,
					textAlign: "center",
					maxWidth: t.sizes.$94
				}),
				children: [
					/* @__PURE__ */ jsx(Icon, {
						icon: exclamation_triangle_default,
						sx: (t) => ({
							width: t.sizes.$8,
							height: t.sizes.$8,
							color: t.colors.$neutralAlpha600
						})
					}),
					/* @__PURE__ */ jsx(Heading, {
						localizationKey: localizationKeys("configureSSO.missingManageEnterpriseConnectionsPermission.title"),
						textVariant: "h1",
						sx: (t) => ({
							fontSize: t.fontSizes.$lg,
							textWrap: "balance"
						})
					}),
					/* @__PURE__ */ jsx(Text, {
						as: "p",
						variant: "body",
						colorScheme: "secondary",
						localizationKey: localizationKeys("configureSSO.missingManageEnterpriseConnectionsPermission.subtitle"),
						sx: { textWrap: "balance" }
					})
				]
			})
		})
	}) }),
	/* @__PURE__ */ jsx(ProfileCardFooter, {})
] });
/**
* Sentinel component rendered inside `<Wizard>`
*
* Clears any card-level error whenever the active step transitions, so a stale failure from one step
* doesn't leak into the next
*/
const ResetCardErrorOnStepChange = () => {
	const { currentStep } = useWizard();
	const card = useCardState();
	const previousStepIdRef = React.useRef(currentStep?.id);
	React.useEffect(() => {
		if (previousStepIdRef.current === currentStep?.id) return;
		previousStepIdRef.current = currentStep?.id;
		card.setError(void 0);
	}, [currentStep?.id, card]);
	return null;
};
/**
* Fetches a single successful test run for the given connection on mount
*/
const useHasSuccessfulTestRun = (enterpriseConnection) => {
	const { data: successfulTestRuns, isLoading } = __internal_useEnterpriseConnectionTestRuns({
		enterpriseConnectionId: enterpriseConnection?.id ?? null,
		params: {
			initialPage: 1,
			pageSize: 1,
			status: ["success"]
		}
	});
	return {
		hasSuccessfulTestRun: (successfulTestRuns?.length ?? 0) > 0,
		isLoading
	};
};
const ConfigureSSO = withCardStateProvider(ConfigureSSOInternal);

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