Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

35.6 KB
Raw Blame
import { TabIcon } from '@/components/ui/TabIcon'
import { ResourceErrorState, ResourceErrorNotice } from '@/components/ResourceLayout'
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import { AutomaticTopUp, OrganizationWallet } from '@/billing-api/types/OrganizationWallet'
import { AsciiButton, AsciiChip, BRAND, Panel, PanelNote, SectionTitle, SegmentedBar } from '@/components/ascii'
import { BalanceThresholdBanner } from '@/components/billing/BalanceLowBanner'
import { DEFAULT_PAGE_SIZE } from '@/constants/Pagination'
import { InvoicesTable } from '@/components/Invoices'
import { WalletTransactionsTable } from '@/components/WalletTransactions'
import { Input } from '@/components/ui/input'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Skeleton } from '@/components/ui/skeleton'
import { Spinner } from '@/components/ui/spinner'
import { useRedeemCouponMutation } from '@/hooks/mutations/useRedeemCouponMutation'
import { useRemovePaymentMethodMutation } from '@/hooks/mutations/useRemovePaymentMethodMutation'
import { useSetDefaultPaymentMethodMutation } from '@/hooks/mutations/useSetDefaultPaymentMethodMutation'
import { useSetAutomaticTopUpMutation } from '@/hooks/mutations/useSetAutomaticTopUpMutation'
import { useTopUpWalletMutation } from '@/hooks/mutations/useTopUpWalletMutation'
import { useConnectCard } from '@/hooks/useConnectCard'
import {
  useOwnerBillingPortalUrlQuery,
  useOwnerInvoicesQuery,
  useOwnerPaymentMethodsQuery,
  useOwnerPlanQuery,
  useOwnerWalletTransactionsQuery,
  useOwnerWalletQuery,
} from '@/hooks/queries/billingQueries'
import { useOrganizations } from '@/hooks/useOrganizations'
import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'
import { cn, formatAmount } from '@/lib/utils'
import { ArrowUpRight } from '@/components/ui/icon'
import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { NumericFormat } from 'react-number-format'
import { useAuth } from 'react-oidc-context'
import { toast } from 'sonner'
import { PaymentMethodsPanel } from './PaymentMethodsPanel'
import { WalletCouponClaim } from './WalletCouponClaim'

/** Commerce rejects anything smaller, so the form says so before the round trip. */
export const MIN_TOP_UP_DOLLARS = 10

/**
 * What an unconfigured auto-reload starts at, so switching it on is one click
 * rather than a policy decision the user has to invent.
 */
const DEFAULT_AUTO_RELOAD: AutomaticTopUp = { thresholdAmount: 20, targetAmount: 100 }

/**
 * Validates whether a top-up amount meets requirements.
 * Whether Top up can run, and why not when it cannot.
 *
 * @param amountDollars - The amount in dollars to validate, or undefined
 * @returns Object with enabled flag and optional reason string when disabled
 */
export function topUpGate(amountDollars: number | undefined): { enabled: boolean; reason: string | null } {
  if (!amountDollars) {
    return { enabled: false, reason: null }
  }
  if (amountDollars < MIN_TOP_UP_DOLLARS) {
    return { enabled: false, reason: `Minimum top-up is $${MIN_TOP_UP_DOLLARS}.` }
  }
  return { enabled: true, reason: null }
}

/** No discount on the multiplier's numeric(5,4) grid, where basis points are exact. */
const LIST_PRICE_BASIS_POINTS = 10_000

/**
 * The whole percent a top-up is discounted by, read from the wallet's
 * multiplier: `'0.7000'` → `'30%'`. Fractions round down (`'0.8765'` →
 * `'12%'`), so the label never exceeds the rate and never outgrows the
 * ribbon. Integer basis points keep `'0.8000'` at 20%, where float math gives
 * 19%. `null` means nothing to show: no discount, one under 1%, or a value
 * outside (0, 1).
 */
