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 users_default from "../../icons/users.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 { common } from "../../styledSystem/common.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 { Fragment, 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 sortedSubscriptionItems = 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, {
			sx: (t) => ({
				overflow: "hidden",
				"tr > td": {
					paddingTop: t.space.$3,
					paddingBottom: t.space.$3,
					paddingInlineStart: t.space.$3,
					paddingInlineEnd: t.space.$3
				}
			}),
			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: sortedSubscriptionItems.map((subscriptionItem) => /* @__PURE__ */ jsx(SubscriptionItemRow, {
				subscriptionItem,
				length: sortedSubscriptionItems.length
			}, subscriptionItem.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 SubscriptionItemRow({ subscriptionItem, length }) {
	const fee = subscriptionItem.planPeriod === "annual" ? subscriptionItem.plan.annualFee : subscriptionItem.plan.fee;
	const { captionForSubscription } = usePlansContext();
	const feeFormatted = useMemo(() => {
		return normalizeFormatted(fee.amountFormatted);
	}, [fee.amountFormatted]);
	const subItemSeatsQty = subscriptionItem.seats?.quantity;
	return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Tr, {
		sx: (t) => {
			if (subscriptionItem.status === "upcoming") return { background: common.mutedBackground(t) };
			return {};
		},
		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,
							color: t.colors.$colorMutedForeground
						})
					}),
					/* @__PURE__ */ jsx(Text, {
						variant: "subtitle",
						sx: (t) => ({ marginInlineEnd: t.sizes.$1 }),
						children: subscriptionItem.plan.name
					}),
					subscriptionItem.isFreeTrial || length > 1 || !!subscriptionItem.canceledAt ? /* @__PURE__ */ jsx(SubscriptionBadge, { subscription: subscriptionItem.isFreeTrial ? { status: "free_trial" } : subscriptionItem }) : null
				]
			}), (!subscriptionItem.plan.isDefault || subscriptionItem.status === "upcoming") && /* @__PURE__ */ jsx(Text, {
				variant: "caption",
				colorScheme: "secondary",
				localizationKey: captionForSubscription(subscriptionItem)
			})]
		}) }), /* @__PURE__ */ jsx(Td, {
			sx: (_) => ({ textAlign: "end" }),
			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: subscriptionItem.planPeriod === "annual" ? localizationKeys("billing.year") : localizationKeys("billing.month")
					})
				]
			})
		})]
	}), typeof subItemSeatsQty !== "undefined" ? /* @__PURE__ */ jsxs(Tr, {
		sx: (t) => {
			if (subscriptionItem.status === "upcoming") return { background: common.mutedBackground(t) };
			return {};
		},
		children: [/* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Col, {
			gap: 1,
			children: /* @__PURE__ */ jsxs(Flex, {
				align: "center",
				gap: 1,
				children: [/* @__PURE__ */ jsx(Icon, {
					icon: users_default,
					sx: (t) => ({
						width: t.sizes.$4,
						height: t.sizes.$4,
						opacity: t.opacity.$inactive,
						color: t.colors.$colorMutedForeground
					})
				}), /* @__PURE__ */ jsx(Text, {
					variant: "subtitle",
					sx: (t) => ({ marginInlineEnd: t.sizes.$1 }),
					localizationKey: localizationKeys("billing.seats")
				})]
			})
		}) }), /* @__PURE__ */ jsx(Td, {
			sx: (_) => ({ textAlign: "end" }),
			children: /* @__PURE__ */ jsx(Text, {
				variant: "subtitle",
				localizationKey: subItemSeatsQty === null ? localizationKeys("billing.pricingTable.seatCost.unlimitedSeats") : localizationKeys("billing.pricingTable.seatCost.upToSeats", { endsAfterBlock: subItemSeatsQty })
			})
		})]
	}) : null] }, subscriptionItem.id);
}

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