"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { CreditCard, ExternalLink, Loader2 } from "lucide-react";
import { Button } from "../ui/button.js";
import { useSubscription } from "../../hooks/useSubscription.js";
import { toast } from "sonner";
function ManageBillingButton({ className }) {
  const t = useTranslations("billing.portal");
  const { subscription } = useSubscription();
  const [isLoading, setIsLoading] = useState(false);
  if (!(subscription == null ? void 0 : subscription.externalCustomerId)) {
    return null;
  }
  const handleClick = async () => {
    var _a;
    setIsLoading(true);
    try {
      const response = await fetch("/api/v1/billing/portal", {
        method: "POST",
        headers: { "Content-Type": "application/json" }
      });
      if (!response.ok) {
        const data2 = await response.json();
        toast.error(data2.error || t("error"));
        setIsLoading(false);
        return;
      }
      const data = await response.json();
      if (data.success && ((_a = data.data) == null ? void 0 : _a.url)) {
        window.location.href = data.data.url;
      } else {
        toast.error(data.error || t("error"));
        setIsLoading(false);
      }
    } catch (error) {
      console.error("Portal error:", error);
      toast.error(t("error"));
      setIsLoading(false);
    }
  };
  return /* @__PURE__ */ jsx(
    Button,
    {
      variant: "outline",
      onClick: handleClick,
      disabled: isLoading,
      className,
      "data-cy": "manage-billing-button",
      children: isLoading ? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
        t("loading")
      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(CreditCard, { className: "mr-2 h-4 w-4" }),
        t("manage"),
        /* @__PURE__ */ jsx(ExternalLink, { className: "ml-2 h-3 w-3" })
      ] })
    }
  );
}
export {
  ManageBillingButton
};