export function topUpDiscountPercent(wallet: Pick<OrganizationWallet, 'usageChargeMultiplier'>): string | null {
  const match = /^(\d+)(?:\.(\d{1,4}))?$/.exec(wallet.usageChargeMultiplier ?? '')
  if (!match) {
    return null
  }
  const paysBasisPoints = Number(match[1]) * LIST_PRICE_BASIS_POINTS + Number((match[2] ?? '').padEnd(4, '0'))
  if (paysBasisPoints < 1 || paysBasisPoints >= LIST_PRICE_BASIS_POINTS) {
    return null
  }
  const offPercent = Math.floor((LIST_PRICE_BASIS_POINTS - paysBasisPoints) / 100)
  return offPercent > 0 ? `${offPercent}%` : null
}

/**
 * Ensures the current page stays within valid bounds when total pages change.
 * Keep the requested page inside a total that shrinks under it.
 *
 * @param page - Current page number
 * @param totalPages - Total number of available pages
 * @param setPage - Function to update the page number
 */
function useClampPage(page: number, totalPages: number, setPage: (page: number) => void) {
  useEffect(() => {
    if (totalPages > 0 && page > totalPages) {
      setPage(totalPages)
    }
  }, [page, totalPages, setPage])
}

/**
 * Renders pagination controls for navigating between pages.
 * Hidden on the first page when no further pages are known. Later pages retain
 * Previous during failed requests, when the total is temporarily unknown.
 *
 * @param props - Component props
 * @param props.page - Current page number
 * @param props.totalPages - Total number of pages
 * @param props.onPage - Callback to update page number, receives updater function
 * @returns Pagination controls or null if not needed
 */
function Pager({
  page,
  totalPages,
  onPage,
}: {
  page: number
  totalPages: number
  onPage: (next: (current: number) => number) => void
}) {
  if (totalPages <= 1 && page <= 1) {
    return null
  }

  return (
    <div className="flex items-center justify-end gap-3 border-b border-border/40 py-3 font-sans text-meta text-muted-foreground">
      <span>
        Page {page}
        {totalPages > 0 && ` of ${totalPages}`}
      </span>
      <AsciiButton onClick={() => onPage((current) => Math.max(1, current - 1))} disabled={page <= 1}>
        ← Previous
      </AsciiButton>
      <AsciiButton onClick={() => onPage((current) => Math.min(totalPages, current + 1))} disabled={page >= totalPages}>
        Next →
      </AsciiButton>
    </div>
  )
}

/**
 * The two money histories, as peers under one tab strip.
 *
 * They were stacked: billing history, then a folded credit ledger under it.
 * Each holds 25 rows a page, so whichever came first pushed the other off the
 * screen, and the fold — added so a grant would not be read as a charge —
 * buried the ledger where nothing suggested it existed.
 *
 * Tabs answer both. Only one table is ever on screen, so neither crowds the
 * other, and a grant can never sit beside a charge at equal weight — a
 * stronger separation than the fold gave, since a fold could be opened. Each
 * label carries its own size, so the ledger announces itself without being
 * opened.
 */
