"use client";
import { InlineSpinner, SectionCard, StatusBadge, Badge, Button, ListCard, ListCardItem } from './chunk-JN6IL6OH.mjs';
import { triggerHaptic } from './chunk-D2JF6C3E.mjs';
import { useTranslations, useFormatter } from './chunk-7VJ7CMMT.mjs';
import { useState, useCallback, useEffect } from 'react';
import { useAuth } from '@datatechsolutions/windsock/client';
import { jsx, jsxs } from 'react/jsx-runtime';

var TIER_ORDER = {
  free_trial: 0,
  starter: 1,
  professional: 2,
  enterprise: 3
};
function BillingPanel({
  defaultBillingInterval = "monthly",
  onRedirect
}) {
  const t = useTranslations("windsock");
  const format = useFormatter();
  const { client } = useAuth();
  const [subscription, setSubscription] = useState(null);
  const [plans, setPlans] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [busyAction, setBusyAction] = useState(null);
  const redirect = useCallback((url) => {
    if (onRedirect) {
      onRedirect(url);
    } else if (typeof window !== "undefined") {
      window.location.assign(url);
    }
  }, [onRedirect]);
  const load = 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]);
  useEffect(() => {
    void load();
  }, [load]);
  const handleOpenPortal = useCallback(async () => {
    setBusyAction("portal");
    triggerHaptic("light");
    try {
      const { url } = await client.createPortalSession();
      redirect(url);
    } catch (portalError) {
      setError(portalError instanceof Error ? portalError.message : String(portalError));
      triggerHaptic("error");
    } finally {
      setBusyAction(null);
    }
  }, [client, redirect]);
  const handleStartCheckout = useCallback(async (planCode) => {
    setBusyAction(`checkout:${planCode}`);
    triggerHaptic("light");
    try {
      const { url } = await client.createCheckoutSession(planCode, defaultBillingInterval);
      redirect(url);
    } catch (checkoutError) {
      setError(checkoutError instanceof Error ? checkoutError.message : String(checkoutError));
      triggerHaptic("error");
    } finally {
      setBusyAction(null);
    }
  }, [client, defaultBillingInterval, redirect]);
  const handleCancel = useCallback(async () => {
    if (typeof window !== "undefined") {
      const confirmed = window.confirm(t("billing.cancelConfirm"));
      if (!confirmed) return;
    }
    setBusyAction("cancel");
    triggerHaptic("warning");
    try {
      const result = await client.cancelSubscription();
      if (!result.success) {
        throw new Error(result.error ?? "Subscription cancellation failed");
      }
      triggerHaptic("success");
      await load();
    } catch (cancelError) {
      setError(cancelError instanceof Error ? cancelError.message : String(cancelError));
      triggerHaptic("error");
    } finally {
      setBusyAction(null);
    }
  }, [client, load, t]);
  if (isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-12", children: /* @__PURE__ */ jsx(InlineSpinner, {}) });
  }
  const currentPlan = subscription?.plan ?? plans.find((plan) => plan.id === subscription?.planId) ?? null;
  const currentTier = subscription?.tier ?? currentPlan?.tier ?? null;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    error && /* @__PURE__ */ 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__ */ jsx(
      SectionCard,
      {
        header: {
          title: t("billing.currentPlan.title"),
          subtitle: t("billing.currentPlan.description")
        },
        children: subscription && currentPlan ? /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
            /* @__PURE__ */ jsx("span", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: currentPlan.name }),
            /* @__PURE__ */ jsx(
              StatusBadge,
              {
                status: subscription.status === "active" ? "success" : subscription.status === "past_due" ? "pending" : "error",
                label: t(`billing.status.${subscription.status}`)
              }
            ),
            subscription.cancelAtPeriodEnd && /* @__PURE__ */ jsx(Badge, { color: "amber", children: t("billing.currentPlan.cancelAtPeriodEnd") })
          ] }),
          /* @__PURE__ */ jsxs("dl", { className: "grid grid-cols-1 gap-3 text-sm sm:grid-cols-2", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("dt", { className: "text-gray-500 dark:text-gray-400", children: t("billing.currentPlan.price") }),
              /* @__PURE__ */ 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__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("dt", { className: "text-gray-500 dark:text-gray-400", children: t("billing.currentPlan.renewsOn") }),
              /* @__PURE__ */ jsx("dd", { className: "font-medium text-gray-900 dark:text-white", children: format.dateTime(new Date(subscription.currentPeriodEnd), { dateStyle: "medium" }) })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2 pt-2", children: [
            /* @__PURE__ */ jsx(
              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__ */ jsx(
              Button,
              {
                size: "sm",
                color: "ios-glass-red",
                onClick: handleCancel,
                loading: busyAction === "cancel",
                disabled: busyAction !== null,
                children: t("billing.currentPlan.cancel")
              }
            )
          ] })
        ] }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("billing.currentPlan.noSubscription") })
      }
    ),
    /* @__PURE__ */ jsx(
      SectionCard,
      {
        header: {
          title: t("billing.plans.title"),
          subtitle: t("billing.plans.description")
        },
        children: plans.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: t("billing.plans.empty") }) : /* @__PURE__ */ jsx(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__ */ jsx(
            ListCardItem,
            {
              leading: /* @__PURE__ */ 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__ */ jsx("span", { className: "text-sm font-bold uppercase", children: plan.tier.charAt(0) }) }),
              trailing: isCurrent ? /* @__PURE__ */ jsx(Badge, { color: "green", children: t("billing.plans.currentBadge") }) : isDowngrade ? /* @__PURE__ */ jsx(
                Button,
                {
                  size: "sm",
                  plain: true,
                  onClick: () => handleStartCheckout(plan.code),
                  loading: busyAction === `checkout:${plan.code}`,
                  disabled: busyAction !== null,
                  children: t("billing.plans.downgradeAction")
                }
              ) : /* @__PURE__ */ jsx(
                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__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-white", children: plan.name }),
                  /* @__PURE__ */ 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__ */ jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: plan.description })
              ] })
            },
            plan.id
          );
        }) })
      }
    )
  ] });
}

export { BillingPanel };
//# sourceMappingURL=chunk-R4TQWXNG.mjs.map
//# sourceMappingURL=chunk-R4TQWXNG.mjs.map