"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback } from "react";
import { getUserMessage } from "@stigmer/sdk";
import { useDeploymentMode } from "../deployment-mode";
import { CloudFeatureNotice } from "../internal/CloudFeatureNotice";
import { useOrg } from "../organization/OrgProvider";
import { useBillingAccount } from "./useBillingAccount";
import { useCreateCheckoutSession } from "./useCreateCheckoutSession";
import { useCreateBillingPortalSession } from "./useCreateBillingPortalSession";
import { CreditBalanceCard } from "./CreditBalanceCard";
import { PaymentMethodCard } from "./PaymentMethodCard";
import { AutoRechargeCard } from "./AutoRechargeCard";
import { CreditPackGrid } from "./CreditPackGrid";
import { CreditLedgerTable } from "./CreditLedgerTable";
import { LowBalanceBanner } from "./LowBalanceBanner";
/**
 * Top-level billing settings section.
 *
 * Composes the billing sub-components into a cohesive settings page:
 * low-balance warning, checkout success banner, credit balance display,
 * credit pack purchase grid, and transaction history. Handles the
 * deployment mode gate (billing unavailable in local mode) and the
 * org-not-selected state.
 *
 * @example
 * ```tsx
 * // In a settings page:
 * <BillingSection checkoutSuccess={searchParams.checkout === "success"} />
 * ```
 */
export function BillingSection({ checkoutSuccess, onDismissCheckoutSuccess, className, }) {
    const { activeOrg } = useOrg();
    const mode = useDeploymentMode();
    const orgId = activeOrg?.metadata?.id ?? "";
    return (_jsxs("section", { "aria-labelledby": "billing-heading", className: className, children: [_jsx("h2", { id: "billing-heading", className: "text-foreground mb-1 text-sm font-semibold", children: "Billing" }), _jsx("p", { className: "text-muted-foreground mb-4 text-xs", children: "Manage credits, purchase credit packs, and view transaction history." }), mode === "local" ? (_jsx(CloudFeatureNotice, { children: "Billing is available on Stigmer Cloud. Connect to a Cloud organization to manage credits and purchase credit packs." })) : !orgId ? (_jsx("p", { className: "text-muted-foreground py-4 text-center text-xs", children: "Select an organization to view billing." })) : (_jsx(BillingContent, { orgId: orgId, checkoutSuccess: checkoutSuccess, onDismissCheckoutSuccess: onDismissCheckoutSuccess }))] }));
}
// ---------------------------------------------------------------------------
// BillingContent (internal)
// ---------------------------------------------------------------------------
function BillingContent({ orgId, checkoutSuccess, onDismissCheckoutSuccess, }) {
    const { account, isLoading, error, refetch } = useBillingAccount(orgId);
    const { createSession, isSubmitting, error: checkoutError, clearError } = useCreateCheckoutSession();
    const { openPortal, isLoading: isPortalLoading } = useCreateBillingPortalSession();
    const [purchasingPackId, setPurchasingPackId] = useState(null);
    const handlePurchase = useCallback((packId) => {
        setPurchasingPackId(packId);
        clearError();
        const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
        const billingPath = `${baseUrl}/settings/billing`;
        createSession({
            orgId,
            packId,
            successUrl: `${billingPath}?checkout=success`,
            cancelUrl: billingPath,
        }).catch(() => {
            setPurchasingPackId(null);
        });
    }, [orgId, createSession, clearError]);
    if (isLoading) {
        return (_jsxs("div", { className: "space-y-4", "aria-busy": "true", "aria-label": "Loading billing", children: [_jsx("div", { className: "h-24 animate-pulse rounded-lg bg-muted-subtle" }), _jsx("div", { className: "grid grid-cols-3 gap-3", children: Array.from({ length: 3 }, (_, i) => (_jsx("div", { className: "h-36 animate-pulse rounded-lg bg-muted-subtle" }, i))) }), _jsx("div", { className: "h-48 animate-pulse rounded-lg bg-muted-subtle" })] }));
    }
    if (error) {
        return (_jsx("p", { className: "text-destructive text-xs", role: "alert", children: getUserMessage(error) }));
    }
    if (!account)
        return null;
    const balance = account.balance;
    if (!balance)
        return null;
    const isLowBalance = balance.availableMicros < account.lowBalanceThresholdMicros;
    return (_jsxs("div", { className: "space-y-6", children: [checkoutSuccess && (_jsx(CheckoutSuccessBanner, { onDismiss: onDismissCheckoutSuccess })), _jsx(LowBalanceBanner, { availableMicros: balance.availableMicros, thresholdMicros: account.lowBalanceThresholdMicros }), _jsx(CreditBalanceCard, { balance: balance, isLowBalance: isLowBalance }), _jsx(PaymentMethodCard, { paymentMethod: account.defaultPaymentMethod, accountStatus: account.status, isPortalLoading: isPortalLoading, onManage: () => openPortal(orgId) }), _jsx(AutoRechargeCard, { orgId: orgId, autoRecharge: account.autoRecharge, hasPaymentMethod: account.defaultPaymentMethod != null &&
                    account.defaultPaymentMethod.paymentMethodId !== "", accountStatus: account.status, onSaved: refetch }), _jsx(CreditPackGrid, { accountStatus: account.status, purchasingPackId: isSubmitting ? purchasingPackId : null, onPurchase: handlePurchase }), checkoutError && (_jsx("p", { className: "text-destructive text-xs", role: "alert", children: getUserMessage(checkoutError) })), _jsx(CreditLedgerTable, { orgId: orgId })] }));
}
// ---------------------------------------------------------------------------
// CheckoutSuccessBanner (internal)
// ---------------------------------------------------------------------------
function CheckoutSuccessBanner({ onDismiss, }) {
    return (_jsxs("div", { role: "status", className: "flex items-center justify-between gap-3 rounded-lg border border-emerald-500/30 bg-emerald-500/5 px-3.5 py-3 text-xs text-emerald-700 dark:text-emerald-300", children: [_jsxs("p", { children: [_jsx("span", { className: "font-medium", children: "Payment received" }), " \u2014 ", "credits will appear in your balance shortly."] }), onDismiss && (_jsx("button", { type: "button", onClick: onDismiss, className: "shrink-0 rounded p-0.5 transition-colors hover:bg-emerald-500/10", "aria-label": "Dismiss", children: _jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M18 6 6 18" }), _jsx("path", { d: "m6 6 12 12" })] }) }))] }));
}
//# sourceMappingURL=BillingSection.js.map