import { useRouter } from "../../router/RouteContext.js";
import { useEnvironment } from "../../contexts/EnvironmentContext.js";
import { localizationKeys } from "../../localization/localizationKeys.js";
import arrows_up_down_default from "../../icons/arrows-up-down.js";
import cog_filled_default from "../../icons/cog-filled.js";
import plans_default from "../../icons/plans.js";
import plus_default from "../../icons/plus.js";
import { useProtect } from "../../common/Gate.js";
import { useSubscriberTypeContext, useSubscriberTypeLocalizationRoot } from "../../contexts/components/SubscriberType.js";
import { normalizeFormatted, usePlansContext, useSubscription } from "../../contexts/components/Plans.js";
import { Col, Flex, Icon, Span, Table, Tbody, Td, Text, Th, Thead, Tr } from "../../customizables/index.js";
import { SubscriptionBadge } from "./badge.js";
import { ProfileSection } from "../../elements/Section.js";
import { useMemo } from "react";
import { jsx, jsxs } from "@emotion/react/jsx-runtime";

//#region src/components/Subscriptions/SubscriptionsList.tsx
const isFreePlan = (plan) => !plan.hasBaseFee;
function SubscriptionsList({ title, switchPlansLabel, newSubscriptionLabel, manageSubscriptionLabel }) {
	const localizationRoot = useSubscriberTypeLocalizationRoot();
	const subscriberType = useSubscriberTypeContext();
	const { subscriptionItems } = useSubscription();
	const canManageBilling = useProtect((has) => has({ permission: "org:sys_billing:manage" })) || subscriberType === "user";
	const { navigate } = useRouter();
	const { commerceSettings } = useEnvironment();
	const { openSubscriptionDetails } = usePlansContext();
	const billingPlansExist = commerceSettings.billing.user.hasPaidPlans && subscriberType === "user" || commerceSettings.billing.organization.hasPaidPlans && subscriberType === "organization";
	const hasActiveFreePlan = useMemo(() => {
		return subscriptionItems.some((sub) => isFreePlan(sub.plan) && sub.status === "active");
	}, [subscriptionItems]);
	const isManageButtonVisible = canManageBilling && !hasActiveFreePlan && subscriptionItems.length > 0;
	const sortedSubscriptions = useMemo(() => subscriptionItems.sort((a, b) => {
		if (a.status === "active" && b.status !== "active") return -1;
		if (b.status === "active" && a.status !== "active") return 1;
		return 1;
	}), [subscriptionItems]);
	return /* @__PURE__ */ jsxs(ProfileSection.Root, {
		id: "subscriptionsList",
		title,
		centered: false,
		sx: (t) => ({
			borderTop: "none",
			paddingTop: t.space.$1
		}),
		children: [subscriptionItems.length > 0 && /* @__PURE__ */ jsxs(Table, {
			tableHeadVisuallyHidden: true,
			children: [/* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [/* @__PURE__ */ jsx(Th, { localizationKey: localizationKeys(`${localizationRoot}.billingPage.subscriptionsListSection.tableHeader__plan`) }), /* @__PURE__ */ jsx(Th, { localizationKey: localizationKeys(`${localizationRoot}.billingPage.subscriptionsListSection.tableHeader__startDate`) })] }) }), /* @__PURE__ */ jsx(Tbody, { children: sortedSubscriptions.map((subscription) => /* @__PURE__ */ jsx(SubscriptionRow, {
				subscription,
				length: sortedSubscriptions.length
			}, subscription.id)) })]
		}), /* @__PURE__ */ jsxs(ProfileSection.ButtonGroup, {
			id: "subscriptionsList",
			children: [billingPlansExist ? /* @__PURE__ */ jsx(ProfileSection.ArrowButton, {
				id: "subscriptionsList",
				textLocalizationKey: subscriptionItems.length > 0 ? switchPlansLabel : newSubscriptionLabel,
				sx: [(t) => ({
					justifyContent: "start",
					height: t.sizes.$8,
					width: isManageButtonVisible ? "unset" : void 0
				})],
				leftIcon: subscriptionItems.length > 0 ? arrows_up_down_default : plus_default,
				rightIcon: null,
				leftIconSx: (t) => ({
					width: t.sizes.$4,
					height: t.sizes.$4
				}),
				onClick: () => void navigate("plans")
			}) : null, isManageButtonVisible ? /* @__PURE__ */ jsx(ProfileSection.ArrowButton, {
				id: "subscriptionsList",
				textLocalizationKey: manageSubscriptionLabel,
				sx: [(t) => ({
					justifyContent: "start",
					height: t.sizes.$8,
					width: "unset"
				})],
				rightIcon: null,
				leftIcon: cog_filled_default,
				leftIconSx: (t) => ({
					width: t.sizes.$4,
					height: t.sizes.$4
				}),
				onClick: (event) => openSubscriptionDetails(event)
			}) : null]
		})]
	});
}
function SubscriptionRow({ subscription, length }) {
	const fee = subscription.planPeriod === "annual" ? subscription.plan.annualFee : subscription.plan.fee;
	const { captionForSubscription } = usePlansContext();
	const feeFormatted = useMemo(() => {
		return normalizeFormatted(fee.amountFormatted);
	}, [fee.amountFormatted]);
	return /* @__PURE__ */ jsxs(Tr, { children: [/* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsxs(Col, {
		gap: 1,
		children: [/* @__PURE__ */ jsxs(Flex, {
			align: "center",
			gap: 1,
			children: [
				/* @__PURE__ */ jsx(Icon, {
					icon: plans_default,
					sx: (t) => ({
						width: t.sizes.$4,
						height: t.sizes.$4,
						opacity: t.opacity.$inactive
					})
				}),
				/* @__PURE__ */ jsx(Text, {
					variant: "subtitle",
					sx: (t) => ({ marginRight: t.sizes.$1 }),
					children: subscription.plan.name
				}),
				subscription.isFreeTrial || length > 1 || !!subscription.canceledAt ? /* @__PURE__ */ jsx(SubscriptionBadge, { subscription: subscription.isFreeTrial ? { status: "free_trial" } : subscription }) : null
			]
		}), (!subscription.plan.isDefault || subscription.status === "upcoming") && /* @__PURE__ */ jsx(Text, {
			variant: "caption",
			colorScheme: "secondary",
			localizationKey: captionForSubscription(subscription)
		})]
	}) }), /* @__PURE__ */ jsx(Td, {
		sx: (_) => ({ textAlign: "right" }),
		children: /* @__PURE__ */ jsxs(Text, {
			variant: "subtitle",
			children: [
				fee.currencySymbol,
				feeFormatted,
				fee.amount > 0 && /* @__PURE__ */ jsx(Span, {
					sx: (t) => ({
						color: t.colors.$colorMutedForeground,
						textTransform: "lowercase",
						":before": {
							content: "\"/\"",
							marginInline: t.space.$1
						}
					}),
					localizationKey: subscription.planPeriod === "annual" ? localizationKeys("billing.year") : localizationKeys("billing.month")
				})
			]
		})
	})] }, subscription.id);
}

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