"use client";
'use strict';

var chunkMT66VKLS_js = require('./chunk-MT66VKLS.js');
var chunkYXN2K77G_js = require('./chunk-YXN2K77G.js');
var chunkBHOT22QL_js = require('./chunk-BHOT22QL.js');
var chunkUZ3CMNUJ_js = require('./chunk-UZ3CMNUJ.js');
var react = require('react');
var jsxRuntime = require('react/jsx-runtime');

var TIER_ORDER = {
  free_trial: 0,
  starter: 1,
  professional: 2,
  enterprise: 3
};
function BillingPanel({
  defaultBillingInterval = "monthly",
  onRedirect
}) {
  const t = chunkYXN2K77G_js.useTranslations("windsock");
  const format = chunkYXN2K77G_js.useFormatter();
  const { client } = chunkMT66VKLS_js.useAuth();
  const [subscription, setSubscription] = react.useState(null);
  const [plans, setPlans] = react.useState([]);
  const [isLoading, setIsLoading] = react.useState(true);
  const [error, setError] = react.useState(null);
  const [busyAction, setBusyAction] = react.useState(null);
  const redirect = react.useCallback((url) => {
    if (onRedirect) {
      onRedirect(url);
    } else if (typeof window !== "undefined") {
      window.location.assign(url);
    }
  }, [onRedirect]);
  const load = react.useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const [sub, availablePlans] = await Promise.all([
        client.getSubscription(),
        client.getPlans()
      ]);
      setSubscription(sub);
      setPlans(
        [...availablePlans].filter((plan) => plan.active).sort(
          (a, b) => (TIER_ORDER[a.tier] ?? 0) - (TIER_ORDER[b.tier] ?? 0)
        )
      );
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : String(loadError));
    } finally {
      setIsLoading(false);
    }
  }, [client]);
  react.useEffect(() => {
    void load();
  }, [load]);
  const handleOpenPortal = react.useCallback(async () => {
    setBusyAction("portal");
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    try {
      const { url } = await client.createPortalSession();
      redirect(url);
    } catch (portalError) {
      setError(portalError instanceof Error ? portalError.message : String(portalError));
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setBusyAction(null);
    }
  }, [client, redirect]);
  const handleStartCheckout = react.useCallback(async (planCode) => {
    setBusyAction(`checkout:${planCode}`);
    chunkUZ3CMNUJ_js.triggerHaptic("light");
    try {
      const { url } = await client.createCheckoutSession(planCode, defaultBillingInterval);
      redirect(url);
    } catch (checkoutError) {
      setError(checkoutError instanceof Error ? checkoutError.message : String(checkoutError));
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setBusyAction(null);
    }
  }, [client, defaultBillingInterval, redirect]);
  const handleCancel = react.useCallback(async () => {
    if (typeof window !== "undefined") {
      const confirmed = window.confirm(t("billing.cancelConfirm"));
      if (!confirmed) return;
    }
    setBusyAction("cancel");
    chunkUZ3CMNUJ_js.triggerHaptic("warning");
    try {
      const result = await client.cancelSubscription();
      if (!result.success) {
        throw new Error(result.error ?? "Subscription cancellation failed");
      }
      chunkUZ3CMNUJ_js.triggerHaptic("success");
      await load();
    } catch (cancelError) {
      setError(cancelError instanceof Error ? cancelError.message : String(cancelError));
      chunkUZ3CMNUJ_js.triggerHaptic("error");
    } finally {
      setBusyAction(null);
    }
  }, [client, load, t]);
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-center py-12", children: /* @__PURE__ */ jsxRuntime.jsx(chunkMT66VKLS_js.InlineSpinner, {}) });
  }
  const currentPlan = subscription?.plan ?? plans.find((plan) => plan.id === subscription?.planId) ?? null;
  const currentTier = subscription?.tier ?? currentPlan?.tier ?? null;
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
    error && /* @__PURE__ */ jsxRuntime.jsx(
      "div",
      {
        role: "alert",
        className: "rounded-xl border border-red-300/40 bg-red-50/80 px-4 py-3 text-sm text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-300",
        children: error
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkMT66VKLS_js.SectionCard,
      {
        header: {
          title: t("billing.currentPlan.title"),
          subtitle: t("billing.currentPlan.description")
        },
        children: subscription && currentPlan ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
            /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: currentPlan.name }),
            /* @__PURE__ */ jsxRuntime.jsx(
              chunkMT66VKLS_js.StatusBadge,
              {
                status: subscription.status === "active" ? "success" : subscription.status === "past_due" ? "pending" : "error",
                label: t(`billing.status.${subscription.status}`)
              }
            ),
            subscription.cancelAtPeriodEnd && /* @__PURE__ */ jsxRuntime.jsx(chunkBHOT22QL_js.Badge, { color: "amber", children: t("billing.currentPlan.cancelAtPeriodEnd") })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsxs("dl", { className: "grid grid-cols-1 gap-3 text-sm sm:grid-cols-2", children: [
            /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntime.jsx("dt", { className: "text-gray-500 dark:text-gray-400", children: t("billing.currentPlan.price") }),
              /* @__PURE__ */ jsxRuntime.jsxs("dd", { className: "font-medium text-gray-900 dark:text-white", children: [
                format.number(currentPlan.price, { style: "currency", currency: currentPlan.currency }),
                " ",
                "/",
                " ",
                t(`billing.interval.${currentPlan.interval}`)
              ] })
            ] }),
            subscription.currentPeriodEnd && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
              /* @__PURE__ */ jsxRuntime.jsx("dt", { className: "text-gray-500 dark:text-gray-400", children: t("billing.currentPlan.renewsOn") }),
              /* @__PURE__ */ jsxRuntime.jsx("dd", { className: "font-medium text-gray-900 dark:text-white", children: format.dateTime(new Date(subscription.currentPeriodEnd), { dateStyle: "medium" }) })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-wrap gap-2 pt-2", children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              chunkBHOT22QL_js.Button,
              {
                size: "sm",
                color: "ios-glass-blue",
                onClick: handleOpenPortal,
                loading: busyAction === "portal",
                disabled: busyAction !== null,
                children: t("billing.currentPlan.manageInPortal")
              }
            ),
            subscription.status === "active" && !subscription.cancelAtPeriodEnd && /* @__PURE__ */ jsxRuntime.jsx(
              chunkBHOT22QL_js.Button,
              {
                size: "sm",
                color: "ios-glass-red",
                onClick: handleCancel,
                loading: busyAction === "cancel",
                disabled: busyAction !== null,
                children: t("billing.currentPlan.cancel")
              }
            )
          ] })
        ] }) : /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("billing.currentPlan.noSubscription") })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      chunkMT66VKLS_js.SectionCard,
      {
        header: {
          title: t("billing.plans.title"),
          subtitle: t("billing.plans.description")
        },
        children: plans.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("billing.plans.empty") }) : /* @__PURE__ */ jsxRuntime.jsx(chunkMT66VKLS_js.ListCard, { children: plans.map((plan) => {
          const isCurrent = currentPlan?.id === plan.id;
          const isDowngrade = currentTier != null && (TIER_ORDER[plan.tier] ?? 0) < (TIER_ORDER[currentTier] ?? 0);
          return /* @__PURE__ */ jsxRuntime.jsx(
            chunkMT66VKLS_js.ListCardItem,
            {
              leading: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-violet-500/20 to-blue-500/20 text-violet-600 dark:text-violet-300", children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-bold uppercase", children: plan.tier.charAt(0) }) }),
              trailing: isCurrent ? /* @__PURE__ */ jsxRuntime.jsx(chunkBHOT22QL_js.Badge, { color: "green", children: t("billing.plans.currentBadge") }) : isDowngrade ? /* @__PURE__ */ jsxRuntime.jsx(
                chunkBHOT22QL_js.Button,
                {
                  size: "sm",
                  plain: true,
                  onClick: () => handleStartCheckout(plan.code),
                  loading: busyAction === `checkout:${plan.code}`,
                  disabled: busyAction !== null,
                  children: t("billing.plans.downgradeAction")
                }
              ) : /* @__PURE__ */ jsxRuntime.jsx(
                chunkBHOT22QL_js.Button,
                {
                  size: "sm",
                  color: "ios-glass-blue",
                  onClick: () => handleStartCheckout(plan.code),
                  loading: busyAction === `checkout:${plan.code}`,
                  disabled: busyAction !== null,
                  children: t("billing.plans.selectAction")
                }
              ),
              children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-1", children: [
                /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: plan.name }),
                  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: [
                    format.number(plan.price, { style: "currency", currency: plan.currency }),
                    " ",
                    "/",
                    " ",
                    t(`billing.interval.${plan.interval}`)
                  ] })
                ] }),
                plan.description && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: plan.description })
              ] })
            },
            plan.id
          );
        }) })
      }
    )
  ] });
}

exports.BillingPanel = BillingPanel;
//# sourceMappingURL=chunk-RFUSH7WD.js.map
//# sourceMappingURL=chunk-RFUSH7WD.js.map