function MoneyHistorySection() {
  const [tab, setTab] = useState('invoices')

  const [invoicePage, setInvoicePage] = useState(1)
  const invoicesQuery = useOwnerInvoicesQuery(invoicePage, DEFAULT_PAGE_SIZE)
  const invoiceTotalPages = invoicesQuery.data?.totalPages ?? 0
  useClampPage(invoicePage, invoiceTotalPages, setInvoicePage)

  const [creditPage, setCreditPage] = useState(1)
  const transactionsQuery = useOwnerWalletTransactionsQuery(creditPage, DEFAULT_PAGE_SIZE)
  const creditTotalPages = transactionsQuery.data?.totalPages ?? 0
  useClampPage(creditPage, creditTotalPages, setCreditPage)

  return (
    <section>
      <Tabs value={tab} onValueChange={setTab} className="w-full gap-0">
        <TabsList variant="underline" aria-label="Payment history">
          <TabsTrigger value="invoices">
            <TabIcon name="document" />
            Billing history
            <Count value={invoicesQuery.data?.totalItems} />
          </TabsTrigger>
          <TabsTrigger value="credits">
            <TabIcon name="credits" />
            Credit activity
            <Count value={transactionsQuery.data?.totalItems} />
          </TabsTrigger>
        </TabsList>

        <TabsContent value="invoices" className="mt-5">
          {invoicesQuery.isError && invoicesQuery.data === undefined ? (
            <ResourceErrorState
              title="Could not load billing history"
              retrying={invoicesQuery.isFetching}
              onRetry={() => void invoicesQuery.refetch()}
            />
          ) : (
            <>
              {invoicesQuery.isError && (
                <ResourceErrorNotice
                  title="Could not refresh billing history. Showing previously loaded data."
                  retrying={invoicesQuery.isFetching}
                  onRetry={() => void invoicesQuery.refetch()}
                />
              )}
              <InvoicesTable data={invoicesQuery.data?.items ?? []} loading={invoicesQuery.isLoading} />
            </>
          )}
          <Pager page={invoicePage} totalPages={invoiceTotalPages} onPage={setInvoicePage} />
          <PanelNote>Amounts charged to your payment method.</PanelNote>
        </TabsContent>

        <TabsContent value="credits" className="mt-5">
          {transactionsQuery.isError && transactionsQuery.data === undefined ? (
            <ResourceErrorState
              title="Could not load credit activity"
              retrying={transactionsQuery.isFetching}
              onRetry={() => void transactionsQuery.refetch()}
            />
          ) : (
            <>
              {transactionsQuery.isError && (
                <ResourceErrorNotice
                  title="Could not refresh credit activity. Showing previously loaded data."
                  retrying={transactionsQuery.isFetching}
                  onRetry={() => void transactionsQuery.refetch()}
                />
              )}
              <WalletTransactionsTable
                data={transactionsQuery.data?.items ?? []}
                loading={transactionsQuery.isLoading}
              />
            </>
          )}
          <Pager page={creditPage} totalPages={creditTotalPages} onPage={setCreditPage} />
          {/* Says what these are, which is the job the fold used to do badly:
              quota granted, not money taken. */}
          <PanelNote>Credit grants and expiries. These are quota, not charges against your card.</PanelNote>
        </TabsContent>
      </Tabs>
    </section>
  )
}

/** A tab's own size, so neither history has to be opened to be sized up. */
function Count({ value }: { value?: number }) {
  if (value === undefined) {
    return null
  }
  return <span className="ml-2 font-normal tabular-nums text-muted-foreground">{value}</span>
}

/**
 * Main wallet section component displaying balance, payment methods, billing history, and credit activity.
 * Manages state for top-ups, auto-reload settings, and coupon redemption.
 *
 * @param linkCouponCode - Reward code provided by the shareable coupon link.
 * @param onCouponClaimAccepted - Removes the accepted reward code from the URL.
 * @returns The complete wallet section component
 */
