"use client";
import { useCallback, useState } from "react";
import { useStigmer } from "../hooks";
import { toError } from "../internal/toError";
/**
 * Behavior hook that opens the Stripe Customer Portal for payment
 * method management.
 *
 * Wraps `billing.createBillingPortalSession` with loading and error
 * state management. On success, redirects the user to the Stripe-hosted
 * portal. Payment method changes are synced back via webhooks.
 *
 * @example
 * ```tsx
 * const { openPortal, isLoading } = useCreateBillingPortalSession();
 *
 * <button onClick={() => openPortal(orgId)} disabled={isLoading}>
 *   Manage payment methods
 * </button>
 * ```
 */
export function useCreateBillingPortalSession() {
    const stigmer = useStigmer();
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const clearError = useCallback(() => setError(null), []);
    const openPortal = useCallback(async (orgId) => {
        setIsLoading(true);
        setError(null);
        try {
            const returnUrl = typeof window !== "undefined" ? window.location.href : "";
            const response = await stigmer.billing.createBillingPortalSession({
                orgId,
                returnUrl,
            });
            if (response.portalUrl) {
                window.location.href = response.portalUrl;
            }
        }
        catch (err) {
            setError(toError(err));
            throw err;
        }
        finally {
            setIsLoading(false);
        }
    }, [stigmer]);
    return { openPortal, isLoading, error, clearError };
}
//# sourceMappingURL=useCreateBillingPortalSession.js.map