export function WalletSection({
  linkCouponCode,
  onCouponClaimAccepted,
}: { linkCouponCode?: string; onCouponClaimAccepted?: () => void } = {}) {
  const {
    selectedOrganization,
    authenticatedUserOrganizationMember,
    organizationMembersStatus,
    refreshOrganizationMembers,
  } = useSelectedOrganization()
  const { organizations } = useOrganizations()
  const { user } = useAuth()
  const [automaticTopUp, setAutomaticTopUp] = useState<AutomaticTopUp | undefined>(undefined)
  const [couponCode, setCouponCode] = useState('')
  const [redeemCouponError, setRedeemCouponError] = useState<string | null>(null)
  const [redeemCouponSuccess, setRedeemCouponSuccess] = useState<string | null>(null)
  const [oneTimeTopUpAmount, setOneTimeTopUpAmount] = useState<number | undefined>(undefined)
  const [selectedPreset, setSelectedPreset] = useState<number | null>(100)
  // Both are folded by default: one is a setting you touch once, the other a
  // one-shot action. Neither earns six rows of the panel on every visit.
  const [autoReloadOpen, setAutoReloadOpen] = useState(false)
  const [couponOpen, setCouponOpen] = useState(false)
  const walletQuery = useOwnerWalletQuery({ refetchOnMount: 'always' })
  const billingPortalUrlQuery = useOwnerBillingPortalUrlQuery()
  const paymentMethodsQuery = useOwnerPaymentMethodsQuery()
  const planQuery = useOwnerPlanQuery()

  const { connectCard, isPending: isCheckoutUrlLoading } = useConnectCard()
  const wallet = walletQuery.data
  const billingPortalUrl = billingPortalUrlQuery.data
  const setAutomaticTopUpMutation = useSetAutomaticTopUpMutation()
  const redeemCouponMutation = useRedeemCouponMutation()
  const topUpWalletMutation = useTopUpWalletMutation()
  const setDefaultPaymentMethodMutation = useSetDefaultPaymentMethodMutation()
  const removePaymentMethodMutation = useRemovePaymentMethodMutation()

  useEffect(() => {
    if (!wallet) {
      return
    }
    setAutomaticTopUp(wallet.automaticTopUp ?? DEFAULT_AUTO_RELOAD)
  }, [wallet])

  const handleSetAutomaticTopUp = useCallback(async () => {
    if (!selectedOrganization) {
      return
    }

    try {
      await setAutomaticTopUpMutation.mutateAsync({
        organizationId: selectedOrganization.id,
        automaticTopUp,
      })
      toast.success('Automatic top up set successfully')
    } catch (error) {
      toast.error('Failed to set automatic top up', {
        description: String(error),
      })
    }
  }, [selectedOrganization, automaticTopUp, setAutomaticTopUpMutation])

  const handleSetDefaultPaymentMethod = useCallback(
    async (paymentMethodId: string) => {
      if (!selectedOrganization) {
        return
      }

      try {
        await setDefaultPaymentMethodMutation.mutateAsync({ organizationId: selectedOrganization.id, paymentMethodId })
      } catch (error) {
        toast.error('Failed to set the default card', { description: String(error) })
      }
    },
    [selectedOrganization, setDefaultPaymentMethodMutation],
  )

  const handleRemovePaymentMethod = useCallback(
    async (paymentMethodId: string) => {
      if (!selectedOrganization) {
        return
      }

      try {
        await removePaymentMethodMutation.mutateAsync({ organizationId: selectedOrganization.id, paymentMethodId })
      } catch (error) {
        toast.error('Failed to remove the card', { description: String(error) })
      }
    },
    [selectedOrganization, removePaymentMethodMutation],
  )

  const handleRedeemCoupon = useCallback(async () => {
    if (!selectedOrganization || !couponCode) {
      return
    }

    setRedeemCouponError(null)
    setRedeemCouponSuccess(null)

    try {
      const message = await redeemCouponMutation.mutateAsync({
        organizationId: selectedOrganization.id,
        couponCode,
      })
      setRedeemCouponSuccess(message)
      setTimeout(() => {
        setRedeemCouponSuccess(null)
      }, 3000)
      toast.success(message)
      setCouponCode('')
    } catch (error) {
      setRedeemCouponError(String(error))
      toast.error(`Coupon ${couponCode} was not redeemed`, { description: String(error) })
      console.error('Failed to redeem coupon:', error)
    }
  }, [selectedOrganization, couponCode, redeemCouponMutation])

  const saveAutomaticTopUpDisabled = useMemo(() => {
    if (setAutomaticTopUpMutation.isPending) {
      return true
    }

    if (automaticTopUp?.thresholdAmount !== wallet?.automaticTopUp?.thresholdAmount) {
      if (!wallet?.automaticTopUp) {
        if ((automaticTopUp?.thresholdAmount || 0) !== 0) {
          return false
        }
      } else {
        return false
      }
    }

    if (automaticTopUp?.targetAmount !== wallet?.automaticTopUp?.targetAmount) {
      if (!wallet?.automaticTopUp) {
        if ((automaticTopUp?.targetAmount || 0) !== 0) {
          return false
        }
      } else {
        return false
      }
    }

    return true
  }, [setAutomaticTopUpMutation.isPending, wallet, automaticTopUp])

  const handleTopUpWallet = useCallback(async () => {
    if (!selectedOrganization) {
      return
    }
    const amount = selectedPreset ?? oneTimeTopUpAmount
    if (!amount) {
      return
    }

    const newWindow = window.open('', '_blank')
    try {
      const result = await topUpWalletMutation.mutateAsync({
        organizationId: selectedOrganization.id,
        amountCents: Math.round(amount * 100),
      })
      if (newWindow) {
        newWindow.location.href = result.url
      }
    } catch (error) {
      newWindow?.close()
      toast.error('Failed to initiate top-up', {
        description: String(error),
      })
    }
  }, [selectedOrganization, selectedPreset, oneTimeTopUpAmount, topUpWalletMutation])

  const isBillingLoading = walletQuery.isLoading && billingPortalUrlQuery.isLoading
  const cardConnected = Boolean(wallet?.creditCardConnected)
  const topUp = topUpGate(selectedPreset ?? oneTimeTopUpAmount)
  const topUpDiscount = wallet ? topUpDiscountPercent(wallet) : null
  // Read the indicator off the saved wallet, not the form: the form is
  // pre-filled with defaults, which would otherwise read as already on.
  const autoReloadActive =
    (wallet?.automaticTopUp?.thresholdAmount ?? 0) > 0 || (wallet?.automaticTopUp?.targetAmount ?? 0) > 0

  return (
    <div className="flex flex-col gap-8">
      {linkCouponCode && !user?.profile.email_verified && (
        <Panel className="px-[22px] py-4">Verify your email to claim coupon code {linkCouponCode}.</Panel>
      )}
      {linkCouponCode && user?.profile.email_verified && organizationMembersStatus === 'error' && (
        <Panel className="flex flex-wrap items-center justify-between gap-3 px-[22px] py-4">
          <p role="alert">Couldn’t verify your organization role.</p>
          <AsciiButton onClick={() => void refreshOrganizationMembers().catch(() => undefined)}>
            Retry verification
          </AsciiButton>
        </Panel>
      )}
      {user?.profile.email_verified &&
        organizationMembersStatus === 'ready' &&
        (selectedOrganization &&
        user.profile.sub &&
        authenticatedUserOrganizationMember?.role === OrganizationUserRoleEnum.OWNER ? (
          <WalletCouponClaim
            key={JSON.stringify([user.profile.sub, selectedOrganization.id])}
            accountId={user.profile.sub}
            organizationId={selectedOrganization.id}
            organizationName={selectedOrganization.name}
            code={linkCouponCode}
            automatic={organizations.length === 1 && organizations[0].id === selectedOrganization.id}
            cardConnected={walletQuery.isPlaceholderData ? undefined : wallet?.creditCardConnected}
            connectCard={connectCard}
            connectingCard={isCheckoutUrlLoading}
            onAccepted={onCouponClaimAccepted}
          />
        ) : (
          linkCouponCode && <Panel className="px-[22px] py-4">Only an organization owner can claim this reward.</Panel>
        ))}
      {isBillingLoading && (
        <div className="flex flex-col gap-8">
          <div className="flex flex-col gap-4 border border-border bg-card p-[22px]">
            <Skeleton className="h-5 w-full max-w-sm" />
            <div className="flex items-center gap-2">
              <Skeleton className="h-10 flex-1" />
              <Skeleton className="h-10 flex-1" />
            </div>
            <Skeleton className="h-10" />
            <Skeleton className="h-10" />
          </div>
          <div className="flex flex-col gap-4 border border-border bg-card p-[22px]">
            <Skeleton className="h-5 w-full max-w-sm" />
            <div className="flex items-center gap-2">
              <Skeleton className="h-10 flex-1" />
              <Skeleton className="h-10 flex-1" />
            </div>
            <Skeleton className="h-10" />
          </div>
        </div>
      )}

      {wallet && (
        <div className="flex flex-col gap-8">
          <PaymentMethodsPanel
            paymentMethods={paymentMethodsQuery.data ?? []}
            isLoading={paymentMethodsQuery.isLoading}
            isError={paymentMethodsQuery.isError}
            isAddLoading={isCheckoutUrlLoading}
            onAdd={connectCard}
            onSetDefault={handleSetDefaultPaymentMethod}
            onRemove={handleRemovePaymentMethod}
          />

          <section>
            <SectionTitle title="Wallet Balance" />
            <Panel className="px-[22px] py-5">
              <div className="flex items-baseline gap-3">
                <span className="font-mono text-page font-semibold leading-none tracking-tight tabular-nums text-foreground">
                  {formatAmount(wallet.ongoingBalanceCents)}
                </span>
                <span className="font-sans text-meta text-muted-foreground">available</span>
              </div>

              <div className="mt-4">
                {/* Only when a grant exists. A $0.00 / $0.00 row is not a fact
                    about promotional credit, it is the absence of one. */}
                {(wallet.creditGrantedCents ?? 0) > 0 && (
                  <>
                    <div className="mb-1.5 flex items-center justify-between font-sans text-label uppercase tracking-[1px] text-muted-foreground">
                      <span>Promotional credit remaining</span>
                      <span className="font-mono tabular-nums">
                        {formatAmount(wallet.creditRemainingCents ?? 0)} /{' '}
                        {formatAmount(wallet.creditGrantedCents ?? 0)}
                      </span>
                    </div>
                    {/* Fill the spent part, not the remaining one: SegmentedBar
                        turns amber past 80% and red past 90%, so passing the
                        remainder painted a freshly granted, untouched credit red. */}
                    <SegmentedBar
                      used={Math.max(0, (wallet.creditGrantedCents ?? 0) - (wallet.creditRemainingCents ?? 0))}
                      limit={wallet.creditGrantedCents ?? 0}
                    />
                  </>
                )}
                {billingPortalUrlQuery.isLoading ? (
                  <Skeleton className="mt-2 h-4 w-[180px]" />
                ) : billingPortalUrl ? (
                  <a
                    href={`${billingPortalUrl}/customer-edit-information`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-2 inline-flex items-center gap-1.5 font-sans text-meta text-muted-foreground transition-colors hover:text-foreground"
                  >
                    Payment history &amp; billing info
                    <ArrowUpRight className="size-3.5" />
                  </a>
                ) : null}
              </div>

              <div className="my-5 h-px bg-border" />

              {/* Add funds — presets, custom amount and the action all on one row */}
              <span className="font-sans text-label uppercase tracking-[1.5px] text-muted-foreground">Add funds</span>
              <div className="mt-3 flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center">
                <div className="grid grid-cols-2 gap-2 sm:contents">
                  {[25, 100, 500, 1000].map((amount) => (
                    <AsciiChip
                      key={amount}
                      selected={selectedPreset === amount}
                      onClick={() => {
                        setSelectedPreset(amount)
                        setOneTimeTopUpAmount(undefined)
                      }}
                    >
                      ${amount.toLocaleString()}
                    </AsciiChip>
                  ))}
                </div>
                <span className="inline-flex items-center border border-border px-3 py-2 font-mono text-body transition-colors focus-within:border-brand hover:border-brand">
                  <span className="text-muted-foreground">$</span>
                  <NumericFormat
                    id="customTopUpAmount"
                    placeholder="custom"
                    inputMode="decimal"
                    thousandSeparator
                    decimalScale={2}
                    value={oneTimeTopUpAmount ?? ''}
                    onValueChange={({ floatValue }) => {
                      const value = floatValue ?? undefined
                      setOneTimeTopUpAmount(value)
                      setSelectedPreset(null)
                    }}
                    onFocus={() => {
                      setSelectedPreset(null)
                    }}
                    className="w-full bg-transparent pl-1 tabular-nums text-foreground outline-none placeholder:text-muted-foreground sm:w-[86px]"
                  />
                </span>
                <div className="relative w-full sm:ml-auto sm:w-auto">
                  <AsciiButton
                    variant="primary"
                    data-console-action="top_up_wallet"
                    onClick={handleTopUpWallet}
                    disabled={!topUp.enabled || topUpWalletMutation.isPending}
                    className={cn('inline-flex w-full items-center justify-center gap-2', topUpDiscount && 'pr-14')}
                  >
                    {topUpWalletMutation.isPending && <Spinner />}
                    Top up →
                  </AsciiButton>
                  {/* A sash across the button's right end. Its own box clips
                      it to the button, so the wrapper clips nothing and the
                      button's focus outline stays whole. It sits beside the
                      button rather than inside it, so the button's name stays
                      "Top up →", and clicks pass through it. At 35° the
                      longest label, "99% OFF" (~42px), stands ~32px tall,
                      inside the 33px button; at 45° it would stand 37px and
                      lose its ends. pr-14 keeps the button's label clear of
                      the band. The ink is the light theme's foreground in both
                      themes: white brand-foreground measures 2.49:1 on the
                      brand fill, which does not change with the theme, where
                      this ink measures 7.30:1. */}
                  {topUpDiscount && (
                    <span className="pointer-events-none absolute inset-0 overflow-hidden">
                      <span
                        role="img"
                        aria-label={`${topUpDiscount} off`}
                        className="absolute right-[-12px] top-1/2 w-[80px] -translate-y-1/2 rotate-[35deg] whitespace-nowrap bg-brand py-[2px] text-center font-sans text-label font-bold leading-none tracking-normal text-[hsl(218_17%_9%)]"
                      >
                        {topUpDiscount} OFF
                      </span>
                    </span>
                  )}
                </div>
              </div>
              {topUp.reason && <p className="mt-3 font-sans text-meta leading-relaxed text-warning">{topUp.reason}</p>}
              <PanelNote>
                Minimum ${MIN_TOP_UP_DOLLARS} · you will be redirected to Stripe to complete the payment.
              </PanelNote>

              {/* Auto-reload stays on the page without a card, disabled and
                  labelled: hiding it is why nobody knew it existed, and it is
                  also the only thing that arms the low-balance warning. */}
              <>
                <div className="my-5 h-px bg-border" />

                <button
                  type="button"
                  aria-expanded={autoReloadOpen}
                  aria-controls="auto-reload-settings"
                  onClick={() => setAutoReloadOpen((wasOpen) => !wasOpen)}
                  className="flex w-full items-center gap-2 font-sans text-label uppercase tracking-[1.5px] text-muted-foreground transition-colors hover:text-foreground"
                >
                  <span style={{ color: BRAND }}>{autoReloadOpen ? '▾' : '▸'}</span>
                  Auto-reload
                  <span
                    className="size-[6px] rounded-full"
                    style={{ background: autoReloadActive ? BRAND : 'hsl(var(--muted-foreground))' }}
                  />
                  {/* Folded, the row still answers the only question it is asked:
                      is it on, and at what numbers. */}
                  <span className="ml-auto normal-case tracking-normal">
                    {autoReloadActive && wallet.automaticTopUp
                      ? `Below $${wallet.automaticTopUp.thresholdAmount.toFixed(2)} → $${wallet.automaticTopUp.targetAmount.toFixed(2)}`
                      : 'Off'}
                  </span>
                </button>

                {autoReloadOpen && (
                  <div id="auto-reload-settings" className="mt-3 flex flex-wrap items-center justify-between gap-3">
                    <div className="flex flex-col gap-1.5">
                      <div className="flex flex-wrap items-center gap-2 font-mono text-body text-foreground">
                        <span className="font-sans">when balance &lt;</span>
                        <span className="inline-flex items-center border border-border px-2 py-1 transition-colors focus-within:border-brand">
                          <span className="text-muted-foreground">$</span>
                          <NumericFormat
                            id="thresholdAmount"
                            disabled={!cardConnected}
                            placeholder="0.00"
                            inputMode="decimal"
                            thousandSeparator
                            decimalScale={2}
                            value={automaticTopUp?.thresholdAmount ?? ''}
                            onValueChange={({ floatValue }) => {
                              const value = floatValue ?? 0

                              let targetAmount = automaticTopUp?.targetAmount ?? 0
                              if (value > targetAmount - 10) {
                                targetAmount = value + 10
                              }

                              setAutomaticTopUp({
                                thresholdAmount: value,
                                targetAmount,
                              })
                            }}
                            className="w-[72px] bg-transparent pl-1 text-right tabular-nums text-foreground outline-none"
                          />
                        </span>
                        <span className="font-sans text-muted-foreground">→ bring to</span>
                        <span className="inline-flex items-center border border-border px-2 py-1 transition-colors focus-within:border-brand">
                          <span className="text-muted-foreground">$</span>
                          <NumericFormat
                            id="targetAmount"
                            disabled={!cardConnected}
                            placeholder="0.00"
                            inputMode="decimal"
                            thousandSeparator
                            decimalScale={2}
                            value={automaticTopUp?.targetAmount ?? ''}
                            onValueChange={({ floatValue }) => {
                              const thresholdAmount = automaticTopUp?.thresholdAmount ?? 0
                              setAutomaticTopUp({
                                thresholdAmount,
                                targetAmount: floatValue ?? 0,
                              })
                            }}
                            onBlur={() => {
                              const thresholdAmount = automaticTopUp?.thresholdAmount ?? 0
                              const currentTarget = automaticTopUp?.targetAmount ?? 0

                              if (currentTarget < thresholdAmount) {
                                setAutomaticTopUp({
                                  thresholdAmount,
                                  targetAmount: thresholdAmount,
                                })
                              }
                            }}
                            className="w-[72px] bg-transparent pl-1 text-right tabular-nums text-foreground outline-none"
                          />
                        </span>
                      </div>
                    </div>
                    <AsciiButton
                      data-console-action="save_auto_top_up"
                      onClick={handleSetAutomaticTopUp}
                      disabled={!cardConnected || saveAutomaticTopUpDisabled || walletQuery.isLoading || !wallet}
                      className="inline-flex items-center gap-2"
                    >
                      {setAutomaticTopUpMutation.isPending && <Spinner />} Save
                    </AsciiButton>
                  </div>
                )}
                {autoReloadOpen &&
                  (cardConnected ? (
                    <PanelNote>Target must be at least $10 above the threshold · set both to 0 to disable</PanelNote>
                  ) : (
                    <p className="mt-3 font-sans text-meta leading-relaxed text-warning">
                      Connect a payment method above to turn auto-reload on. Until it is set, nothing warns you before
                      the balance runs out.
                    </p>
                  ))}
              </>

              <BalanceThresholdBanner wallet={wallet} plan={planQuery.data} />

              {user?.profile.email_verified && (
                <>
                  <div className="my-5 h-px bg-border" />

                  {/* A one-shot action with no state to summarise, so it gets a
                      link rather than a settings row — the checkout convention. */}
                  {!couponOpen ? (
                    <button
                      type="button"
                      onClick={() => setCouponOpen(true)}
                      className="font-sans text-meta text-muted-foreground underline underline-offset-2 transition-colors hover:text-foreground"
                    >
                      Have a coupon code?
                    </button>
                  ) : (
                    <div className="flex flex-wrap items-center justify-between gap-3">
                      <div className="flex flex-col gap-1.5">
                        <span className="font-sans text-label uppercase tracking-[1.5px] text-muted-foreground">
                          Redeem coupon
                        </span>
                        {redeemCouponError ? (
                          <span className="font-sans text-meta text-destructive">{redeemCouponError}</span>
                        ) : redeemCouponSuccess ? (
                          <span className="font-sans text-meta text-success">{redeemCouponSuccess}</span>
                        ) : (
                          <span className="font-sans text-meta text-muted-foreground">
                            Credits go to {selectedOrganization?.name ?? 'this organization'}.
                          </span>
                        )}
                      </div>
                      <div className="flex w-full items-center gap-2 sm:w-auto">
                        <Input
                          placeholder="Enter coupon code"
                          value={couponCode}
                          onChange={(e) => setCouponCode(e.target.value)}
                          className="h-9 w-full font-mono text-body sm:w-[200px]"
                        />
                        <AsciiButton
                          data-console-action="redeem_coupon"
                          onClick={handleRedeemCoupon}
                          disabled={redeemCouponMutation.isPending}
                          className="inline-flex shrink-0 items-center gap-2"
                        >
                          {redeemCouponMutation.isPending && <Spinner />} Redeem
                        </AsciiButton>
                      </div>
                    </div>
                  )}
                </>
              )}
            </Panel>
          </section>

          <MoneyHistorySection key={`history-${selectedOrganization?.id ?? 'no-organization'}`} />
        </div>
      )}
    </div>
  )
}